]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/shared/sysctl-util.c
tree-wide: drop 'This file is part of systemd' blurb
[thirdparty/systemd.git] / src / shared / sysctl-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
88a60da0 2/***
88a60da0 3 Copyright 2010 Lennart Poettering
88a60da0
KS
4***/
5
521251d2
MG
6#include <errno.h>
7#include <fcntl.h>
3f6fd1ba 8#include <stdio.h>
3f6fd1ba 9#include <string.h>
521251d2 10#include <unistd.h>
88a60da0 11
521251d2 12#include "fd-util.h"
3f6fd1ba 13#include "fileio.h"
88a60da0 14#include "log.h"
a8fbdf54 15#include "macro.h"
07630cea 16#include "string-util.h"
88a60da0
KS
17#include "sysctl-util.h"
18
19char *sysctl_normalize(char *s) {
20 char *n;
21
22 n = strpbrk(s, "/.");
23 /* If the first separator is a slash, the path is
24 * assumed to be normalized and slashes remain slashes
25 * and dots remains dots. */
26 if (!n || *n == '/')
27 return s;
28
29 /* Otherwise, dots become slashes and slashes become
30 * dots. Fun. */
31 while (n) {
32 if (*n == '.')
33 *n = '/';
34 else
35 *n = '.';
36
37 n = strpbrk(n + 1, "/.");
38 }
39
40 return s;
41}
42
43int sysctl_write(const char *property, const char *value) {
0f5a8be5 44 char *p;
521251d2 45 _cleanup_close_ int fd = -1;
88a60da0 46
0f5a8be5
LP
47 assert(property);
48 assert(value);
88a60da0 49
0f5a8be5 50 log_debug("Setting '%s' to '%s'", property, value);
88a60da0 51
0f5a8be5 52 p = strjoina("/proc/sys/", property);
521251d2
MG
53 fd = open(p, O_WRONLY|O_CLOEXEC);
54 if (fd < 0)
55 return -errno;
56
57 if (!endswith(value, "\n"))
58 value = strjoina(value, "\n");
59
60 if (write(fd, value, strlen(value)) < 0)
61 return -errno;
62
63 return 0;
88a60da0
KS
64}
65
66int sysctl_read(const char *property, char **content) {
0f5a8be5 67 char *p;
88a60da0 68
0f5a8be5
LP
69 assert(property);
70 assert(content);
88a60da0 71
0f5a8be5 72 p = strjoina("/proc/sys/", property);
88a60da0
KS
73 return read_full_file(p, content, NULL);
74}