]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/sysctl-util.c
0bc81aaa567837a2f030d26c28c2f126dff49215
[thirdparty/systemd.git] / src / shared / sysctl-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19 ***/
20
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #include "fd-util.h"
28 #include "fileio.h"
29 #include "log.h"
30 #include "macro.h"
31 #include "string-util.h"
32 #include "sysctl-util.h"
33
34 char *sysctl_normalize(char *s) {
35 char *n;
36
37 n = strpbrk(s, "/.");
38 /* If the first separator is a slash, the path is
39 * assumed to be normalized and slashes remain slashes
40 * and dots remains dots. */
41 if (!n || *n == '/')
42 return s;
43
44 /* Otherwise, dots become slashes and slashes become
45 * dots. Fun. */
46 while (n) {
47 if (*n == '.')
48 *n = '/';
49 else
50 *n = '.';
51
52 n = strpbrk(n + 1, "/.");
53 }
54
55 return s;
56 }
57
58 int sysctl_write(const char *property, const char *value) {
59 char *p;
60 _cleanup_close_ int fd = -1;
61
62 assert(property);
63 assert(value);
64
65 log_debug("Setting '%s' to '%s'", property, value);
66
67 p = strjoina("/proc/sys/", property);
68 fd = open(p, O_WRONLY|O_CLOEXEC);
69 if (fd < 0)
70 return -errno;
71
72 if (!endswith(value, "\n"))
73 value = strjoina(value, "\n");
74
75 if (write(fd, value, strlen(value)) < 0)
76 return -errno;
77
78 return 0;
79 }
80
81 int sysctl_read(const char *property, char **content) {
82 char *p;
83
84 assert(property);
85 assert(content);
86
87 p = strjoina("/proc/sys/", property);
88 return read_full_file(p, content, NULL);
89 }