chiark / gitweb /
hostname: Allow comments in /etc/hostname
authorMartin Pitt <martin.pitt@ubuntu.com>
Tue, 19 May 2015 05:49:56 +0000 (07:49 +0200)
committerSven Eden <yamakuzure@gmx.net>
Tue, 14 Mar 2017 08:57:17 +0000 (09:57 +0100)
The hostname(1) tool allows comments in /etc/hostname. Introduce a new
read_hostname_config() in hostname-util which reads a hostname configuration
file like /etc/hostname, strips out comments, whitespace, and cleans the
hostname. Use it in hostname-setup.c and hostnamed and remove duplicated code.

Update hostname manpage. Add tests.

https://launchpad.net/bugs/1053048

src/shared/hostname-util.c
src/shared/hostname-util.h

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;
+}
index f2821c307810f8156567d38f837310c9bb856b1b..0c4763cf5a377053b085a272e04cce85607b082d 100644 (file)
@@ -35,3 +35,5 @@ char* hostname_cleanup(char *s, bool lowercase);
 bool is_localhost(const char *hostname);
 
 int sethostname_idempotent(const char *s);
+
+int read_hostname_config(const char *path, char **hostname);