From 08983ab5cb0b8de9df3759fffe621c1cdcff6c0d Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Tue, 8 Oct 2019 15:34:15 -0500 Subject: Add dnsdomainname, fix "hostname -d" segfault on machine with no domain name, and cleanup hostname to only call gethostname() once. It passes the one test in test_hostname, if that helps. --- toys/lsb/hostname.c | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/toys/lsb/hostname.c b/toys/lsb/hostname.c index ac7f9163..b3cc1967 100644 --- a/toys/lsb/hostname.c +++ b/toys/lsb/hostname.c @@ -5,6 +5,7 @@ * http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/hostname.html USE_HOSTNAME(NEWTOY(hostname, ">1bdsfF:[!bdsf]", TOYFLAG_BIN)) +USE_DNSDOMAINNAME(NEWTOY(dnsdomainname, ">0", TOYFLAG_BIN)) config HOSTNAME bool "hostname" @@ -19,9 +20,18 @@ config HOSTNAME -f Show fully-qualified name (host+domain, FQDN) -F Set hostname to contents of FILENAME -s Show short host name (no domain) + +config DNSDOMAINNAME + bool "dnsdomainname" + default y + help + usage: dnsdomainname + + Show domain this system belongs to (same as hostname -d). */ #define FOR_hostname +#define FORCE_FLAGS #include "toys.h" GLOBALS( @@ -30,21 +40,17 @@ GLOBALS( void hostname_main(void) { - char *hostname = *toys.optargs, *dot; + char *hostname = toybuf, *dot; struct hostent *h; + gethostname(toybuf, sizeof(toybuf)-1); if (TT.F && (hostname = xreadfile(TT.F, 0, 0))) { if (!*chomp(hostname)) { if (CFG_TOYBOX_FREE) free(hostname); if (!FLAG(b)) error_exit("empty '%s'", TT.F); hostname = 0; } - } - - // Implement -b. - if (!hostname && FLAG(b)) - if (gethostname(toybuf, sizeof(toybuf)-1) || !*toybuf) - hostname = "localhost"; + } else hostname = (FLAG(b) && !*toybuf) ? "localhost" : *toys.optargs; // Setting? if (hostname) { @@ -53,14 +59,18 @@ void hostname_main(void) return; } - // Get the hostname. - if (gethostname(toybuf, sizeof(toybuf)-1)) perror_exit("gethostname"); // We only do the DNS lookup for -d and -f. if (FLAG(d) || FLAG(f)) { if (!(h = gethostbyname(toybuf))) perror_exit("gethostbyname"); snprintf(toybuf, sizeof(toybuf), "%s", h->h_name); } - dot = strchr(toybuf, '.'); - if (FLAG(s) && dot) *dot = '\0'; + dot = toybuf+strcspn(toybuf, "."); + if (FLAG(s)) *dot = '\0'; xputs(FLAG(d) ? dot+1 : toybuf); } + +void dnsdomainname_main(void) +{ + toys.optflags = FLAG_d; + hostname_main(); +} -- cgit v1.2.3