#include #include #include #include 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; int outfd; struct termios term; if (read_pw_from_stdin) { infd = 0; outfd = 1; is_tty = tcgetattr(outfd, &term) == 0; } else { infd = outfd = open("/dev/tty", O_RDWR); if (!(infd >= 0 && tcgetattr(outfd, &term) == 0)) return NULL; } 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; }