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