2022-05-05 08:21:48 +02:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <termios.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
|
|
|
|
char* readpassphrase(const char* prompt, char* buf, size_t bufsz) {
|
|
|
|
int n;
|
|
|
|
int ttyfd = -1;
|
|
|
|
|
|
|
|
struct termios term;
|
|
|
|
|
|
|
|
for (int i = 0; i < 3; i++) {
|
|
|
|
if (tcgetattr(i, &term) == 0) {
|
|
|
|
ttyfd = i;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (ttyfd < 0)
|
|
|
|
return NULL;
|
|
|
|
|
|
|
|
term.c_lflag &= ~ECHO;
|
|
|
|
tcsetattr(ttyfd, 0, &term);
|
|
|
|
term.c_lflag |= ECHO;
|
|
|
|
|
2022-12-17 00:12:03 +01:00
|
|
|
if (write(ttyfd, prompt, strlen(prompt)) < 0) {
|
2022-05-05 08:21:48 +02:00
|
|
|
tcsetattr(ttyfd, 0, &term);
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2022-12-17 00:12:03 +01:00
|
|
|
n = read(ttyfd, buf, bufsz);
|
2022-05-05 08:21:48 +02:00
|
|
|
if (n < 0) {
|
|
|
|
tcsetattr(ttyfd, 0, &term);
|
2022-12-17 00:12:03 +01:00
|
|
|
n = write(ttyfd, "\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:12:03 +01:00
|
|
|
n = write(ttyfd, "\n", 1);
|
2022-05-06 08:13:01 +02:00
|
|
|
|
2022-05-05 08:21:48 +02:00
|
|
|
tcsetattr(ttyfd, 0, &term);
|
|
|
|
|
|
|
|
return buf;
|
|
|
|
}
|