From b8013c883c0e654a53d93ac24aefa02611889a93 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Mon, 2 Dec 2024 05:10:09 +0200 Subject: [PATCH] LibC: Implement getpass --- userspace/libraries/LibC/include/limits.h | 1 + userspace/libraries/LibC/include/unistd.h | 1 + userspace/libraries/LibC/unistd.cpp | 41 +++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/userspace/libraries/LibC/include/limits.h b/userspace/libraries/LibC/include/limits.h index 4ffdd81a..68f69f49 100644 --- a/userspace/libraries/LibC/include/limits.h +++ b/userspace/libraries/LibC/include/limits.h @@ -60,6 +60,7 @@ __BEGIN_DECLS #define OPEN_MAX 64 #define NAME_MAX 255 #define PATH_MAX 256 +#define PASS_MAX 256 #define LOGIN_NAME_MAX 256 #define HOST_NAME_MAX 255 #define TTY_NAME_MAX PATH_MAX diff --git a/userspace/libraries/LibC/include/unistd.h b/userspace/libraries/LibC/include/unistd.h index ad854514..795cc918 100644 --- a/userspace/libraries/LibC/include/unistd.h +++ b/userspace/libraries/LibC/include/unistd.h @@ -234,6 +234,7 @@ int usleep(useconds_t usec); ssize_t write(int fildes, const void* buf, size_t nbyte); int getpagesize(void); +char* getpass(const char* prompt); extern char* optarg; extern int opterr, optind, optopt; diff --git a/userspace/libraries/LibC/unistd.cpp b/userspace/libraries/LibC/unistd.cpp index da59d044..35205f05 100644 --- a/userspace/libraries/LibC/unistd.cpp +++ b/userspace/libraries/LibC/unistd.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include char** environ; @@ -454,6 +455,46 @@ int getpagesize(void) return PAGE_SIZE; } +char* getpass(const char* prompt) +{ + static char buffer[PASS_MAX]; + + int fd = open("/dev/tty", O_RDWR); + if (fd == -1) + return NULL; + + termios orig, temp; + tcgetattr(fd, &orig); + + char* ret = nullptr; + ssize_t total_read = 0; + + if (write(fd, prompt, strlen(prompt)) < 0) + goto error; + + temp = orig; + temp.c_lflag &= ~ECHO; + tcsetattr(fd, TCSANOW, &temp); + + while (total_read == 0 || buffer[total_read - 1] != '\n') + { + ssize_t nread = read(fd, buffer + total_read, sizeof(buffer) - total_read - 1); + if (nread < 0) + goto error; + total_read += nread; + } + + buffer[total_read - 1] = '\0'; + ret = buffer; + + write(fd, "\n", 1); + +error: + tcsetattr(fd, TCSANOW, &orig); + close(fd); + return ret; +} + pid_t getpid(void) { return syscall(SYS_GET_PID);