1#define _GNU_SOURCE
2#include <fcntl.h>
3#include <stdio.h>
4#include <string.h>
5#include <termios.h>
6#include <unistd.h>
7
8char* getpass(const char* prompt) {
9    int fd;
10    struct termios s, t;
11    ssize_t l;
12    static char password[128];
13
14    if ((fd = open("/dev/tty", O_RDWR | O_NOCTTY | O_CLOEXEC)) < 0)
15        return 0;
16
17    tcgetattr(fd, &t);
18    s = t;
19    t.c_lflag &= ~(ECHO | ISIG);
20    t.c_lflag |= ICANON;
21    t.c_iflag &= ~(INLCR | IGNCR);
22    t.c_iflag |= ICRNL;
23    tcsetattr(fd, TCSAFLUSH, &t);
24    tcdrain(fd);
25
26    dprintf(fd, "%s", prompt);
27
28    l = read(fd, password, sizeof password);
29    if (l >= 0) {
30        if (l > 0 && password[l - 1] == '\n')
31            l--;
32        password[l] = 0;
33    }
34
35    tcsetattr(fd, TCSAFLUSH, &s);
36
37    dprintf(fd, "\n");
38    close(fd);
39
40    return l < 0 ? 0 : password;
41}
42