Commit | Line | Data |
---|---|---|
843a841b KB |
1 | /* |
2 | * Copyright (c) 1988 The Regents of the University of California. | |
3 | * All rights reserved. | |
4 | * | |
269a7923 | 5 | * %sccs.include.redist.c% |
843a841b KB |
6 | */ |
7 | ||
2ce81398 | 8 | #if defined(LIBC_SCCS) && !defined(lint) |
b258adec | 9 | static char sccsid[] = "@(#)getpass.c 5.7 (Berkeley) %G%"; |
843a841b | 10 | #endif /* LIBC_SCCS and not lint */ |
b8f253e8 | 11 | |
c40ae03a | 12 | #include <sys/termios.h> |
843a841b | 13 | #include <sys/signal.h> |
6a4d2ab3 | 14 | #include <stdio.h> |
c40ae03a | 15 | #include <pwd.h> |
6a4d2ab3 BJ |
16 | |
17 | char * | |
18 | getpass(prompt) | |
843a841b | 19 | char *prompt; |
6a4d2ab3 | 20 | { |
c40ae03a | 21 | struct termios term; |
843a841b | 22 | register int ch; |
6a4d2ab3 | 23 | register char *p; |
843a841b KB |
24 | FILE *fp, *outfp; |
25 | long omask; | |
c40ae03a MT |
26 | int echo; |
27 | static char buf[_PASSWORD_LEN + 1]; | |
6a4d2ab3 | 28 | |
843a841b KB |
29 | /* |
30 | * read and write to /dev/tty if possible; else read from | |
31 | * stdin and write to stderr. | |
32 | */ | |
33 | if ((outfp = fp = fopen("/dev/tty", "w+")) == NULL) { | |
34 | outfp = stderr; | |
35 | fp = stdin; | |
6a4d2ab3 | 36 | } |
c40ae03a MT |
37 | /* |
38 | * note - blocking signals isn't necessarily the | |
39 | * right thing, but we leave it for now. | |
40 | */ | |
41 | omask = sigblock(sigmask(SIGINT)|sigmask(SIGTSTP)); | |
42 | (void)tcgetattr(fileno(fp), &term); | |
43 | if (echo = (term.c_lflag & ECHO)) { | |
44 | term.c_lflag &= ~ECHO; | |
45 | term.c_cflag |= CIGNORE; | |
b258adec | 46 | (void)tcsetattr(fileno(fp), TCSAFLUSH, &term); |
c40ae03a | 47 | } |
5f797d54 | 48 | (void)fputs(prompt, outfp); |
843a841b KB |
49 | rewind(outfp); /* implied flush */ |
50 | for (p = buf; (ch = getc(fp)) != EOF && ch != '\n';) | |
c40ae03a | 51 | if (p < buf + _PASSWORD_LEN) |
843a841b | 52 | *p++ = ch; |
6a4d2ab3 | 53 | *p = '\0'; |
843a841b | 54 | (void)write(fileno(outfp), "\n", 1); |
c40ae03a MT |
55 | if (echo) { |
56 | term.c_lflag |= ECHO; | |
57 | term.c_cflag |= CIGNORE; | |
b258adec | 58 | tcsetattr(fileno(fp), TCSAFLUSH, &term); |
c40ae03a | 59 | } |
843a841b KB |
60 | (void)sigsetmask(omask); |
61 | if (fp != stdin) | |
62 | (void)fclose(fp); | |
63 | return(buf); | |
6a4d2ab3 | 64 | } |