sysctl-util: introduce sysctl_write_ip_property() and friends
authorYu Watanabe <watanabe.yu+github@gmail.com>
Mon, 18 Feb 2019 04:34:01 +0000 (13:34 +0900)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Thu, 21 Feb 2019 01:38:10 +0000 (10:38 +0900)
src/shared/sysctl-util.c
src/shared/sysctl-util.h

index 480e6c3..82f557e 100644 (file)
@@ -60,6 +60,22 @@ int sysctl_write(const char *property, const char *value) {
         return 0;
 }
 
+int sysctl_write_ip_property(int af, const char *ifname, const char *property, const char *value) {
+        const char *p;
+
+        assert(IN_SET(af, AF_INET, AF_INET6));
+        assert(property);
+        assert(value);
+
+        p = strjoina("/proc/sys/net/ipv", af == AF_INET ? "4" : "6",
+                     ifname ? "/conf/" : "", strempty(ifname),
+                     property[0] == '/' ? "" : "/", property);
+
+        log_debug("Setting '%s' to '%s'", p, value);
+
+        return write_string_file(p, value, WRITE_STRING_FILE_VERIFY_ON_FAILURE | WRITE_STRING_FILE_DISABLE_BUFFER);
+}
+
 int sysctl_read(const char *property, char **content) {
         char *p;
 
index fd7c78b..940118c 100644 (file)
@@ -1,7 +1,28 @@
 /* SPDX-License-Identifier: LGPL-2.1+ */
 #pragma once
 
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "macro.h"
+#include "stdio-util.h"
+#include "util.h"
+
 char *sysctl_normalize(char *s);
 int sysctl_read(const char *property, char **value);
 int sysctl_write(const char *property, const char *value);
 
+int sysctl_write_ip_property(int af, const char *ifname, const char *property, const char *value);
+static inline int sysctl_write_ip_property_boolean(int af, const char *ifname, const char *property, bool value) {
+        return sysctl_write_ip_property(af, ifname, property, one_zero(value));
+}
+
+#define DEFINE_SYSCTL_WRITE_IP_PROPERTY(name, type, format)           \
+        static inline int sysctl_write_ip_property_##name(int af, const char *ifname, const char *property, type value) { \
+                char buf[DECIMAL_STR_MAX(type)];                        \
+                xsprintf(buf, format, value);                           \
+                return sysctl_write_ip_property(af, ifname, property, buf); \
+        }
+
+DEFINE_SYSCTL_WRITE_IP_PROPERTY(int, int, "%i");
+DEFINE_SYSCTL_WRITE_IP_PROPERTY(uint32, uint32_t, "%" PRIu32);