Szabolcs Nagy | 5717444 | 2013-12-12 05:09:18 +0000 | [diff] [blame] | 1 | #define _GNU_SOURCE |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 2 | #include <stdio.h> |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 3 | #include <termios.h> |
| 4 | #include <unistd.h> |
| 5 | #include <fcntl.h> |
Rich Felker | ea496d6 | 2014-07-06 01:34:13 -0400 | [diff] [blame] | 6 | #include <string.h> |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 7 | |
| 8 | char *getpass(const char *prompt) |
| 9 | { |
| 10 | int fd; |
| 11 | struct termios s, t; |
| 12 | ssize_t l; |
| 13 | static char password[128]; |
| 14 | |
Rich Felker | ea496d6 | 2014-07-06 01:34:13 -0400 | [diff] [blame] | 15 | if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0) return 0; |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 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 | |
Rich Felker | ea496d6 | 2014-07-06 01:34:13 -0400 | [diff] [blame] | 26 | dprintf(fd, "%s", prompt); |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 27 | |
| 28 | l = read(fd, password, sizeof password); |
| 29 | if (l >= 0) { |
Rich Felker | 3ec8b3a | 2017-03-14 15:13:16 -0400 | [diff] [blame] | 30 | if (l > 0 && password[l-1] == '\n' || l==sizeof password) l--; |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 31 | password[l] = 0; |
| 32 | } |
| 33 | |
| 34 | tcsetattr(fd, TCSAFLUSH, &s); |
| 35 | |
Rich Felker | ea496d6 | 2014-07-06 01:34:13 -0400 | [diff] [blame] | 36 | dprintf(fd, "\n"); |
| 37 | close(fd); |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 38 | |
Rich Felker | ea496d6 | 2014-07-06 01:34:13 -0400 | [diff] [blame] | 39 | return l<0 ? 0 : password; |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 40 | } |