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"
21 #include "syslog-util.h"
24 /* We follow bash for the character set. Different shells have different rules. */
25 #define VALID_BASH_ENV_NAME_CHARS \
29 static bool env_name_is_valid_n(const char *e
, size_t n
) {
39 if (ascii_isdigit(e
[0]))
42 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, an individual assignment
43 * hence cannot be either. Discounting the equal sign and trailing NUL this hence leaves ARG_MAX-2 as
44 * longest possible variable name. */
45 if (n
> (size_t) sysconf(_SC_ARG_MAX
) - 2)
48 for (const char *p
= e
; p
< e
+ n
; p
++)
49 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *p
))
55 bool env_name_is_valid(const char *e
) {
56 return env_name_is_valid_n(e
, strlen_ptr(e
));
59 bool env_value_is_valid(const char *e
) {
63 if (!utf8_is_valid(e
))
66 /* Note that variable *values* may contain control characters, in particular NL, TAB, BS, DEL, ESC…
67 * When printing those variables with show-environment, we'll escape them. Make sure to print
68 * environment variables carefully! */
70 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, an individual assignment
71 * hence cannot be either. Discounting the shortest possible variable name of length 1, the equal
72 * sign and trailing NUL this hence leaves ARG_MAX-3 as longest possible variable value. */
73 if (strlen(e
) > sc_arg_max() - 3)
79 bool env_assignment_is_valid(const char *e
) {
86 if (!env_name_is_valid_n(e
, eq
- e
))
89 if (!env_value_is_valid(eq
+ 1))
92 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, hence the individual
93 * variable assignments cannot be either, but let's leave room for one trailing NUL byte. */
94 if (strlen(e
) > sc_arg_max() - 1)
100 bool strv_env_is_valid(char **e
) {
104 if (!env_assignment_is_valid(*p
))
107 /* Check if there are duplicate assignments */
108 k
= strcspn(*p
, "=");
109 STRV_FOREACH(q
, p
+ 1)
110 if (strneq(*p
, *q
, k
) && (*q
)[k
] == '=')
117 bool strv_env_name_is_valid(char **l
) {
119 if (!env_name_is_valid(*p
))
122 if (strv_contains(p
+ 1, *p
))
129 bool strv_env_name_or_assignment_is_valid(char **l
) {
131 if (!env_assignment_is_valid(*p
) && !env_name_is_valid(*p
))
134 if (strv_contains(p
+ 1, *p
))
141 static int env_append(char **e
, char ***k
, char **a
) {
149 /* Expects the following arguments: 'e' shall point to the beginning of an strv we are going to append to, 'k'
150 * to a pointer pointing to the NULL entry at the end of the same array. 'a' shall point to another strv.
152 * This call adds every entry of 'a' to 'e', either overriding an existing matching entry, or appending to it.
154 * This call assumes 'e' has enough pre-allocated space to grow by all of 'a''s items. */
160 n
= strcspn(*a
, "=");
164 for (j
= e
; j
< *k
; j
++)
165 if (strneq(*j
, *a
, n
))
172 if (j
>= *k
) { /* Append to the end? */
177 free_and_replace(*j
, c
); /* Override existing item */
183 char** _strv_env_merge(char **first
, ...) {
184 _cleanup_strv_free_
char **merged
= NULL
;
188 /* Merges an arbitrary number of environment sets */
190 size_t n
= strv_length(first
);
196 l
= va_arg(ap
, char**);
197 if (l
== POINTER_MAX
)
204 k
= merged
= new(char*, n
+ 1);
209 if (env_append(merged
, &k
, first
) < 0)
216 l
= va_arg(ap
, char**);
217 if (l
== POINTER_MAX
)
220 if (env_append(merged
, &k
, l
) < 0) {
227 return TAKE_PTR(merged
);
230 static bool env_match(const char *t
, const char *pattern
) {
234 /* pattern a matches string a
239 * a= does not match a
240 * a=b does not match a=
241 * a=b does not match a
242 * a=b does not match a=c */
244 if (streq(t
, pattern
))
247 if (!strchr(pattern
, '=')) {
248 t
= startswith(t
, pattern
);
250 return t
&& *t
== '=';
256 static bool env_entry_has_name(const char *entry
, const char *name
) {
262 t
= startswith(entry
, name
);
269 char **strv_env_delete(char **x
, size_t n_lists
, ...) {
271 _cleanup_strv_free_
char **t
= NULL
;
274 /* Deletes every entry from x that is mentioned in the other
284 va_start(ap
, n_lists
);
285 for (size_t v
= 0; v
< n_lists
; v
++) {
288 l
= va_arg(ap
, char**);
290 if (env_match(*k
, *j
))
313 char** strv_env_unset(char **l
, const char *p
) {
319 /* Drops every occurrence of the env var setting p in the
320 * string list. Edits in-place. */
323 for (f
= t
= l
; *f
; f
++) {
324 if (env_match(*f
, p
)) {
336 char** strv_env_unset_many_internal(char **l
, ...) {
340 /* Like strv_env_unset() but applies many at once. Edits in-place. */
343 for (f
= t
= l
; *f
; f
++) {
350 while ((p
= va_arg(ap
, const char*)))
351 if (env_match(*f
, p
)) {
370 int strv_env_replace_consume(char ***l
, char *p
) {
371 const char *t
, *name
;
376 /* Replace first occurrence of the env var or add a new one in the string list. Drop other
377 * occurrences. Edits in-place. Does not copy p and CONSUMES p EVEN ON FAILURE.
379 * p must be a valid key=value assignment. */
387 name
= strndupa_safe(p
, t
- p
);
390 if (env_entry_has_name(*f
, name
)) {
391 free_and_replace(*f
, p
);
392 strv_env_unset(f
+ 1, *f
);
396 /* We didn't find a match, we need to append p or create a new strv */
397 r
= strv_consume(l
, p
);
404 int strv_env_replace_strdup(char ***l
, const char *assignment
) {
405 /* Like strv_env_replace_consume(), but copies the argument. */
407 char *p
= strdup(assignment
);
411 return strv_env_replace_consume(l
, p
);
414 int strv_env_replace_strdup_passthrough(char ***l
, const char *assignment
) {
415 /* Like strv_env_replace_strdup(), but pulls the variable from the environment of
416 * the calling program, if a variable name without value is specified.
420 if (strchr(assignment
, '=')) {
421 if (!env_assignment_is_valid(assignment
))
424 p
= strdup(assignment
);
426 if (!env_name_is_valid(assignment
))
429 /* If we can't find the variable in our environment, we will use
430 * the empty string. This way "passthrough" is equivalent to passing
431 * --setenv=FOO=$FOO in the shell. */
432 p
= strjoin(assignment
, "=", secure_getenv(assignment
));
437 return strv_env_replace_consume(l
, p
);
440 int strv_env_assign(char ***l
, const char *key
, const char *value
) {
441 if (!env_name_is_valid(key
))
444 /* NULL removes assignment, "" creates an empty assignment. */
447 strv_env_unset(*l
, key
);
451 char *p
= strjoin(key
, "=", value
);
455 return strv_env_replace_consume(l
, p
);
458 int strv_env_assignf(char ***l
, const char *key
, const char *valuef
, ...) {
464 if (!env_name_is_valid(key
))
468 strv_env_unset(*l
, key
);
472 _cleanup_free_
char *value
= NULL
;
474 va_start(ap
, valuef
);
475 r
= vasprintf(&value
, valuef
, ap
);
480 char *p
= strjoin(key
, "=", value
);
484 return strv_env_replace_consume(l
, p
);
487 int _strv_env_assign_many(char ***l
, ...) {
495 const char *key
, *value
;
497 key
= va_arg(ap
, const char *);
501 if (!env_name_is_valid(key
)) {
506 value
= va_arg(ap
, const char *);
508 strv_env_unset(*l
, key
);
512 char *p
= strjoin(key
, "=", value
);
518 r
= strv_env_replace_consume(l
, p
);
529 char* strv_env_get_n(char * const *l
, const char *name
, size_t k
, ReplaceEnvFlags flags
) {
537 STRV_FOREACH_BACKWARDS(i
, l
)
538 if (strneq(*i
, name
, k
) && (*i
)[k
] == '=')
539 return (char*) *i
+ k
+ 1;
541 if (flags
& REPLACE_ENV_USE_ENVIRONMENT
) {
544 /* Safety check that the name is not overly long, before we do a stack allocation */
545 if (k
> (size_t) sysconf(_SC_ARG_MAX
) - 2)
548 t
= strndupa_safe(name
, k
);
555 char *strv_env_pairs_get(char **l
, const char *name
) {
560 STRV_FOREACH_PAIR(key
, value
, l
)
561 if (streq(*key
, name
))
567 char **strv_env_clean_with_callback(char **e
, void (*invalid_callback
)(const char *p
, void *userdata
), void *userdata
) {
572 bool duplicate
= false;
574 if (!env_assignment_is_valid(*p
)) {
575 if (invalid_callback
)
576 invalid_callback(*p
, userdata
);
581 n
= strcspn(*p
, "=");
582 STRV_FOREACH(q
, p
+ 1)
583 if (strneq(*p
, *q
, n
) && (*q
)[n
] == '=') {
602 static int strv_extend_with_length(char ***l
, const char *s
, size_t n
) {
609 return strv_consume(l
, c
);
612 static int strv_env_get_n_validated(
616 ReplaceEnvFlags flags
,
617 char **ret
, /* points into the env block! do not free! */
618 char ***unset_variables
, /* updated in place */
619 char ***bad_variables
) { /* ditto */
624 assert(l
== 0 || name
);
627 if (env_name_is_valid_n(name
, l
)) {
628 e
= strv_env_get_n(env
, name
, l
, flags
);
629 if (!e
&& unset_variables
) {
630 r
= strv_extend_with_length(unset_variables
, name
, l
);
635 e
= NULL
; /* Resolve invalid variable names the same way as unset ones */
638 r
= strv_extend_with_length(bad_variables
, name
, l
);
648 int replace_env_full(
652 ReplaceEnvFlags flags
,
654 char ***ret_unset_variables
,
655 char ***ret_bad_variables
) {
667 _cleanup_strv_free_
char **unset_variables
= NULL
, **bad_variables
= NULL
;
668 const char *e
, *word
= format
, *test_value
= NULL
; /* test_value is initialized to appease gcc */
669 _cleanup_free_
char *s
= NULL
;
670 char ***pu
, ***pb
, *k
;
671 size_t i
, len
= 0; /* len is initialized to appease gcc */
679 pu
= ret_unset_variables
? &unset_variables
: NULL
;
680 pb
= ret_bad_variables
? &bad_variables
: NULL
;
682 for (e
= format
, i
= 0; *e
&& i
< n
; e
++, i
++)
692 k
= strnappend(s
, word
, e
-word
-1);
696 free_and_replace(s
, k
);
702 } else if (*e
== '$') {
703 k
= strnappend(s
, word
, e
-word
);
707 free_and_replace(s
, k
);
712 } else if (FLAGS_SET(flags
, REPLACE_ENV_ALLOW_BRACELESS
) && strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
713 k
= strnappend(s
, word
, e
-word
-1);
717 free_and_replace(s
, k
);
720 state
= VARIABLE_RAW
;
730 r
= strv_env_get_n_validated(env
, word
+2, e
-word
-2, flags
, &t
, pu
, pb
);
734 if (!strextend(&s
, t
))
740 } else if (*e
== ':') {
741 if (flags
& REPLACE_ENV_ALLOW_EXTENDED
) {
745 /* Treat this as unsupported syntax, i.e. do no replacement */
752 state
= DEFAULT_VALUE
;
754 state
= ALTERNATE_VALUE
;
763 case DEFAULT_VALUE
: /* fall through */
764 case ALTERNATE_VALUE
:
765 assert(flags
& REPLACE_ENV_ALLOW_EXTENDED
);
777 _cleanup_strv_free_
char **u
= NULL
, **b
= NULL
;
778 _cleanup_free_
char *v
= NULL
;
781 r
= strv_env_get_n_validated(env
, word
+2, len
, flags
, &t
, pu
, pb
);
785 if (t
&& state
== ALTERNATE_VALUE
) {
786 r
= replace_env_full(test_value
, e
-test_value
, env
, flags
, &v
, pu
? &u
: NULL
, pb
? &b
: NULL
);
791 } else if (!t
&& state
== DEFAULT_VALUE
) {
792 r
= replace_env_full(test_value
, e
-test_value
, env
, flags
, &v
, pu
? &u
: NULL
, pb
? &b
: NULL
);
799 r
= strv_extend_strv(&unset_variables
, u
, /* filter_duplicates= */ true);
802 r
= strv_extend_strv(&bad_variables
, b
, /* filter_duplicates= */ true);
806 if (!strextend(&s
, t
))
815 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
817 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
820 r
= strv_env_get_n_validated(env
, word
+1, e
-word
-1, flags
, &t
, &unset_variables
, &bad_variables
);
824 if (!strextend(&s
, t
))
834 if (state
== VARIABLE_RAW
) {
837 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
839 r
= strv_env_get_n_validated(env
, word
+1, e
-word
-1, flags
, &t
, &unset_variables
, &bad_variables
);
843 if (!strextend(&s
, t
))
846 } else if (!strextendn(&s
, word
, e
-word
))
849 if (ret_unset_variables
)
850 *ret_unset_variables
= TAKE_PTR(unset_variables
);
851 if (ret_bad_variables
)
852 *ret_bad_variables
= TAKE_PTR(bad_variables
);
860 int replace_env_argv(
864 char ***ret_unset_variables
,
865 char ***ret_bad_variables
) {
867 _cleanup_strv_free_
char **n
= NULL
, **unset_variables
= NULL
, **bad_variables
= NULL
;
871 l
= strv_length(argv
);
877 STRV_FOREACH(i
, argv
) {
878 const char *word
= *i
;
880 /* If $FOO appears as single word, replace it by the split up variable */
881 if (word
[0] == '$' && !IN_SET(word
[1], '{', '$')) {
882 _cleanup_strv_free_
char **m
= NULL
;
883 const char *name
= word
+ 1;
887 if (env_name_is_valid(name
)) {
888 e
= strv_env_get(env
, name
);
890 r
= strv_split_full(&m
, e
, WHITESPACE
, EXTRACT_RELAX
|EXTRACT_UNQUOTE
);
891 else if (ret_unset_variables
)
892 r
= strv_extend(&unset_variables
, name
);
895 } else if (ret_bad_variables
)
896 r
= strv_extend(&bad_variables
, name
);
905 w
= reallocarray(n
, l
+ 1, sizeof(char*));
911 memcpy(n
+ k
, m
, (q
+ 1) * sizeof(char*));
919 _cleanup_strv_free_
char **u
= NULL
, **b
= NULL
;
921 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
922 r
= replace_env_full(
924 /* length= */ SIZE_MAX
,
928 ret_unset_variables
? &u
: NULL
,
929 ret_bad_variables
? &b
: NULL
);
934 r
= strv_extend_strv(&unset_variables
, u
, /* filter_duplicates= */ true);
938 r
= strv_extend_strv(&bad_variables
, b
, /*filter_duplicates= */ true);
943 if (ret_unset_variables
) {
944 strv_uniq(strv_sort(unset_variables
));
945 *ret_unset_variables
= TAKE_PTR(unset_variables
);
947 if (ret_bad_variables
) {
948 strv_uniq(strv_sort(bad_variables
));
949 *ret_bad_variables
= TAKE_PTR(bad_variables
);
956 int getenv_bool(const char *p
) {
963 return parse_boolean(e
);
966 int getenv_bool_secure(const char *p
) {
969 e
= secure_getenv(p
);
973 return parse_boolean(e
);
976 int getenv_uint64_secure(const char *p
, uint64_t *ret
) {
981 e
= secure_getenv(p
);
985 return safe_atou64(e
, ret
);
988 int set_unset_env(const char *name
, const char *value
, bool overwrite
) {
992 return RET_NERRNO(setenv(name
, value
, overwrite
));
994 return RET_NERRNO(unsetenv(name
));
997 int putenv_dup(const char *assignment
, bool override
) {
1000 e
= strchr(assignment
, '=');
1004 n
= strndupa_safe(assignment
, e
- assignment
);
1006 /* This is like putenv(), but uses setenv() so that our memory doesn't become part of environ[]. */
1007 return RET_NERRNO(setenv(n
, e
+ 1, override
));
1010 int setenv_systemd_exec_pid(bool update_only
) {
1014 /* Update $SYSTEMD_EXEC_PID=pid except when '*' is set for the variable. */
1016 e
= secure_getenv("SYSTEMD_EXEC_PID");
1017 if (!e
&& update_only
)
1020 if (streq_ptr(e
, "*"))
1023 r
= setenvf("SYSTEMD_EXEC_PID", /* overwrite= */ 1, PID_FMT
, getpid_cached());
1030 int setenv_systemd_log_level(void) {
1031 _cleanup_free_
char *val
= NULL
;
1034 r
= log_level_to_string_alloc(log_get_max_level(), &val
);
1038 return RET_NERRNO(setenv("SYSTEMD_LOG_LEVEL", val
, /* overwrite= */ true));
1041 int getenv_path_list(const char *name
, char ***ret_paths
) {
1042 _cleanup_strv_free_
char **l
= NULL
;
1049 e
= secure_getenv(name
);
1053 r
= strv_split_full(&l
, e
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
);
1055 return log_debug_errno(r
, "Failed to parse $%s: %m", name
);
1057 STRV_FOREACH(p
, l
) {
1058 if (!path_is_absolute(*p
))
1059 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1060 "Path '%s' is not absolute, refusing.", *p
);
1062 if (!path_is_normalized(*p
))
1063 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1064 "Path '%s' is not normalized, refusing.", *p
);
1066 if (path_equal(*p
, "/"))
1067 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1068 "Path '%s' is the root fs, refusing.", *p
);
1071 if (strv_isempty(l
))
1072 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
1073 "No paths specified, refusing.");
1075 *ret_paths
= TAKE_PTR(l
);
1079 int getenv_steal_erase(const char *name
, char **ret
) {
1080 _cleanup_(erase_and_freep
) char *a
= NULL
;
1085 /* Reads an environment variable, makes a copy of it, erases its memory in the environment block and removes
1086 * it from there. Usecase: reading passwords from the env block (which is a bad idea, but useful for
1087 * testing, and given that people are likely going to misuse this, be thorough) */
1104 if (unsetenv(name
) < 0)
1113 int set_full_environment(char **env
) {
1118 STRV_FOREACH(e
, env
) {
1119 _cleanup_free_
char *k
= NULL
, *v
= NULL
;
1121 r
= split_pair(*e
, "=", &k
, &v
);
1125 if (setenv(k
, v
, /* overwrite= */ true) < 0)
1132 int setenvf(const char *name
, bool overwrite
, const char *valuef
, ...) {
1133 _cleanup_free_
char *value
= NULL
;
1140 return RET_NERRNO(unsetenv(name
));
1142 va_start(ap
, valuef
);
1143 DISABLE_WARNING_FORMAT_NONLITERAL
;
1144 r
= vasprintf(&value
, valuef
, ap
);
1151 return RET_NERRNO(setenv(name
, value
, overwrite
));