1 | /* getpass() - read a password Author: Kees J. Bot
|
---|
2 | * Feb 16 1993
|
---|
3 | */
|
---|
4 | #define open _open
|
---|
5 | #define sigaction _sigaction
|
---|
6 | #define sigemptyset _sigemptyset
|
---|
7 | #define tcgetattr _tcgetattr
|
---|
8 | #define tcsetattr _tcsetattr
|
---|
9 | #define write _write
|
---|
10 | #define read _read
|
---|
11 | #define close _close
|
---|
12 | #include <sys/types.h>
|
---|
13 | #include <fcntl.h>
|
---|
14 | #include <unistd.h>
|
---|
15 | #include <signal.h>
|
---|
16 | #include <termios.h>
|
---|
17 | #include <string.h>
|
---|
18 |
|
---|
19 | static int intr;
|
---|
20 |
|
---|
21 | static void catch(int sig)
|
---|
22 | {
|
---|
23 | intr= 1;
|
---|
24 | }
|
---|
25 |
|
---|
26 | char *getpass(const char *prompt)
|
---|
27 | {
|
---|
28 | struct sigaction osa, sa;
|
---|
29 | struct termios cooked, raw;
|
---|
30 | static char password[32+1];
|
---|
31 | int fd, n= 0;
|
---|
32 |
|
---|
33 | /* Try to open the controlling terminal. */
|
---|
34 | if ((fd= open("/dev/tty", O_RDONLY)) < 0) return NULL;
|
---|
35 |
|
---|
36 | /* Trap interrupts unless ignored. */
|
---|
37 | intr= 0;
|
---|
38 | sigaction(SIGINT, NULL, &osa);
|
---|
39 | if (osa.sa_handler != SIG_IGN) {
|
---|
40 | sigemptyset(&sa.sa_mask);
|
---|
41 | sa.sa_flags= 0;
|
---|
42 | sa.sa_handler= catch;
|
---|
43 | sigaction(SIGINT, &sa, &osa);
|
---|
44 | }
|
---|
45 |
|
---|
46 | /* Set the terminal to non-echo mode. */
|
---|
47 | tcgetattr(fd, &cooked);
|
---|
48 | raw= cooked;
|
---|
49 | raw.c_iflag|= ICRNL;
|
---|
50 | raw.c_lflag&= ~ECHO;
|
---|
51 | raw.c_lflag|= ECHONL;
|
---|
52 | raw.c_oflag|= OPOST | ONLCR;
|
---|
53 | tcsetattr(fd, TCSANOW, &raw);
|
---|
54 |
|
---|
55 | /* Print the prompt. (After setting non-echo!) */
|
---|
56 | write(2, prompt, strlen(prompt));
|
---|
57 |
|
---|
58 | /* Read the password, 32 characters max. */
|
---|
59 | while (read(fd, password+n, 1) > 0) {
|
---|
60 | if (password[n] == '\n') break;
|
---|
61 | if (n < 32) n++;
|
---|
62 | }
|
---|
63 | password[n]= 0;
|
---|
64 |
|
---|
65 | /* Terminal back to cooked mode. */
|
---|
66 | tcsetattr(fd, TCSANOW, &cooked);
|
---|
67 |
|
---|
68 | close(fd);
|
---|
69 |
|
---|
70 | /* Interrupt? */
|
---|
71 | sigaction(SIGINT, &osa, NULL);
|
---|
72 | if (intr) raise(SIGINT);
|
---|
73 |
|
---|
74 | return password;
|
---|
75 | }
|
---|