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