]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/environment-d-generator/environment-d-generator.c
39c46c7c2b28d517d2321cccb4a08122c6ae8556
[thirdparty/systemd.git] / src / environment-d-generator / environment-d-generator.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-path.h"
4
5 #include "conf-files.h"
6 #include "def.h"
7 #include "env-file.h"
8 #include "escape.h"
9 #include "log.h"
10 #include "path-lookup.h"
11 #include "strv.h"
12
13 static int environment_dirs(char ***ret) {
14 _cleanup_strv_free_ char **dirs = NULL;
15 _cleanup_free_ char *c = NULL;
16 int r;
17
18 dirs = strv_new(CONF_PATHS_USR("environment.d"), NULL);
19 if (!dirs)
20 return -ENOMEM;
21
22 /* ~/.config/systemd/environment.d */
23 r = sd_path_lookup(SD_PATH_USER_CONFIGURATION, "environment.d", &c);
24 if (r < 0)
25 return r;
26
27 r = strv_extend_front(&dirs, c);
28 if (r < 0)
29 return r;
30
31 if (DEBUG_LOGGING) {
32 _cleanup_free_ char *t = NULL;
33
34 t = strv_join(dirs, "\n\t");
35 log_debug("Looking for environment.d files in (higher priority first):\n\t%s", strna(t));
36 }
37
38 *ret = TAKE_PTR(dirs);
39 return 0;
40 }
41
42 static int load_and_print(void) {
43 _cleanup_strv_free_ char **dirs = NULL, **files = NULL, **env = NULL;
44 int r;
45
46 r = environment_dirs(&dirs);
47 if (r < 0)
48 return r;
49
50 r = conf_files_list_strv(&files, ".conf", NULL, 0, (const char **) dirs);
51 if (r < 0)
52 return r;
53
54 /* This will mutate the existing environment, based on the presumption
55 * that in case of failure, a partial update is better than none. */
56
57 STRV_FOREACH(i, files) {
58 log_debug("Reading %s…", *i);
59
60 r = merge_env_file(&env, NULL, *i);
61 if (r == -ENOMEM)
62 return r;
63 }
64
65 STRV_FOREACH(i, env) {
66 char *t;
67 _cleanup_free_ char *q = NULL;
68
69 t = strchr(*i, '=');
70 assert(t);
71
72 q = shell_maybe_quote(t + 1, 0);
73 if (!q)
74 return log_oom();
75
76 printf("%.*s=%s\n", (int) (t - *i), *i, q);
77 }
78
79 return 0;
80 }
81
82 int main(int argc, char *argv[]) {
83 int r;
84
85 log_parse_environment();
86 log_open();
87
88 if (argc > 1) {
89 log_error("This program takes no arguments.");
90 return EXIT_FAILURE;
91 }
92
93 r = load_and_print();
94 if (r < 0)
95 log_error_errno(r, "Failed to load environment.d: %m");
96
97 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
98 }