| 24 | #include "rsync.h" |
| 25 | |
| 26 | char *getpass(const char *prompt) |
| 27 | { |
| 28 | static char password[256]; |
| 29 | |
| 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+"); |
| 34 | |
| 35 | if (tty) |
| 36 | in = out = tty; |
| 37 | |
| 38 | if (tcgetattr(fileno(in), &tty_old) == 0) { |
| 39 | tty_new = tty_old; |
| 40 | tty_new.c_lflag &= ~(ECHO | ISIG); |
| 41 | |
| 42 | if (tcsetattr(fileno(in), TCSAFLUSH, &tty_new) == 0) |
| 43 | tty_changed = True; |
| 44 | } |
| 45 | |
| 46 | if (!tty_changed) |
| 47 | fputs("(WARNING: will be visible) ", out); |
| 48 | fputs(prompt, out); |
| 49 | fflush(out); |
| 50 | |
| 51 | read_success = fgets(password, sizeof password, in) != NULL; |
| 52 | |
| 53 | /* Print the newline that hasn't been echoed. */ |
| 54 | fputc('\n', out); |
| 55 | |
| 56 | if (tty_changed) |
| 57 | tcsetattr(fileno(in), TCSAFLUSH, &tty_old); |
| 58 | |
| 59 | if (tty) |
| 60 | fclose(tty); |
| 61 | |
| 62 | if (read_success) { |
| 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'; |
| 67 | |
| 68 | return password; |
| 69 | } |
| 70 | |
| 71 | return NULL; |
| 72 | } |