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
) {
38 if (ascii_isdigit(e
[0]))
41 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, an individual assignment
42 * hence cannot be either. Discounting the equal sign and trailing NUL this hence leaves ARG_MAX-2 as
43 * longest possible variable name. */
44 if (n
> (size_t) sysconf(_SC_ARG_MAX
) - 2)
47 for (const char *p
= e
; p
< e
+ n
; p
++)
48 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *p
))
54 bool env_name_is_valid(const char *e
) {
55 return env_name_is_valid_n(e
, strlen_ptr(e
));
58 bool env_value_is_valid(const char *e
) {
62 if (!utf8_is_valid(e
))
65 /* Note that variable *values* may contain control characters, in particular NL, TAB, BS, DEL, ESC…
66 * When printing those variables with show-environment, we'll escape them. Make sure to print
67 * environment variables carefully! */
69 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, an individual assignment
70 * hence cannot be either. Discounting the shortest possible variable name of length 1, the equal
71 * sign and trailing NUL this hence leaves ARG_MAX-3 as longest possible variable value. */
72 if (strlen(e
) > sc_arg_max() - 3)
78 bool env_assignment_is_valid(const char *e
) {
85 if (!env_name_is_valid_n(e
, eq
- e
))
88 if (!env_value_is_valid(eq
+ 1))
91 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, hence the individual
92 * variable assignments cannot be either, but let's leave room for one trailing NUL byte. */
93 if (strlen(e
) > sc_arg_max() - 1)
99 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
) {
118 if (!env_name_is_valid(*p
))
121 if (strv_contains(p
+ 1, *p
))
128 bool strv_env_name_or_assignment_is_valid(char **l
) {
130 if (!env_assignment_is_valid(*p
) && !env_name_is_valid(*p
))
133 if (strv_contains(p
+ 1, *p
))
140 static int env_append(char **e
, char ***k
, char **a
) {
148 /* Expects the following arguments: 'e' shall point to the beginning of an strv we are going to append to, 'k'
149 * to a pointer pointing to the NULL entry at the end of the same array. 'a' shall point to another strv.
151 * This call adds every entry of 'a' to 'e', either overriding an existing matching entry, or appending to it.
153 * This call assumes 'e' has enough pre-allocated space to grow by all of 'a''s items. */
159 n
= strcspn(*a
, "=");
163 for (j
= e
; j
< *k
; j
++)
164 if (strneq(*j
, *a
, n
))
171 if (j
>= *k
) { /* Append to the end? */
176 free_and_replace(*j
, c
); /* Override existing item */
182 char** _strv_env_merge(char **first
, ...) {
183 _cleanup_strv_free_
char **merged
= NULL
;
187 /* Merges an arbitrary number of environment sets */
189 size_t n
= strv_length(first
);
195 l
= va_arg(ap
, char**);
196 if (l
== POINTER_MAX
)
203 k
= merged
= new(char*, n
+ 1);
208 if (env_append(merged
, &k
, first
) < 0)
215 l
= va_arg(ap
, char**);
216 if (l
== POINTER_MAX
)
219 if (env_append(merged
, &k
, l
) < 0) {
226 return TAKE_PTR(merged
);
229 static bool env_match(const char *t
, const char *pattern
) {
233 /* pattern a matches string a
238 * a= does not match a
239 * a=b does not match a=
240 * a=b does not match a
241 * a=b does not match a=c */
243 if (streq(t
, pattern
))
246 if (!strchr(pattern
, '=')) {
247 size_t l
= strlen(pattern
);
249 return strneq(t
, pattern
, l
) && t
[l
] == '=';
255 static bool env_entry_has_name(const char *entry
, const char *name
) {
261 t
= startswith(entry
, name
);
268 char **strv_env_delete(char **x
, size_t n_lists
, ...) {
270 _cleanup_strv_free_
char **t
= NULL
;
273 /* Deletes every entry from x that is mentioned in the other
283 va_start(ap
, n_lists
);
284 for (size_t v
= 0; v
< n_lists
; v
++) {
287 l
= va_arg(ap
, char**);
289 if (env_match(*k
, *j
))
312 char **strv_env_unset(char **l
, const char *p
) {
320 /* Drops every occurrence of the env var setting p in the
321 * string list. Edits in-place. */
323 for (f
= t
= l
; *f
; f
++) {
325 if (env_match(*f
, p
)) {
337 char **strv_env_unset_many(char **l
, ...) {
343 /* Like strv_env_unset() but applies many at once. Edits in-place. */
345 for (f
= t
= l
; *f
; f
++) {
352 while ((p
= va_arg(ap
, const char*))) {
353 if (env_match(*f
, p
)) {
373 int strv_env_replace_consume(char ***l
, char *p
) {
374 const char *t
, *name
;
379 /* Replace first occurrence of the env var or add a new one in the string list. Drop other
380 * occurrences. Edits in-place. Does not copy p and CONSUMES p EVEN ON FAILURE.
382 * p must be a valid key=value assignment. */
390 name
= strndupa_safe(p
, t
- p
);
393 if (env_entry_has_name(*f
, name
)) {
394 free_and_replace(*f
, p
);
395 strv_env_unset(f
+ 1, *f
);
399 /* We didn't find a match, we need to append p or create a new strv */
400 r
= strv_consume(l
, p
);
407 int strv_env_replace_strdup(char ***l
, const char *assignment
) {
408 /* Like strv_env_replace_consume(), but copies the argument. */
410 char *p
= strdup(assignment
);
414 return strv_env_replace_consume(l
, p
);
417 int strv_env_replace_strdup_passthrough(char ***l
, const char *assignment
) {
418 /* Like strv_env_replace_strdup(), but pulls the variable from the environment of
419 * the calling program, if a variable name without value is specified.
423 if (strchr(assignment
, '=')) {
424 if (!env_assignment_is_valid(assignment
))
427 p
= strdup(assignment
);
429 if (!env_name_is_valid(assignment
))
432 /* If we can't find the variable in our environment, we will use
433 * the empty string. This way "passthrough" is equivalent to passing
434 * --setenv=FOO=$FOO in the shell. */
435 p
= strjoin(assignment
, "=", secure_getenv(assignment
));
440 return strv_env_replace_consume(l
, p
);
443 int strv_env_assign(char ***l
, const char *key
, const char *value
) {
444 if (!env_name_is_valid(key
))
447 /* NULL removes assignment, "" creates an empty assignment. */
450 strv_env_unset(*l
, key
);
454 char *p
= strjoin(key
, "=", value
);
458 return strv_env_replace_consume(l
, p
);
461 int _strv_env_assign_many(char ***l
, ...) {
469 const char *key
, *value
;
471 key
= va_arg(ap
, const char *);
475 if (!env_name_is_valid(key
)) {
480 value
= va_arg(ap
, const char *);
482 strv_env_unset(*l
, key
);
486 char *p
= strjoin(key
, "=", value
);
492 r
= strv_env_replace_consume(l
, p
);
503 char *strv_env_get_n(char **l
, const char *name
, size_t k
, ReplaceEnvFlags flags
) {
507 k
= strlen_ptr(name
);
511 STRV_FOREACH_BACKWARDS(i
, l
)
512 if (strneq(*i
, name
, k
) &&
516 if (flags
& REPLACE_ENV_USE_ENVIRONMENT
) {
519 /* Safety check that the name is not overly long, before we do a stack allocation */
520 if (k
> (size_t) sysconf(_SC_ARG_MAX
) - 2)
523 t
= strndupa_safe(name
, k
);
530 char *strv_env_pairs_get(char **l
, const char *name
) {
535 STRV_FOREACH_PAIR(key
, value
, l
)
536 if (streq(*key
, name
))
542 char **strv_env_clean_with_callback(char **e
, void (*invalid_callback
)(const char *p
, void *userdata
), void *userdata
) {
547 bool duplicate
= false;
549 if (!env_assignment_is_valid(*p
)) {
550 if (invalid_callback
)
551 invalid_callback(*p
, userdata
);
556 n
= strcspn(*p
, "=");
557 STRV_FOREACH(q
, p
+ 1)
558 if (strneq(*p
, *q
, n
) && (*q
)[n
] == '=') {
577 static int strv_extend_with_length(char ***l
, const char *s
, size_t n
) {
584 return strv_consume(l
, c
);
587 static int strv_env_get_n_validated(
591 ReplaceEnvFlags flags
,
592 char **ret
, /* points into the env block! do not free! */
593 char ***unset_variables
, /* updated in place */
594 char ***bad_variables
) { /* ditto */
599 assert(l
== 0 || name
);
602 if (env_name_is_valid_n(name
, l
)) {
603 e
= strv_env_get_n(env
, name
, l
, flags
);
604 if (!e
&& unset_variables
) {
605 r
= strv_extend_with_length(unset_variables
, name
, l
);
610 e
= NULL
; /* Resolve invalid variable names the same way as unset ones */
613 r
= strv_extend_with_length(bad_variables
, name
, l
);
623 int replace_env_full(
627 ReplaceEnvFlags flags
,
629 char ***ret_unset_variables
,
630 char ***ret_bad_variables
) {
642 _cleanup_strv_free_
char **unset_variables
= NULL
, **bad_variables
= NULL
;
643 const char *e
, *word
= format
, *test_value
= NULL
; /* test_value is initialized to appease gcc */
644 _cleanup_free_
char *s
= NULL
;
645 char ***pu
, ***pb
, *k
;
646 size_t i
, len
= 0; /* len is initialized to appease gcc */
654 pu
= ret_unset_variables
? &unset_variables
: NULL
;
655 pb
= ret_bad_variables
? &bad_variables
: NULL
;
657 for (e
= format
, i
= 0; *e
&& i
< n
; e
++, i
++)
667 k
= strnappend(s
, word
, e
-word
-1);
671 free_and_replace(s
, k
);
677 } else if (*e
== '$') {
678 k
= strnappend(s
, word
, e
-word
);
682 free_and_replace(s
, k
);
687 } else if (FLAGS_SET(flags
, REPLACE_ENV_ALLOW_BRACELESS
) && strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
688 k
= strnappend(s
, word
, e
-word
-1);
692 free_and_replace(s
, k
);
695 state
= VARIABLE_RAW
;
705 r
= strv_env_get_n_validated(env
, word
+2, e
-word
-2, flags
, &t
, pu
, pb
);
709 if (!strextend(&s
, t
))
715 } else if (*e
== ':') {
716 if (flags
& REPLACE_ENV_ALLOW_EXTENDED
) {
720 /* Treat this as unsupported syntax, i.e. do no replacement */
727 state
= DEFAULT_VALUE
;
729 state
= ALTERNATE_VALUE
;
738 case DEFAULT_VALUE
: /* fall through */
739 case ALTERNATE_VALUE
:
740 assert(flags
& REPLACE_ENV_ALLOW_EXTENDED
);
752 _cleanup_strv_free_
char **u
= NULL
, **b
= NULL
;
753 _cleanup_free_
char *v
= NULL
;
756 r
= strv_env_get_n_validated(env
, word
+2, len
, flags
, &t
, pu
, pb
);
760 if (t
&& state
== ALTERNATE_VALUE
) {
761 r
= replace_env_full(test_value
, e
-test_value
, env
, flags
, &v
, pu
? &u
: NULL
, pb
? &b
: NULL
);
766 } else if (!t
&& state
== DEFAULT_VALUE
) {
767 r
= replace_env_full(test_value
, e
-test_value
, env
, flags
, &v
, pu
? &u
: NULL
, pb
? &b
: NULL
);
774 r
= strv_extend_strv(&unset_variables
, u
, /* filter_duplicates= */ true);
777 r
= strv_extend_strv(&bad_variables
, b
, /* filter_duplicates= */ true);
781 if (!strextend(&s
, t
))
790 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
792 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
795 r
= strv_env_get_n_validated(env
, word
+1, e
-word
-1, flags
, &t
, &unset_variables
, &bad_variables
);
799 if (!strextend(&s
, t
))
809 if (state
== VARIABLE_RAW
) {
812 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
814 r
= strv_env_get_n_validated(env
, word
+1, e
-word
-1, flags
, &t
, &unset_variables
, &bad_variables
);
818 if (!strextend(&s
, t
))
821 } else if (!strextendn(&s
, word
, e
-word
))
824 if (ret_unset_variables
)
825 *ret_unset_variables
= TAKE_PTR(unset_variables
);
826 if (ret_bad_variables
)
827 *ret_bad_variables
= TAKE_PTR(bad_variables
);
835 int replace_env_argv(
839 char ***ret_unset_variables
,
840 char ***ret_bad_variables
) {
842 _cleanup_strv_free_
char **n
= NULL
, **unset_variables
= NULL
, **bad_variables
= NULL
;
846 l
= strv_length(argv
);
852 STRV_FOREACH(i
, argv
) {
853 const char *word
= *i
;
855 /* If $FOO appears as single word, replace it by the split up variable */
856 if (word
[0] == '$' && !IN_SET(word
[1], '{', '$')) {
857 _cleanup_strv_free_
char **m
= NULL
;
858 const char *name
= word
+ 1;
862 if (env_name_is_valid(name
)) {
863 e
= strv_env_get(env
, name
);
865 r
= strv_split_full(&m
, e
, WHITESPACE
, EXTRACT_RELAX
|EXTRACT_UNQUOTE
);
866 else if (ret_unset_variables
)
867 r
= strv_extend(&unset_variables
, name
);
870 } else if (ret_bad_variables
)
871 r
= strv_extend(&bad_variables
, name
);
880 w
= reallocarray(n
, l
+ 1, sizeof(char*));
886 memcpy(n
+ k
, m
, (q
+ 1) * sizeof(char*));
894 _cleanup_strv_free_
char **u
= NULL
, **b
= NULL
;
896 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
897 r
= replace_env_full(
899 /* length= */ SIZE_MAX
,
903 ret_unset_variables
? &u
: NULL
,
904 ret_bad_variables
? &b
: NULL
);
909 r
= strv_extend_strv(&unset_variables
, u
, /* filter_duplicates= */ true);
913 r
= strv_extend_strv(&bad_variables
, b
, /*filter_duplicates= */ true);
918 if (ret_unset_variables
) {
919 strv_uniq(strv_sort(unset_variables
));
920 *ret_unset_variables
= TAKE_PTR(unset_variables
);
922 if (ret_bad_variables
) {
923 strv_uniq(strv_sort(bad_variables
));
924 *ret_bad_variables
= TAKE_PTR(bad_variables
);
931 int getenv_bool(const char *p
) {
938 return parse_boolean(e
);
941 int getenv_bool_secure(const char *p
) {
944 e
= secure_getenv(p
);
948 return parse_boolean(e
);
951 int getenv_uint64_secure(const char *p
, uint64_t *ret
) {
956 e
= secure_getenv(p
);
960 return safe_atou64(e
, ret
);
963 int set_unset_env(const char *name
, const char *value
, bool overwrite
) {
967 return RET_NERRNO(setenv(name
, value
, overwrite
));
969 return RET_NERRNO(unsetenv(name
));
972 int putenv_dup(const char *assignment
, bool override
) {
975 e
= strchr(assignment
, '=');
979 n
= strndupa_safe(assignment
, e
- assignment
);
981 /* This is like putenv(), but uses setenv() so that our memory doesn't become part of environ[]. */
982 return RET_NERRNO(setenv(n
, e
+ 1, override
));
985 int setenv_systemd_exec_pid(bool update_only
) {
986 char str
[DECIMAL_STR_MAX(pid_t
)];
989 /* Update $SYSTEMD_EXEC_PID=pid except when '*' is set for the variable. */
991 e
= secure_getenv("SYSTEMD_EXEC_PID");
992 if (!e
&& update_only
)
995 if (streq_ptr(e
, "*"))
998 xsprintf(str
, PID_FMT
, getpid_cached());
1000 if (setenv("SYSTEMD_EXEC_PID", str
, 1) < 0)
1006 int getenv_path_list(const char *name
, char ***ret_paths
) {
1007 _cleanup_strv_free_
char **l
= NULL
;
1014 e
= secure_getenv(name
);
1018 r
= strv_split_full(&l
, e
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
);
1020 return log_debug_errno(r
, "Failed to parse $%s: %m", name
);
1022 STRV_FOREACH(p
, l
) {
1023 if (!path_is_absolute(*p
))
1024 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1025 "Path '%s' is not absolute, refusing.", *p
);
1027 if (!path_is_normalized(*p
))
1028 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1029 "Path '%s' is not normalized, refusing.", *p
);
1031 if (path_equal(*p
, "/"))
1032 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1033 "Path '%s' is the root fs, refusing.", *p
);
1036 if (strv_isempty(l
))
1037 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1038 "No paths specified, refusing.");
1040 *ret_paths
= TAKE_PTR(l
);
1044 int getenv_steal_erase(const char *name
, char **ret
) {
1045 _cleanup_(erase_and_freep
) char *a
= NULL
;
1050 /* Reads an environment variable, makes a copy of it, erases its memory in the environment block and removes
1051 * it from there. Usecase: reading passwords from the env block (which is a bad idea, but useful for
1052 * testing, and given that people are likely going to misuse this, be thorough) */
1069 if (unsetenv(name
) < 0)