ClickHouse/base/common/setTerminalEcho.cpp

45 lines
1.2 KiB
C++
Raw Normal View History

// https://stackoverflow.com/questions/1413445/reading-a-password-from-stdcin
2019-02-02 00:25:12 +00:00
#include <common/setTerminalEcho.h>
#include <stdexcept>
#include <cstring>
2018-05-23 18:28:23 +00:00
#include <string>
#ifdef WIN32
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
2018-05-23 18:28:23 +00:00
#include <errno.h>
#endif
2019-02-02 00:25:12 +00:00
void setTerminalEcho(bool enable)
{
#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()));
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()));
#else
struct termios tty;
if (tcgetattr(STDIN_FILENO, &tty))
2019-02-02 00:25:12 +00:00
throw std::runtime_error(std::string("setTerminalEcho failed get: ") + strerror(errno));
if (!enable)
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
auto ret = tcsetattr(STDIN_FILENO, TCSANOW, &tty);
if (ret)
2019-02-02 00:25:12 +00:00
throw std::runtime_error(std::string("setTerminalEcho failed set: ") + strerror(errno));
#endif
}