From 551853c5d6062ca2ab2df13621668d6eacd0c7fe Mon Sep 17 00:00:00 2001 From: EnderIce2 Date: Mon, 10 Mar 2025 22:05:28 +0000 Subject: [PATCH] fix(userspace/libc): implement gethostname() Signed-off-by: EnderIce2 --- Userspace/libc/src/std/unistd.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/Userspace/libc/src/std/unistd.c b/Userspace/libc/src/std/unistd.c index 43e8fffd..9892924c 100644 --- a/Userspace/libc/src/std/unistd.c +++ b/Userspace/libc/src/std/unistd.c @@ -23,6 +23,7 @@ #include #include #include +#include export char *optarg; export int optind, opterr, optopt; @@ -183,16 +184,30 @@ export long gethostid(void); export int gethostname(char *name, size_t namelen) { if (namelen == 0) - { - errno = EINVAL; return -1; + + char *hostname = getenv("HOSTNAME"); + if (hostname) + { + strncpy(name, hostname, namelen); + return 0; } - strncpy(name, "localhost", namelen); - if (namelen < strlen("localhost") + 1) - { - errno = ENAMETOOLONG; + int fd = open("/etc/hostname", O_RDONLY); + if (fd == -1) return -1; + + int result = read(fd, name, namelen); + close(fd); + if (result == -1) + return -1; + + for (int i = 0; i < namelen; i++) + { + if (name[i] == '\n' || name[i] == '\r') + name[i] = '\0'; + else if (name[i] < ' ' || name[i] > '~') + name[i] = '\0'; } return 0;