forked from soccera/rdo
60 lines
1.3 KiB
C
60 lines
1.3 KiB
C
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <termios.h>
|
|
#include <fcntl.h>
|
|
|
|
char* readpassphrase(const char* prompt, char* buf, size_t bufsz, int read_pw_from_stdin) {
|
|
int n;
|
|
int is_tty = !read_pw_from_stdin;
|
|
int infd = -1;
|
|
int outfd = -1;
|
|
|
|
struct termios term;
|
|
|
|
if (read_pw_from_stdin) {
|
|
infd = 0;
|
|
outfd = 1;
|
|
is_tty = tcgetattr(outfd, &term) == 0;
|
|
} else {
|
|
for (int i = 0; i < 3; i++) {
|
|
if (tcgetattr(i, &term) == 0) {
|
|
infd = i;
|
|
outfd = i;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (infd < 0)
|
|
return NULL;
|
|
|
|
if (is_tty) {
|
|
term.c_lflag &= ~ECHO;
|
|
tcsetattr(outfd, 0, &term);
|
|
term.c_lflag |= ECHO;
|
|
}
|
|
|
|
if (write(outfd, prompt, strlen(prompt)) < 0) {
|
|
if (is_tty)
|
|
tcsetattr(outfd, 0, &term);
|
|
return NULL;
|
|
}
|
|
|
|
n = read(infd, buf, bufsz);
|
|
if (n < 0) {
|
|
if (is_tty)
|
|
tcsetattr(outfd, 0, &term);
|
|
n = write(outfd, "\n", 1);
|
|
return NULL;
|
|
}
|
|
|
|
buf[n-1] = '\0';
|
|
|
|
// NOTE: As we disabled echo, the enter sent by the user isn't displayed, so we resend it.
|
|
n = write(outfd, "\n", 1);
|
|
|
|
if (is_tty)
|
|
tcsetattr(outfd, 0, &term);
|
|
|
|
return buf;
|
|
}
|