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(size_t n_lists
, ...) {
187 _cleanup_strv_free_
char **ret
= NULL
;
192 /* Merges an arbitrary number of environment sets */
194 va_start(ap
, n_lists
);
195 for (size_t i
= 0; i
< n_lists
; i
++) {
196 l
= va_arg(ap
, char**);
201 ret
= new(char*, n
+1);
208 va_start(ap
, n_lists
);
209 for (size_t i
= 0; i
< n_lists
; i
++) {
210 l
= va_arg(ap
, char**);
211 if (env_append(ret
, &k
, l
) < 0) {
218 return TAKE_PTR(ret
);
221 static bool env_match(const char *t
, const char *pattern
) {
225 /* pattern a matches string a
230 * a= does not match a
231 * a=b does not match a=
232 * a=b does not match a
233 * a=b does not match a=c */
235 if (streq(t
, pattern
))
238 if (!strchr(pattern
, '=')) {
239 size_t l
= strlen(pattern
);
241 return strneq(t
, pattern
, l
) && t
[l
] == '=';
247 static bool env_entry_has_name(const char *entry
, const char *name
) {
253 t
= startswith(entry
, name
);
260 char **strv_env_delete(char **x
, size_t n_lists
, ...) {
265 /* Deletes every entry from x that is mentioned in the other
275 va_start(ap
, n_lists
);
276 for (size_t v
= 0; v
< n_lists
; v
++) {
279 l
= va_arg(ap
, char**);
281 if (env_match(*k
, *j
))
306 char **strv_env_unset(char **l
, const char *p
) {
314 /* Drops every occurrence of the env var setting p in the
315 * string list. Edits in-place. */
317 for (f
= t
= l
; *f
; f
++) {
319 if (env_match(*f
, p
)) {
331 char **strv_env_unset_many(char **l
, ...) {
337 /* Like strv_env_unset() but applies many at once. Edits in-place. */
339 for (f
= t
= l
; *f
; f
++) {
346 while ((p
= va_arg(ap
, const char*))) {
347 if (env_match(*f
, p
)) {
367 int strv_env_replace_consume(char ***l
, char *p
) {
368 const char *t
, *name
;
374 /* Replace first occurrence of the env var or add a new one in the string list. Drop other
375 * occurrences. Edits in-place. Does not copy p and CONSUMES p EVEN ON FAILURE.
377 * p must be a valid key=value assignment. */
385 name
= strndupa(p
, t
- p
);
388 if (env_entry_has_name(*f
, name
)) {
389 free_and_replace(*f
, p
);
390 strv_env_unset(f
+ 1, *f
);
394 /* We didn't find a match, we need to append p or create a new strv */
395 r
= strv_consume(l
, p
);
402 int strv_env_replace_strdup(char ***l
, const char *assignment
) {
403 /* Like strv_env_replace_consume(), but copies the argument. */
405 char *p
= strdup(assignment
);
409 return strv_env_replace_consume(l
, p
);
412 int strv_env_assign(char ***l
, const char *key
, const char *value
) {
413 if (!env_name_is_valid(key
))
416 /* NULL removes assignment, "" creates an empty assignment. */
419 strv_env_unset(*l
, key
);
423 char *p
= strjoin(key
, "=", value
);
427 return strv_env_replace_consume(l
, p
);
430 char *strv_env_get_n(char **l
, const char *name
, size_t k
, unsigned flags
) {
438 STRV_FOREACH_BACKWARDS(i
, l
)
439 if (strneq(*i
, name
, k
) &&
443 if (flags
& REPLACE_ENV_USE_ENVIRONMENT
) {
446 t
= strndupa(name
, k
);
453 char *strv_env_get(char **l
, const char *name
) {
456 return strv_env_get_n(l
, name
, strlen(name
), 0);
459 char *strv_env_pairs_get(char **l
, const char *name
) {
460 char **key
, **value
, *result
= NULL
;
464 STRV_FOREACH_PAIR(key
, value
, l
)
465 if (streq(*key
, name
))
471 char **strv_env_clean_with_callback(char **e
, void (*invalid_callback
)(const char *p
, void *userdata
), void *userdata
) {
477 bool duplicate
= false;
479 if (!env_assignment_is_valid(*p
)) {
480 if (invalid_callback
)
481 invalid_callback(*p
, userdata
);
486 n
= strcspn(*p
, "=");
487 STRV_FOREACH(q
, p
+ 1)
488 if (strneq(*p
, *q
, n
) && (*q
)[n
] == '=') {
507 char *replace_env_n(const char *format
, size_t n
, char **env
, unsigned flags
) {
518 const char *e
, *word
= format
, *test_value
= NULL
; /* test_value is initialized to appease gcc */
520 _cleanup_free_
char *r
= NULL
;
521 size_t i
, len
= 0; /* len is initialized to appease gcc */
526 for (e
= format
, i
= 0; *e
&& i
< n
; e
++, i
++)
536 k
= strnappend(r
, word
, e
-word
-1);
540 free_and_replace(r
, k
);
545 } else if (*e
== '$') {
546 k
= strnappend(r
, word
, e
-word
);
550 free_and_replace(r
, k
);
555 } else if (flags
& REPLACE_ENV_ALLOW_BRACELESS
&& strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
556 k
= strnappend(r
, word
, e
-word
-1);
560 free_and_replace(r
, k
);
563 state
= VARIABLE_RAW
;
573 t
= strv_env_get_n(env
, word
+2, e
-word
-2, flags
);
575 if (!strextend(&r
, t
))
580 } else if (*e
== ':') {
581 if (flags
& REPLACE_ENV_ALLOW_EXTENDED
) {
585 /* Treat this as unsupported syntax, i.e. do no replacement */
592 state
= DEFAULT_VALUE
;
594 state
= ALTERNATE_VALUE
;
603 case DEFAULT_VALUE
: /* fall through */
604 case ALTERNATE_VALUE
:
605 assert(flags
& REPLACE_ENV_ALLOW_EXTENDED
);
618 _cleanup_free_
char *v
= NULL
;
620 t
= strv_env_get_n(env
, word
+2, len
, flags
);
622 if (t
&& state
== ALTERNATE_VALUE
)
623 t
= v
= replace_env_n(test_value
, e
-test_value
, env
, flags
);
624 else if (!t
&& state
== DEFAULT_VALUE
)
625 t
= v
= replace_env_n(test_value
, e
-test_value
, env
, flags
);
627 if (!strextend(&r
, t
))
636 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
638 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
641 t
= strv_env_get_n(env
, word
+1, e
-word
-1, flags
);
643 if (!strextend(&r
, t
))
653 if (state
== VARIABLE_RAW
) {
656 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
658 t
= strv_env_get_n(env
, word
+1, e
-word
-1, flags
);
659 return strjoin(r
, t
);
661 return strnappend(r
, word
, e
-word
);
664 char **replace_env_argv(char **argv
, char **env
) {
668 l
= strv_length(argv
);
670 ret
= new(char*, l
+1);
674 STRV_FOREACH(i
, argv
) {
676 /* If $FOO appears as single word, replace it by the split up variable */
677 if ((*i
)[0] == '$' && !IN_SET((*i
)[1], '{', '$')) {
679 char **w
, **m
= NULL
;
682 e
= strv_env_get(env
, *i
+1);
686 r
= strv_split_full(&m
, e
, WHITESPACE
, EXTRACT_RELAX
|EXTRACT_UNQUOTE
);
698 w
= reallocarray(ret
, l
+ 1, sizeof(char *));
708 memcpy(ret
+ k
, m
, q
* sizeof(char*));
716 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
717 ret
[k
] = replace_env(*i
, env
, 0);
729 int getenv_bool(const char *p
) {
736 return parse_boolean(e
);
739 int getenv_bool_secure(const char *p
) {
742 e
= secure_getenv(p
);
746 return parse_boolean(e
);
749 int set_unset_env(const char *name
, const char *value
, bool overwrite
) {
753 r
= setenv(name
, value
, overwrite
);
761 int putenv_dup(const char *assignment
, bool override
) {
764 e
= strchr(assignment
, '=');
768 n
= strndupa(assignment
, e
- assignment
);
770 /* This is like putenv(), but uses setenv() so that our memory doesn't become part of environ[]. */
771 if (setenv(n
, e
+ 1, override
) < 0)
776 int setenv_systemd_exec_pid(bool update_only
) {
777 char str
[DECIMAL_STR_MAX(pid_t
)];
780 /* Update $SYSTEMD_EXEC_PID=pid except when '*' is set for the variable. */
782 e
= secure_getenv("SYSTEMD_EXEC_PID");
783 if (!e
&& update_only
)
786 if (streq_ptr(e
, "*"))
789 xsprintf(str
, PID_FMT
, getpid_cached());
791 if (setenv("SYSTEMD_EXEC_PID", str
, 1) < 0)
797 int getenv_path_list(const char *name
, char ***ret_paths
) {
798 _cleanup_strv_free_
char **l
= NULL
;
806 e
= secure_getenv(name
);
810 r
= strv_split_full(&l
, e
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
);
812 return log_debug_errno(r
, "Failed to parse $%s: %m", name
);
815 if (!path_is_absolute(*p
))
816 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
817 "Path '%s' is not absolute, refusing.", *p
);
819 if (!path_is_normalized(*p
))
820 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
821 "Path '%s' is not normalized, refusing.", *p
);
823 if (path_equal(*p
, "/"))
824 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
825 "Path '%s' is the root fs, refusing.", *p
);
829 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
830 "No paths specified, refusing.");
832 *ret_paths
= TAKE_PTR(l
);