Debian Codegraph @

src/sysctl/sysctl.c

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