]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/sysctl-util.c
sysctl-util: add sysctl_read_ip_property()
[thirdparty/systemd.git] / src / shared / sysctl-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <unistd.h>
8
9 #include "fd-util.h"
10 #include "fileio.h"
11 #include "log.h"
12 #include "macro.h"
13 #include "string-util.h"
14 #include "sysctl-util.h"
15
16 char *sysctl_normalize(char *s) {
17 char *n;
18
19 n = strpbrk(s, "/.");
20 /* If the first separator is a slash, the path is
21 * assumed to be normalized and slashes remain slashes
22 * and dots remains dots. */
23 if (!n || *n == '/')
24 return s;
25
26 /* Otherwise, dots become slashes and slashes become
27 * dots. Fun. */
28 while (n) {
29 if (*n == '.')
30 *n = '/';
31 else
32 *n = '.';
33
34 n = strpbrk(n + 1, "/.");
35 }
36
37 return s;
38 }
39
40 int sysctl_write(const char *property, const char *value) {
41 char *p;
42 _cleanup_close_ int fd = -1;
43
44 assert(property);
45 assert(value);
46
47 log_debug("Setting '%s' to '%.*s'.", property, (int) strcspn(value, NEWLINE), value);
48
49 p = strjoina("/proc/sys/", property);
50 fd = open(p, O_WRONLY|O_CLOEXEC);
51 if (fd < 0)
52 return -errno;
53
54 if (!endswith(value, "\n"))
55 value = strjoina(value, "\n");
56
57 if (write(fd, value, strlen(value)) < 0)
58 return -errno;
59
60 return 0;
61 }
62
63 int sysctl_write_ip_property(int af, const char *ifname, const char *property, const char *value) {
64 const char *p;
65
66 assert(IN_SET(af, AF_INET, AF_INET6));
67 assert(property);
68 assert(value);
69
70 p = strjoina("/proc/sys/net/ipv", af == AF_INET ? "4" : "6",
71 ifname ? "/conf/" : "", strempty(ifname),
72 property[0] == '/' ? "" : "/", property);
73
74 log_debug("Setting '%s' to '%s'", p, value);
75
76 return write_string_file(p, value, WRITE_STRING_FILE_VERIFY_ON_FAILURE | WRITE_STRING_FILE_DISABLE_BUFFER);
77 }
78
79 int sysctl_read(const char *property, char **content) {
80 char *p;
81
82 assert(property);
83 assert(content);
84
85 p = strjoina("/proc/sys/", property);
86 return read_full_file(p, content, NULL);
87 }
88
89 int sysctl_read_ip_property(int af, const char *ifname, const char *property, char **ret) {
90 _cleanup_free_ char *value = NULL;
91 const char *p;
92 int r;
93
94 assert(IN_SET(af, AF_INET, AF_INET6));
95 assert(property);
96
97 p = strjoina("/proc/sys/net/ipv", af == AF_INET ? "4" : "6",
98 ifname ? "/conf/" : "", strempty(ifname),
99 property[0] == '/' ? "" : "/", property);
100
101 r = read_one_line_file(p, &value);
102 if (r < 0)
103 return r;
104
105 if (ret)
106 *ret = TAKE_PTR(value);
107
108 return r;
109 }