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