1 /* getpass() - read a password Author: Kees J. Bot
5 #define sigaction _sigaction
6 #define sigemptyset _sigemptyset
7 #define tcgetattr _tcgetattr
8 #define tcsetattr _tcsetattr
12 #include <sys/types.h>
21 static void catch(int sig
)
26 char *getpass(const char *prompt
)
28 struct sigaction osa
, sa
;
29 struct termios cooked
, raw
;
30 static char password
[32+1];
33 /* Try to open the controlling terminal. */
34 if ((fd
= open("/dev/tty", O_RDONLY
)) < 0) return NULL
;
36 /* Trap interrupts unless ignored. */
38 sigaction(SIGINT
, NULL
, &osa
);
39 if (osa
.sa_handler
!= SIG_IGN
) {
40 sigemptyset(&sa
.sa_mask
);
43 sigaction(SIGINT
, &sa
, &osa
);
46 /* Set the terminal to non-echo mode. */
47 tcgetattr(fd
, &cooked
);
52 raw
.c_oflag
|= OPOST
| ONLCR
;
53 tcsetattr(fd
, TCSANOW
, &raw
);
55 /* Print the prompt. (After setting non-echo!) */
56 write(2, prompt
, strlen(prompt
));
58 /* Read the password, 32 characters max. */
59 while (read(fd
, password
+n
, 1) > 0) {
60 if (password
[n
] == '\n') break;
65 /* Terminal back to cooked mode. */
66 tcsetattr(fd
, TCSANOW
, &cooked
);
71 sigaction(SIGINT
, &osa
, NULL
);
72 if (intr
) raise(SIGINT
);