]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/sysctl/sysctl.c
Merge pull request #18567 from Werkov/mkosi-opensuse-v9+
[thirdparty/systemd.git] / src / sysctl / sysctl.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <getopt.h>
5 #include <limits.h>
6 #include <stdbool.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11
12 #include "conf-files.h"
13 #include "def.h"
14 #include "errno-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "glob-util.h"
18 #include "hashmap.h"
19 #include "log.h"
20 #include "main-func.h"
21 #include "pager.h"
22 #include "path-util.h"
23 #include "pretty-print.h"
24 #include "string-util.h"
25 #include "strv.h"
26 #include "sysctl-util.h"
27
28 static char **arg_prefixes = NULL;
29 static bool arg_cat_config = false;
30 static PagerFlags arg_pager_flags = 0;
31
32 STATIC_DESTRUCTOR_REGISTER(arg_prefixes, strv_freep);
33
34 typedef struct Option {
35 char *key;
36 char *value;
37 bool ignore_failure;
38 } Option;
39
40 static Option *option_free(Option *o) {
41 if (!o)
42 return NULL;
43
44 free(o->key);
45 free(o->value);
46
47 return mfree(o);
48 }
49
50 DEFINE_TRIVIAL_CLEANUP_FUNC(Option*, option_free);
51 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(option_hash_ops, char, string_hash_func, string_compare_func, Option, option_free);
52
53 static bool test_prefix(const char *p) {
54 char **i;
55
56 if (strv_isempty(arg_prefixes))
57 return true;
58
59 STRV_FOREACH(i, arg_prefixes) {
60 const char *t;
61
62 t = path_startswith(*i, "/proc/sys/");
63 if (!t)
64 t = *i;
65
66 if (path_startswith(p, t))
67 return true;
68 }
69
70 return false;
71 }
72
73 static Option *option_new(
74 const char *key,
75 const char *value,
76 bool ignore_failure) {
77
78 _cleanup_(option_freep) Option *o = NULL;
79
80 assert(key);
81
82 o = new(Option, 1);
83 if (!o)
84 return NULL;
85
86 *o = (Option) {
87 .key = strdup(key),
88 .value = value ? strdup(value) : NULL,
89 .ignore_failure = ignore_failure,
90 };
91
92 if (!o->key)
93 return NULL;
94 if (value && !o->value)
95 return NULL;
96
97 return TAKE_PTR(o);
98 }
99
100 static int sysctl_write_or_warn(const char *key, const char *value, bool ignore_failure) {
101 int r;
102
103 r = sysctl_write(key, value);
104 if (r < 0) {
105 /* If the sysctl is not available in the kernel or we are running with reduced privileges and
106 * cannot write it, then log about the issue, and proceed without failing. (EROFS is treated
107 * as a permission problem here, since that's how container managers usually protected their
108 * sysctls.) In all other cases log an error and make the tool fail. */
109 if (ignore_failure || r == -EROFS || ERRNO_IS_PRIVILEGE(r))
110 log_debug_errno(r, "Couldn't write '%s' to '%s', ignoring: %m", value, key);
111 else if (r == -ENOENT)
112 log_info_errno(r, "Couldn't write '%s' to '%s', ignoring: %m", value, key);
113 else
114 return log_error_errno(r, "Couldn't write '%s' to '%s': %m", value, key);
115 }
116
117 return 0;
118 }
119
120 static int apply_all(OrderedHashmap *sysctl_options) {
121 Option *option;
122 int r = 0;
123
124 ORDERED_HASHMAP_FOREACH(option, sysctl_options) {
125 int k;
126
127 /* Ignore "negative match" options, they are there only to exclude stuff from globs. */
128 if (!option->value)
129 continue;
130
131 if (string_is_glob(option->key)) {
132 _cleanup_strv_free_ char **paths = NULL;
133 _cleanup_free_ char *pattern = NULL;
134 char **s;
135
136 pattern = path_join("/proc/sys", option->key);
137 if (!pattern)
138 return log_oom();
139
140 k = glob_extend(&paths, pattern, GLOB_NOCHECK);
141 if (k < 0) {
142 if (option->ignore_failure || ERRNO_IS_PRIVILEGE(k))
143 log_debug_errno(k, "Failed to resolve glob '%s', ignoring: %m",
144 option->key);
145 else {
146 log_error_errno(k, "Couldn't resolve glob '%s': %m",
147 option->key);
148 if (r == 0)
149 r = k;
150 }
151
152 } else if (strv_isempty(paths))
153 log_debug("No match for glob: %s", option->key);
154
155 STRV_FOREACH(s, paths) {
156 const char *key;
157
158 assert_se(key = path_startswith(*s, "/proc/sys"));
159
160 if (!test_prefix(key))
161 continue;
162
163 if (ordered_hashmap_contains(sysctl_options, key)) {
164 log_debug("Not setting %s (explicit setting exists).", key);
165 continue;
166 }
167
168 k = sysctl_write_or_warn(key, option->value, option->ignore_failure);
169 if (r == 0)
170 r = k;
171 }
172
173 } else {
174 k = sysctl_write_or_warn(option->key, option->value, option->ignore_failure);
175 if (r == 0)
176 r = k;
177 }
178 }
179
180 return r;
181 }
182
183 static int parse_file(OrderedHashmap **sysctl_options, const char *path, bool ignore_enoent) {
184 _cleanup_fclose_ FILE *f = NULL;
185 _cleanup_free_ char *pp = NULL;
186 unsigned c = 0;
187 int r;
188
189 assert(path);
190
191 r = search_and_fopen(path, "re", NULL, (const char**) CONF_PATHS_STRV("sysctl.d"), &f, &pp);
192 if (r < 0) {
193 if (ignore_enoent && r == -ENOENT)
194 return 0;
195
196 return log_error_errno(r, "Failed to open file '%s', ignoring: %m", path);
197 }
198
199 log_debug("Parsing %s", pp);
200 for (;;) {
201 _cleanup_(option_freep) Option *new_option = NULL;
202 _cleanup_free_ char *l = NULL;
203 bool ignore_failure = false;
204 Option *existing;
205 char *p, *value;
206 int k;
207
208 k = read_line(f, LONG_LINE_MAX, &l);
209 if (k == 0)
210 break;
211 if (k < 0)
212 return log_error_errno(k, "Failed to read file '%s', ignoring: %m", pp);
213
214 c++;
215
216 p = strstrip(l);
217
218 if (isempty(p))
219 continue;
220 if (strchr(COMMENTS "\n", *p))
221 continue;
222
223 value = strchr(p, '=');
224 if (value) {
225 if (p[0] == '-') {
226 ignore_failure = true;
227 p++;
228 }
229
230 *value = 0;
231 value++;
232 value = strstrip(value);
233
234 } else {
235 if (p[0] == '-')
236 /* We have a "negative match" option. Let's continue with value==NULL. */
237 p++;
238 else {
239 log_syntax(NULL, LOG_WARNING, pp, c, 0,
240 "Line is not an assignment, ignoring: %s", p);
241 if (r == 0)
242 r = -EINVAL;
243 continue;
244 }
245 }
246
247 p = strstrip(p);
248 p = sysctl_normalize(p);
249
250 /* We can't filter out globs at this point, we'll need to do that later. */
251 if (!string_is_glob(p) &&
252 !test_prefix(p))
253 continue;
254
255 if (ordered_hashmap_ensure_allocated(sysctl_options, &option_hash_ops) < 0)
256 return log_oom();
257
258 existing = ordered_hashmap_get(*sysctl_options, p);
259 if (existing) {
260 if (streq_ptr(value, existing->value)) {
261 existing->ignore_failure = existing->ignore_failure || ignore_failure;
262 continue;
263 }
264
265 log_debug("Overwriting earlier assignment of %s at '%s:%u'.", p, pp, c);
266 option_free(ordered_hashmap_remove(*sysctl_options, p));
267 }
268
269 new_option = option_new(p, value, ignore_failure);
270 if (!new_option)
271 return log_oom();
272
273 k = ordered_hashmap_put(*sysctl_options, new_option->key, new_option);
274 if (k < 0)
275 return log_error_errno(k, "Failed to add sysctl variable %s to hashmap: %m", p);
276
277 TAKE_PTR(new_option);
278 }
279
280 return r;
281 }
282
283 static int help(void) {
284 _cleanup_free_ char *link = NULL;
285 int r;
286
287 r = terminal_urlify_man("systemd-sysctl.service", "8", &link);
288 if (r < 0)
289 return log_oom();
290
291 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
292 "Applies kernel sysctl settings.\n\n"
293 " -h --help Show this help\n"
294 " --version Show package version\n"
295 " --cat-config Show configuration files\n"
296 " --prefix=PATH Only apply rules with the specified prefix\n"
297 " --no-pager Do not pipe output into a pager\n"
298 "\nSee the %s for details.\n",
299 program_invocation_short_name,
300 link);
301
302 return 0;
303 }
304
305 static int parse_argv(int argc, char *argv[]) {
306
307 enum {
308 ARG_VERSION = 0x100,
309 ARG_CAT_CONFIG,
310 ARG_PREFIX,
311 ARG_NO_PAGER,
312 };
313
314 static const struct option options[] = {
315 { "help", no_argument, NULL, 'h' },
316 { "version", no_argument, NULL, ARG_VERSION },
317 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
318 { "prefix", required_argument, NULL, ARG_PREFIX },
319 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
320 {}
321 };
322
323 int c;
324
325 assert(argc >= 0);
326 assert(argv);
327
328 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
329
330 switch (c) {
331
332 case 'h':
333 return help();
334
335 case ARG_VERSION:
336 return version();
337
338 case ARG_CAT_CONFIG:
339 arg_cat_config = true;
340 break;
341
342 case ARG_PREFIX: {
343 char *p;
344
345 /* We used to require people to specify absolute paths
346 * in /proc/sys in the past. This is kinda useless, but
347 * we need to keep compatibility. We now support any
348 * sysctl name available. */
349 sysctl_normalize(optarg);
350
351 if (path_startswith(optarg, "/proc/sys"))
352 p = strdup(optarg);
353 else
354 p = path_join("/proc/sys", optarg);
355 if (!p)
356 return log_oom();
357
358 if (strv_consume(&arg_prefixes, p) < 0)
359 return log_oom();
360
361 break;
362 }
363
364 case ARG_NO_PAGER:
365 arg_pager_flags |= PAGER_DISABLE;
366 break;
367
368 case '?':
369 return -EINVAL;
370
371 default:
372 assert_not_reached();
373 }
374
375 if (arg_cat_config && argc > optind)
376 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
377 "Positional arguments are not allowed with --cat-config");
378
379 return 1;
380 }
381
382 static int run(int argc, char *argv[]) {
383 _cleanup_(ordered_hashmap_freep) OrderedHashmap *sysctl_options = NULL;
384 int r, k;
385
386 r = parse_argv(argc, argv);
387 if (r <= 0)
388 return r;
389
390 log_setup();
391
392 umask(0022);
393
394 if (argc > optind) {
395 int i;
396
397 r = 0;
398
399 for (i = optind; i < argc; i++) {
400 k = parse_file(&sysctl_options, argv[i], false);
401 if (k < 0 && r == 0)
402 r = k;
403 }
404 } else {
405 _cleanup_strv_free_ char **files = NULL;
406 char **f;
407
408 r = conf_files_list_strv(&files, ".conf", NULL, 0, (const char**) CONF_PATHS_STRV("sysctl.d"));
409 if (r < 0)
410 return log_error_errno(r, "Failed to enumerate sysctl.d files: %m");
411
412 if (arg_cat_config) {
413 (void) pager_open(arg_pager_flags);
414
415 return cat_files(NULL, files, 0);
416 }
417
418 STRV_FOREACH(f, files) {
419 k = parse_file(&sysctl_options, *f, true);
420 if (k < 0 && r == 0)
421 r = k;
422 }
423 }
424
425 k = apply_all(sysctl_options);
426 if (k < 0 && r == 0)
427 r = k;
428
429 return r;
430 }
431
432 DEFINE_MAIN_FUNCTION(run);