1// https://stackoverflow.com/questions/1413445/reading-a-password-from-stdcin
2
3#include <common/setTerminalEcho.h>
4#include <stdexcept>
5#include <cstring>
6#include <string>
7
8#ifdef WIN32
9#include <windows.h>
10#else
11#include <termios.h>
12#include <unistd.h>
13#include <errno.h>
14#endif
15
16void setTerminalEcho(bool enable)
17{
18#ifdef WIN32
19 auto handle = GetStdHandle(STD_INPUT_HANDLE);
20 DWORD mode;
21 if (!GetConsoleMode(handle, &mode))
22 throw std::runtime_error(std::string("setTerminalEcho failed get: ") + std::to_string(GetLastError()));
23
24 if (!enable)
25 mode &= ~ENABLE_ECHO_INPUT;
26 else
27 mode |= ENABLE_ECHO_INPUT;
28
29 if (!SetConsoleMode(handle, mode))
30 throw std::runtime_error(std::string("setTerminalEcho failed set: ") + std::to_string(GetLastError()));
31#else
32 struct termios tty;
33 if (tcgetattr(STDIN_FILENO, &tty))
34 throw std::runtime_error(std::string("setTerminalEcho failed get: ") + strerror(errno));
35 if (!enable)
36 tty.c_lflag &= ~ECHO;
37 else
38 tty.c_lflag |= ECHO;
39
40 auto ret = tcsetattr(STDIN_FILENO, TCSANOW, &tty);
41 if (ret)
42 throw std::runtime_error(std::string("setTerminalEcho failed set: ") + strerror(errno));
43#endif
44}
45