aboutsummaryrefslogtreecommitdiff
path: root/toys
diff options
context:
space:
mode:
Diffstat (limited to 'toys')
-rw-r--r--toys/lsb/hostname.c44
1 files changed, 13 insertions, 31 deletions
diff --git a/toys/lsb/hostname.c b/toys/lsb/hostname.c
index ebfc803c..f30d1fbd 100644
--- a/toys/lsb/hostname.c
+++ b/toys/lsb/hostname.c
@@ -27,43 +27,25 @@ GLOBALS(
void hostname_main(void)
{
- const char *hostname = toys.optargs[0];
-
- if (toys.optflags & FLAG_F) {
- char *buf;
- if ((hostname = buf = readfile(TT.fname, 0, 0))) {
- size_t len = strlen(hostname);
- char *end = buf + len - 1;
-
- /* Trim trailing whitespace. */
- while (len && isspace(*end)) {
- *end-- = '\0';
- len--;
- }
- if (!len) {
- free(buf);
- hostname = NULL;
- if (!(toys.optflags & FLAG_b))
- error_exit("empty file '%s'", TT.fname);
- }
- } else if (!(toys.optflags & FLAG_b))
- error_exit("failed to read '%s'", TT.fname);
+ char *hostname = *toys.optargs;
+
+ if (TT.fname && (hostname = xreadfile(TT.fname, 0, 0))) {
+ if (!*chomp(hostname)) {
+ if (CFG_TOYBOX_FREE) free(hostname);
+ if (!(toys.optflags&FLAG_b)) error_exit("empty '%s'", TT.fname);
+ hostname = 0;
+ }
}
- if (!hostname && toys.optflags & FLAG_b) {
- /* Do nothing if hostname already set. */
- if (gethostname(toybuf, sizeof(toybuf))) perror_exit("get failed");
- if (strnlen(toybuf, sizeof(toybuf))) exit(0);
-
- /* Else set hostname to localhost. */
- hostname = "localhost";
- }
+ if (!hostname && (toys.optflags&FLAG_b))
+ if (gethostname(toybuf, sizeof(toybuf)-1) || !*toybuf)
+ hostname = "localhost";
if (hostname) {
if (sethostname(hostname, strlen(hostname)))
- perror_exit("set failed '%s'", hostname);
+ perror_exit("set '%s'", hostname);
} else {
- if (gethostname(toybuf, sizeof(toybuf))) perror_exit("get failed");
+ if (gethostname(toybuf, sizeof(toybuf)-1)) perror_exit("gethostname");
xputs(toybuf);
}
}