2018-05-21 17:27:18 +00:00
|
|
|
// https://stackoverflow.com/questions/1413445/reading-a-password-from-stdcin
|
|
|
|
|
2019-02-02 00:25:12 +00:00
|
|
|
#include <common/setTerminalEcho.h>
|
2020-12-17 18:08:42 +00:00
|
|
|
#include <common/errnoToString.h>
|
2018-05-21 17:27:18 +00:00
|
|
|
#include <stdexcept>
|
|
|
|
#include <cstring>
|
2018-05-23 18:28:23 +00:00
|
|
|
#include <string>
|
2018-05-21 17:27:18 +00:00
|
|
|
|
|
|
|
#ifdef WIN32
|
|
|
|
#include <windows.h>
|
|
|
|
#else
|
|
|
|
#include <termios.h>
|
|
|
|
#include <unistd.h>
|
2018-05-23 18:28:23 +00:00
|
|
|
#include <errno.h>
|
2018-05-21 17:27:18 +00:00
|
|
|
#endif
|
|
|
|
|
2019-02-02 00:25:12 +00:00
|
|
|
void setTerminalEcho(bool enable)
|
2018-05-21 17:27:18 +00:00
|
|
|
{
|
|
|
|
#ifdef WIN32
|
|
|
|
auto handle = GetStdHandle(STD_INPUT_HANDLE);
|
|
|
|
DWORD mode;
|
|
|
|
if (!GetConsoleMode(handle, &mode))
|
2019-02-02 00:25:12 +00:00
|
|
|
throw std::runtime_error(std::string("setTerminalEcho failed get: ") + std::to_string(GetLastError()));
|
2018-05-21 17:27:18 +00:00
|
|
|
|
|
|
|
if (!enable)
|
|
|
|
mode &= ~ENABLE_ECHO_INPUT;
|
|
|
|
else
|
|
|
|
mode |= ENABLE_ECHO_INPUT;
|
|
|
|
|
|
|
|
if (!SetConsoleMode(handle, mode))
|
2019-02-02 00:25:12 +00:00
|
|
|
throw std::runtime_error(std::string("setTerminalEcho failed set: ") + std::to_string(GetLastError()));
|
2018-05-21 17:27:18 +00:00
|
|
|
#else
|
|
|
|
struct termios tty;
|
|
|
|
if (tcgetattr(STDIN_FILENO, &tty))
|
2020-12-17 18:08:42 +00:00
|
|
|
throw std::runtime_error(std::string("setTerminalEcho failed get: ") + errnoToString(errno));
|
2018-05-21 17:27:18 +00:00
|
|
|
if (!enable)
|
|
|
|
tty.c_lflag &= ~ECHO;
|
|
|
|
else
|
|
|
|
tty.c_lflag |= ECHO;
|
|
|
|
|
|
|
|
auto ret = tcsetattr(STDIN_FILENO, TCSANOW, &tty);
|
|
|
|
if (ret)
|
2020-12-17 18:08:42 +00:00
|
|
|
throw std::runtime_error(std::string("setTerminalEcho failed set: ") + errnoToString(errno));
|
2018-05-21 17:27:18 +00:00
|
|
|
#endif
|
|
|
|
}
|