1 /* Copyright (C) 1992-2019 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
19 #include <stdio_ext.h>
20 #include <string.h> /* For string function builtin redirect. */
25 #define flockfile(s) _IO_flockfile (s)
26 #define funlockfile(s) _IO_funlockfile (s)
27 #include <libc-lock.h>
29 /* It is desirable to use this bit on systems that have it.
30 The only bit of terminal state we want to twiddle is echoing, which is
31 done in software; there is no need to change the state of the terminal
39 call_fclose (void *arg
)
46 getpass (const char *prompt
)
52 static size_t bufsize
;
55 /* Try to write to and read from the terminal if we can.
56 If we can't open the terminal, use stderr and stdin. */
58 in
= fopen ("/dev/tty", "w+ce");
66 /* We do the locking ourselves. */
67 __fsetlocking (in
, FSETLOCKING_BYCALLER
);
72 /* Make sure the stream we opened is closed even if the thread is
74 __libc_cleanup_push (call_fclose
, in
== out
? in
: NULL
);
78 /* Turn echoing off if it is on now. */
80 if (__tcgetattr (fileno (in
), &t
) == 0)
82 /* Save the old one. */
85 t
.c_lflag
&= ~(ECHO
|ISIG
);
86 tty_changed
= (tcsetattr (fileno (in
), TCSAFLUSH
|TCSASOFT
, &t
) == 0);
91 /* Write the prompt. */
92 __fxprintf (out
, "%s", prompt
);
93 __fflush_unlocked (out
);
95 /* Read the password. */
96 nread
= __getline (&buf
, &bufsize
, in
);
101 else if (buf
[nread
- 1] == '\n')
103 /* Remove the newline. */
104 buf
[nread
- 1] = '\0';
106 /* Write the newline that was not echoed. */
107 __fxprintf (out
, "\n");
111 /* Restore the original setting. */
113 (void) tcsetattr (fileno (in
), TCSAFLUSH
|TCSASOFT
, &s
);
117 __libc_cleanup_pop (0);
120 /* We opened the terminal; now close it. */