LibC: Implement getpass

This commit is contained in:
Bananymous 2024-12-02 05:10:09 +02:00
parent ffcc4fd03a
commit b8013c883c
3 changed files with 43 additions and 0 deletions

View File

@ -60,6 +60,7 @@ __BEGIN_DECLS
#define OPEN_MAX 64 #define OPEN_MAX 64
#define NAME_MAX 255 #define NAME_MAX 255
#define PATH_MAX 256 #define PATH_MAX 256
#define PASS_MAX 256
#define LOGIN_NAME_MAX 256 #define LOGIN_NAME_MAX 256
#define HOST_NAME_MAX 255 #define HOST_NAME_MAX 255
#define TTY_NAME_MAX PATH_MAX #define TTY_NAME_MAX PATH_MAX

View File

@ -234,6 +234,7 @@ int usleep(useconds_t usec);
ssize_t write(int fildes, const void* buf, size_t nbyte); ssize_t write(int fildes, const void* buf, size_t nbyte);
int getpagesize(void); int getpagesize(void);
char* getpass(const char* prompt);
extern char* optarg; extern char* optarg;
extern int opterr, optind, optopt; extern int opterr, optind, optopt;

View File

@ -13,6 +13,7 @@
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/syscall.h> #include <sys/syscall.h>
#include <sys/time.h> #include <sys/time.h>
#include <termios.h>
#include <unistd.h> #include <unistd.h>
char** environ; char** environ;
@ -454,6 +455,46 @@ int getpagesize(void)
return PAGE_SIZE; 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) pid_t getpid(void)
{ {
return syscall(SYS_GET_PID); return syscall(SYS_GET_PID);