diff options
author | Yu Watanabe <watanabe.yu+github@gmail.com> | 2021-08-10 20:44:24 +0200 |
---|---|---|
committer | Yu Watanabe <watanabe.yu+github@gmail.com> | 2021-08-12 06:48:15 +0200 |
commit | 0995accdfd8d6c8ab5d237398cfaf58c64246274 (patch) | |
tree | 99824dcaf687740479ffab26fa23223e3751ebc4 /src/basic/hostname-util.c | |
parent | hostname: fix off-by-one issue in gethostname() (diff) | |
download | systemd-0995accdfd8d6c8ab5d237398cfaf58c64246274.tar.xz systemd-0995accdfd8d6c8ab5d237398cfaf58c64246274.zip |
hostname: introduce gethostname_full() and use it in various gethostname() variants
Diffstat (limited to 'src/basic/hostname-util.c')
-rw-r--r-- | src/basic/hostname-util.c | 67 |
1 files changed, 20 insertions, 47 deletions
diff --git a/src/basic/hostname-util.c b/src/basic/hostname-util.c index 29d69910d2..1d0640e075 100644 --- a/src/basic/hostname-util.c +++ b/src/basic/hostname-util.c @@ -36,66 +36,39 @@ char* get_default_hostname(void) { return strdup(FALLBACK_HOSTNAME); } -char* gethostname_malloc(void) { +int gethostname_full(GetHostnameFlags flags, char **ret) { + _cleanup_free_ char *buf = NULL, *fallback = NULL; struct utsname u; const char *s; - /* This call tries to return something useful, either the actual hostname - * or it makes something up. The only reason it might fail is OOM. - * It might even return "localhost" if that's set. */ + assert(ret); assert_se(uname(&u) >= 0); s = u.nodename; - if (isempty(s) || streq(s, "(none)")) - return get_default_hostname(); - - return strdup(s); -} - -char* gethostname_short_malloc(void) { - struct utsname u; - const char *s; - _cleanup_free_ char *f = NULL; - - /* Like above, but kills the FQDN part if present. */ - - assert_se(uname(&u) >= 0); - - s = u.nodename; - if (isempty(s) || streq(s, "(none)") || s[0] == '.') { - s = f = get_default_hostname(); + if (isempty(s) || + (!FLAGS_SET(flags, GET_HOSTNAME_ALLOW_NONE) && streq(s, "(none)")) || + (!FLAGS_SET(flags, GET_HOSTNAME_ALLOW_LOCALHOST) && is_localhost(s)) || + (FLAGS_SET(flags, GET_HOSTNAME_SHORT) && s[0] == '.')) { + if (!FLAGS_SET(flags, GET_HOSTNAME_FALLBACK_DEFAULT)) + return -ENXIO; + + s = fallback = get_default_hostname(); if (!s) - return NULL; + return -ENOMEM; - assert(s[0] != '.'); + if (FLAGS_SET(flags, GET_HOSTNAME_SHORT) && s[0] == '.') + return -ENXIO; } - return strndup(s, strcspn(s, ".")); -} - -int gethostname_strict(char **ret) { - struct utsname u; - char *k; - - /* This call will rather fail than make up a name. It will not return "localhost" either. */ - - assert_se(uname(&u) >= 0); - - if (isempty(u.nodename)) - return -ENXIO; - - if (streq(u.nodename, "(none)")) - return -ENXIO; - - if (is_localhost(u.nodename)) - return -ENXIO; - - k = strdup(u.nodename); - if (!k) + if (FLAGS_SET(flags, GET_HOSTNAME_SHORT)) + buf = strndup(s, strcspn(s, ".")); + else + buf = strdup(s); + if (!buf) return -ENOMEM; - *ret = k; + *ret = TAKE_PTR(buf); return 0; } |