Update github links.
[rsync.git] / lib / getpass.c
blobdea312682474a95d1123d3283092617f84774dca
1 /*
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.
20 #include <stdio.h>
21 #include <string.h>
22 #include <termios.h>
24 #include "rsync.h"
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+");
35 if (tty)
36 in = out = tty;
38 if (tcgetattr(fileno(in), &tty_old) == 0) {
39 tty_new = tty_old;
40 tty_new.c_lflag &= ~(ECHO | ISIG);
42 if (tcsetattr(fileno(in), TCSAFLUSH, &tty_new) == 0)
43 tty_changed = True;
46 if (!tty_changed)
47 fputs("(WARNING: will be visible) ", out);
48 fputs(prompt, out);
49 fflush(out);
51 read_success = fgets(password, sizeof password, in) != NULL;
53 /* Print the newline that hasn't been echoed. */
54 fputc('\n', out);
56 if (tty_changed)
57 tcsetattr(fileno(in), TCSAFLUSH, &tty_old);
59 if (tty)
60 fclose(tty);
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';
68 return password;
71 return NULL;