2022-05-05 08:21:48 +02:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <termios.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
|
2022-12-17 00:25:24 +01:00
|
|
|
char* readpassphrase(const char* prompt, char* buf, size_t bufsz, int read_pw_from_stdin) {
|
2022-05-05 08:21:48 +02:00
|
|
|
int n;
|
2022-12-17 00:25:24 +01:00
|
|
|
int is_tty = !read_pw_from_stdin;
|
2022-12-20 22:51:14 +01:00
|
|
|
int infd;
|
|
|
|
int outfd;
|
2022-05-05 08:21:48 +02:00
|
|
|
|
|
|
|
struct termios term;
|
|
|
|
|
2022-12-17 00:25:24 +01:00
|
|
|
if (read_pw_from_stdin) {
|
|
|
|
infd = 0;
|
|
|
|
outfd = 1;
|
|
|
|
is_tty = tcgetattr(outfd, &term) == 0;
|
|
|
|
} else {
|
2022-12-20 22:51:14 +01:00
|
|
|
infd = outfd = open("/dev/tty", O_RDWR);
|
|
|
|
if (!(infd >= 0 && tcgetattr(outfd, &term) == 0))
|
|
|
|
return NULL;
|
2022-05-05 08:21:48 +02:00
|
|
|
}
|
2022-12-17 00:25:24 +01:00
|
|
|
|
|
|
|
if (infd < 0)
|
2022-05-05 08:21:48 +02:00
|
|
|
return NULL;
|
|
|
|
|
2022-12-17 00:25:24 +01:00
|
|
|
if (is_tty) {
|
|
|
|
term.c_lflag &= ~ECHO;
|
|
|
|
tcsetattr(outfd, 0, &term);
|
|
|
|
term.c_lflag |= ECHO;
|
|
|
|
}
|
2022-05-05 08:21:48 +02:00
|
|
|
|
2022-12-17 00:25:24 +01:00
|
|
|
if (write(outfd, prompt, strlen(prompt)) < 0) {
|
|
|
|
if (is_tty)
|
|
|
|
tcsetattr(outfd, 0, &term);
|
2022-05-05 08:21:48 +02:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2022-12-17 00:25:24 +01:00
|
|
|
n = read(infd, buf, bufsz);
|
2022-05-05 08:21:48 +02:00
|
|
|
if (n < 0) {
|
2022-12-17 00:25:24 +01:00
|
|
|
if (is_tty)
|
|
|
|
tcsetattr(outfd, 0, &term);
|
|
|
|
n = write(outfd, "\n", 1);
|
2022-05-05 08:21:48 +02:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
buf[n-1] = '\0';
|
|
|
|
|
2022-05-06 08:13:01 +02:00
|
|
|
// NOTE: As we disabled echo, the enter sent by the user isn't displayed, so we resend it.
|
2022-12-17 00:25:24 +01:00
|
|
|
n = write(outfd, "\n", 1);
|
2022-05-06 08:13:01 +02:00
|
|
|
|
2022-12-17 00:25:24 +01:00
|
|
|
if (is_tty)
|
|
|
|
tcsetattr(outfd, 0, &term);
|
2022-05-05 08:21:48 +02:00
|
|
|
|
|
|
|
return buf;
|
|
|
|
}
|