chiark / gitweb /
hostname: Allow comments in /etc/hostname
[elogind.git] / src / shared / hostname-util.c
index 2998fdf2c7328db18b033027d53ebb145fec6a0b..e336f269fae160cf4c045f1b34b1719ee278b353 100644 (file)
@@ -158,3 +158,36 @@ int sethostname_idempotent(const char *s) {
 
         return 1;
 }
+
+int read_hostname_config(const char *path, char **hostname) {
+        _cleanup_fclose_ FILE *f = NULL;
+        char l[LINE_MAX];
+        char *name = NULL;
+
+        assert(path);
+        assert(hostname);
+
+        f = fopen(path, "re");
+        if (!f)
+                return -errno;
+
+        /* may have comments, ignore them */
+        FOREACH_LINE(l, f, return -errno) {
+                truncate_nl(l);
+                if (l[0] != '\0' && l[0] != '#') {
+                        /* found line with value */
+                        name = hostname_cleanup(l, false);
+                        name = strdup(name);
+                        if (!name)
+                                return -ENOMEM;
+                        break;
+                }
+        }
+
+        if (!name)
+                /* no non-empty line found */
+                return -ENOENT;
+
+        *hostname = name;
+        return 0;
+}