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