2 * An implementation of getpass for systems that lack one.
4 * Copyright (C) 2013 Roman Donchenko
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, visit the http://fsf.org website.
26 char *getpass(const char *prompt
)
28 static char password
[256];
30 BOOL tty_changed
= False
, read_success
;
31 struct termios tty_old
, tty_new
;
32 FILE *in
= stdin
, *out
= stderr
;
33 FILE *tty
= fopen("/dev/tty", "w+");
38 if (tcgetattr(fileno(in
), &tty_old
) == 0) {
40 tty_new
.c_lflag
&= ~(ECHO
| ISIG
);
42 if (tcsetattr(fileno(in
), TCSAFLUSH
, &tty_new
) == 0)
47 fputs("(WARNING: will be visible) ", out
);
51 read_success
= fgets(password
, sizeof password
, in
) != NULL
;
53 /* Print the newline that hasn't been echoed. */
57 tcsetattr(fileno(in
), TCSAFLUSH
, &tty_old
);
63 /* Remove the trailing newline. */
64 size_t password_len
= strlen(password
);
65 if (password_len
&& password
[password_len
- 1] == '\n')
66 password
[password_len
- 1] = '\0';