]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/sysctl/sysctl.c
sysctl: use ordered_hashmap_ensure_put()
[thirdparty/systemd.git] / src / sysctl / sysctl.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
8e1bd70d 2
8e1bd70d 3#include <errno.h>
7a2a0b90 4#include <getopt.h>
3f6fd1ba
LP
5#include <limits.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <stdlib.h>
ca78ad1d
ZJS
9#include <sys/stat.h>
10#include <sys/types.h>
8e1bd70d 11
2c21044f 12#include "conf-files.h"
39f0d1d2 13#include "creds-util.h"
a0f29c76 14#include "def.h"
32458cc9 15#include "errno-util.h"
3ffd4af2 16#include "fd-util.h"
a5c32cff 17#include "fileio.h"
e0f42479 18#include "glob-util.h"
3f6fd1ba
LP
19#include "hashmap.h"
20#include "log.h"
8eb42d90 21#include "main-func.h"
dcd5c891 22#include "pager.h"
3f6fd1ba 23#include "path-util.h"
294bf0c3 24#include "pretty-print.h"
07630cea 25#include "string-util.h"
3f6fd1ba 26#include "strv.h"
88a60da0 27#include "sysctl-util.h"
8e1bd70d 28
fabe5c0e 29static char **arg_prefixes = NULL;
3c51c626 30static bool arg_cat_config = false;
e88748c1 31static bool arg_strict = false;
0221d68a 32static PagerFlags arg_pager_flags = 0;
8e1bd70d 33
fd8bdbc7
LP
34STATIC_DESTRUCTOR_REGISTER(arg_prefixes, strv_freep);
35
dec02d6e
LP
36typedef struct Option {
37 char *key;
38 char *value;
39 bool ignore_failure;
40} Option;
41
42static 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
52DEFINE_TRIVIAL_CLEANUP_FUNC(Option*, option_free);
53DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(option_hash_ops, char, string_hash_func, string_compare_func, Option, option_free);
54
e0f42479 55static bool test_prefix(const char *p) {
e0f42479
ZJS
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
dec02d6e
LP
73static 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);
dec02d6e
LP
81
82 o = new(Option, 1);
83 if (!o)
84 return NULL;
85
86 *o = (Option) {
87 .key = strdup(key),
e0f42479 88 .value = value ? strdup(value) : NULL,
dec02d6e
LP
89 .ignore_failure = ignore_failure,
90 };
91
e0f42479
ZJS
92 if (!o->key)
93 return NULL;
94 if (value && !o->value)
dec02d6e
LP
95 return NULL;
96
97 return TAKE_PTR(o);
98}
99
e0f42479
ZJS
100static 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) {
e88748c1
QD
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))))
e0f42479 113 log_debug_errno(r, "Couldn't write '%s' to '%s', ignoring: %m", value, key);
e88748c1 114 else if (!arg_strict && r == -ENOENT)
1805fbcf 115 log_warning_errno(r, "Couldn't write '%s' to '%s', ignoring: %m", value, key);
e0f42479
ZJS
116 else
117 return log_error_errno(r, "Couldn't write '%s' to '%s': %m", value, key);
118 }
119
120 return 0;
121}
122
886cf982 123static int apply_all(OrderedHashmap *sysctl_options) {
dec02d6e 124 Option *option;
e50b33be 125 int r = 0;
fabe5c0e 126
90e74a66 127 ORDERED_HASHMAP_FOREACH(option, sysctl_options) {
86fc77c4
MS
128 int k;
129
e0f42479
ZJS
130 /* Ignore "negative match" options, they are there only to exclude stuff from globs. */
131 if (!option->value)
132 continue;
e50b33be 133
e0f42479
ZJS
134 if (string_is_glob(option->key)) {
135 _cleanup_strv_free_ char **paths = NULL;
136 _cleanup_free_ char *pattern = NULL;
86fc77c4 137
e0f42479
ZJS
138 pattern = path_join("/proc/sys", option->key);
139 if (!pattern)
140 return log_oom();
9c37b41c 141
544e146b 142 k = glob_extend(&paths, pattern, GLOB_NOCHECK);
e0f42479 143 if (k < 0) {
c53ce14d 144 if (option->ignore_failure || ERRNO_IS_PRIVILEGE(k))
e0f42479
ZJS
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 }
9c37b41c 153
e0f42479
ZJS
154 } else if (strv_isempty(paths))
155 log_debug("No match for glob: %s", option->key);
9c37b41c 156
e0f42479
ZJS
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)) {
42a033f7 166 log_debug("Not setting %s (explicit setting exists).", key);
e0f42479
ZJS
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 }
9c37b41c
LP
180 }
181
e0f42479 182 return r;
9c37b41c
LP
183}
184
b2ae4d9e 185static int parse_file(OrderedHashmap **sysctl_options, const char *path, bool ignore_enoent) {
fabe5c0e 186 _cleanup_fclose_ FILE *f = NULL;
2708160c 187 _cleanup_free_ char *pp = NULL;
98bf5011 188 unsigned c = 0;
fabe5c0e 189 int r;
8e1bd70d
LP
190
191 assert(path);
192
2708160c 193 r = search_and_fopen(path, "re", NULL, (const char**) CONF_PATHS_STRV("sysctl.d"), &f, &pp);
fabe5c0e 194 if (r < 0) {
6f6fad96 195 if (ignore_enoent && r == -ENOENT)
c1b664d0
LP
196 return 0;
197
8d3d7072 198 return log_error_errno(r, "Failed to open file '%s', ignoring: %m", path);
8e1bd70d
LP
199 }
200
2708160c 201 log_debug("Parsing %s", pp);
4f14f2bb 202 for (;;) {
dec02d6e 203 _cleanup_(option_freep) Option *new_option = NULL;
a668bfe8 204 _cleanup_free_ char *l = NULL;
e0f42479 205 bool ignore_failure = false;
dec02d6e
LP
206 Option *existing;
207 char *p, *value;
fabe5c0e 208 int k;
548f6937 209
a668bfe8
TSH
210 k = read_line(f, LONG_LINE_MAX, &l);
211 if (k == 0)
212 break;
a668bfe8 213 if (k < 0)
2708160c 214 return log_error_errno(k, "Failed to read file '%s', ignoring: %m", pp);
8e1bd70d 215
98bf5011
LP
216 c++;
217
8e1bd70d 218 p = strstrip(l);
8e1bd70d 219
548f6937
LP
220 if (isempty(p))
221 continue;
d3b6d0c2 222 if (strchr(COMMENTS "\n", *p))
8e1bd70d
LP
223 continue;
224
86fc77c4 225 value = strchr(p, '=');
e0f42479
ZJS
226 if (value) {
227 if (p[0] == '-') {
228 ignore_failure = true;
229 p++;
230 }
8e1bd70d 231
e0f42479
ZJS
232 *value = 0;
233 value++;
234 value = strstrip(value);
8e1bd70d 235
e0f42479
ZJS
236 } else {
237 if (p[0] == '-')
238 /* We have a "negative match" option. Let's continue with value==NULL. */
239 p++;
240 else {
2708160c 241 log_syntax(NULL, LOG_WARNING, pp, c, 0,
e0f42479
ZJS
242 "Line is not an assignment, ignoring: %s", p);
243 if (r == 0)
244 r = -EINVAL;
245 continue;
246 }
247 }
dec02d6e 248
e0f42479 249 p = strstrip(p);
dec02d6e 250 p = sysctl_normalize(p);
fabe5c0e 251
e0f42479
ZJS
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))
b99802f7 255 continue;
b99802f7 256
b2ae4d9e 257 existing = ordered_hashmap_get(*sysctl_options, p);
fabe5c0e 258 if (existing) {
db99904b 259 if (streq_ptr(value, existing->value)) {
dec02d6e 260 existing->ignore_failure = existing->ignore_failure || ignore_failure;
04bf3c1a 261 continue;
dec02d6e 262 }
fabe5c0e 263
2708160c 264 log_debug("Overwriting earlier assignment of %s at '%s:%u'.", p, pp, c);
b2ae4d9e 265 option_free(ordered_hashmap_remove(*sysctl_options, p));
86fc77c4
MS
266 }
267
dec02d6e
LP
268 new_option = option_new(p, value, ignore_failure);
269 if (!new_option)
fabe5c0e
LP
270 return log_oom();
271
350ffa97 272 k = ordered_hashmap_ensure_put(sysctl_options, &option_hash_ops, new_option->key, new_option);
dec02d6e
LP
273 if (k < 0)
274 return log_error_errno(k, "Failed to add sysctl variable %s to hashmap: %m", p);
86fc77c4 275
dec02d6e 276 TAKE_PTR(new_option);
8e1bd70d
LP
277 }
278
c1b664d0 279 return r;
8e1bd70d
LP
280}
281
39f0d1d2
LP
282static int read_credential_lines(OrderedHashmap **sysctl_options) {
283 _cleanup_free_ char *j = NULL;
284 const char *d;
285 int r;
286
287 r = get_credentials_dir(&d);
288 if (r == -ENXIO)
289 return 0;
290 if (r < 0)
291 return log_error_errno(r, "Failed to get credentials directory: %m");
292
293 j = path_join(d, "sysctl.extra");
294 if (!j)
295 return log_oom();
296
297 (void) parse_file(sysctl_options, j, /* ignore_enoent= */ true);
298 return 0;
299}
300
37ec0fdd
LP
301static int help(void) {
302 _cleanup_free_ char *link = NULL;
303 int r;
304
305 r = terminal_urlify_man("systemd-sysctl.service", "8", &link);
306 if (r < 0)
307 return log_oom();
308
7a2a0b90
LP
309 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
310 "Applies kernel sysctl settings.\n\n"
311 " -h --help Show this help\n"
eb9da376 312 " --version Show package version\n"
3c51c626 313 " --cat-config Show configuration files\n"
0e1f5792 314 " --prefix=PATH Only apply rules with the specified prefix\n"
dcd5c891 315 " --no-pager Do not pipe output into a pager\n"
bc556335
DDM
316 "\nSee the %s for details.\n",
317 program_invocation_short_name,
318 link);
37ec0fdd
LP
319
320 return 0;
7a2a0b90
LP
321}
322
323static int parse_argv(int argc, char *argv[]) {
324
325 enum {
eb9da376 326 ARG_VERSION = 0x100,
3c51c626
ZJS
327 ARG_CAT_CONFIG,
328 ARG_PREFIX,
dcd5c891 329 ARG_NO_PAGER,
e88748c1 330 ARG_STRICT,
7a2a0b90
LP
331 };
332
333 static const struct option options[] = {
3c51c626
ZJS
334 { "help", no_argument, NULL, 'h' },
335 { "version", no_argument, NULL, ARG_VERSION },
336 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
337 { "prefix", required_argument, NULL, ARG_PREFIX },
dcd5c891 338 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
e88748c1 339 { "strict", no_argument, NULL, ARG_STRICT },
eb9da376 340 {}
7a2a0b90
LP
341 };
342
343 int c;
344
345 assert(argc >= 0);
346 assert(argv);
347
601185b4 348 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
7a2a0b90
LP
349
350 switch (c) {
351
352 case 'h':
37ec0fdd 353 return help();
eb9da376
LP
354
355 case ARG_VERSION:
3f6fd1ba 356 return version();
7a2a0b90 357
3c51c626
ZJS
358 case ARG_CAT_CONFIG:
359 arg_cat_config = true;
360 break;
361
7a2a0b90
LP
362 case ARG_PREFIX: {
363 char *p;
364
0e1f5792
DH
365 /* We used to require people to specify absolute paths
366 * in /proc/sys in the past. This is kinda useless, but
367 * we need to keep compatibility. We now support any
368 * sysctl name available. */
88a60da0 369 sysctl_normalize(optarg);
e50b33be 370
27458ed6 371 if (path_startswith(optarg, "/proc/sys"))
0e1f5792
DH
372 p = strdup(optarg);
373 else
b910cc72 374 p = path_join("/proc/sys", optarg);
0e1f5792
DH
375 if (!p)
376 return log_oom();
e50b33be 377
0e1f5792 378 if (strv_consume(&arg_prefixes, p) < 0)
0d0f0c50 379 return log_oom();
f68c5a70 380
7a2a0b90
LP
381 break;
382 }
383
dcd5c891 384 case ARG_NO_PAGER:
0221d68a 385 arg_pager_flags |= PAGER_DISABLE;
dcd5c891
LP
386 break;
387
e88748c1
QD
388 case ARG_STRICT:
389 arg_strict = true;
390 break;
391
7a2a0b90
LP
392 case '?':
393 return -EINVAL;
394
395 default:
04499a70 396 assert_not_reached();
7a2a0b90 397 }
7a2a0b90 398
baaa35ad
ZJS
399 if (arg_cat_config && argc > optind)
400 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
401 "Positional arguments are not allowed with --cat-config");
3c51c626 402
7a2a0b90
LP
403 return 1;
404}
405
8eb42d90 406static int run(int argc, char *argv[]) {
dec02d6e 407 _cleanup_(ordered_hashmap_freep) OrderedHashmap *sysctl_options = NULL;
a34c79d0 408 int r, k;
8e1bd70d 409
7a2a0b90
LP
410 r = parse_argv(argc, argv);
411 if (r <= 0)
a34c79d0 412 return r;
7a2a0b90 413
d2acb93d 414 log_setup();
8e1bd70d 415
4c12626c
LP
416 umask(0022);
417
de19ece7
LP
418 if (argc > optind) {
419 int i;
420
2de30233
LP
421 r = 0;
422
de19ece7 423 for (i = optind; i < argc; i++) {
b2ae4d9e 424 k = parse_file(&sysctl_options, argv[i], false);
fabe5c0e 425 if (k < 0 && r == 0)
de19ece7
LP
426 r = k;
427 }
428 } else {
fabe5c0e 429 _cleanup_strv_free_ char **files = NULL;
c1b664d0 430
a826d4f7 431 r = conf_files_list_strv(&files, ".conf", NULL, 0, (const char**) CONF_PATHS_STRV("sysctl.d"));
a34c79d0
ZJS
432 if (r < 0)
433 return log_error_errno(r, "Failed to enumerate sysctl.d files: %m");
db1413d7 434
3c51c626 435 if (arg_cat_config) {
384c2c32 436 pager_open(arg_pager_flags);
dcd5c891 437
a34c79d0 438 return cat_files(NULL, files, 0);
3c51c626
ZJS
439 }
440
fabe5c0e 441 STRV_FOREACH(f, files) {
b2ae4d9e 442 k = parse_file(&sysctl_options, *f, true);
fabe5c0e 443 if (k < 0 && r == 0)
db1413d7
KS
444 r = k;
445 }
39f0d1d2
LP
446
447 k = read_credential_lines(&sysctl_options);
448 if (k < 0 && r == 0)
449 r = k;
8e1bd70d 450 }
86fc77c4 451
fabe5c0e
LP
452 k = apply_all(sysctl_options);
453 if (k < 0 && r == 0)
0187f62b
LP
454 r = k;
455
8eb42d90 456 return r;
8e1bd70d 457}
8eb42d90
LP
458
459DEFINE_MAIN_FUNCTION(run);