From: Martin Pitt Date: Tue, 19 May 2015 05:49:56 +0000 (+0200) Subject: hostname: Allow comments in /etc/hostname X-Git-Tag: v226.4~1^2~374 X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?p=elogind.git;a=commitdiff_plain;h=2e69dc3b6967982d9cfc35bd55d34a2358c6a99e hostname: Allow comments in /etc/hostname 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 --- diff --git a/src/shared/hostname-util.c b/src/shared/hostname-util.c index 2998fdf2c..e336f269f 100644 --- a/src/shared/hostname-util.c +++ b/src/shared/hostname-util.c @@ -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; +} diff --git a/src/shared/hostname-util.h b/src/shared/hostname-util.h index f2821c307..0c4763cf5 100644 --- a/src/shared/hostname-util.h +++ b/src/shared/hostname-util.h @@ -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);