2020-07-25 17:38:55 -06:00
|
|
|
/*
|
2021-08-31 19:32:46 -07:00
|
|
|
* Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
|
2021-01-10 04:41:30 +01:00
|
|
|
* Copyright (c) 2021, Emanuele Torre <torreemanuele6@gmail.com>
|
2020-07-25 17:38:55 -06:00
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-07-25 17:38:55 -06:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include <LibCore/GetPassword.h>
|
2021-11-29 23:52:30 +01:00
|
|
|
#include <LibCore/System.h>
|
2020-07-25 17:38:55 -06:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <termios.h>
|
2021-03-12 17:29:37 +01:00
|
|
|
#include <unistd.h>
|
2020-07-25 17:38:55 -06:00
|
|
|
|
|
|
|
namespace Core {
|
|
|
|
|
2021-11-07 11:24:26 +01:00
|
|
|
ErrorOr<SecretString> get_password(StringView prompt)
|
2020-07-25 17:38:55 -06:00
|
|
|
{
|
2021-11-29 23:52:30 +01:00
|
|
|
TRY(Core::System::write(STDOUT_FILENO, prompt.bytes()));
|
2020-07-25 17:38:55 -06:00
|
|
|
|
2021-11-29 23:52:30 +01:00
|
|
|
auto original = TRY(Core::System::tcgetattr(STDIN_FILENO));
|
2020-07-25 17:38:55 -06:00
|
|
|
|
2021-01-10 13:48:05 +01:00
|
|
|
termios no_echo = original;
|
2020-07-25 17:38:55 -06:00
|
|
|
no_echo.c_lflag &= ~ECHO;
|
2021-11-29 23:52:30 +01:00
|
|
|
TRY(Core::System::tcsetattr(STDIN_FILENO, TCSAFLUSH, no_echo));
|
2020-07-25 17:38:55 -06:00
|
|
|
|
|
|
|
char* password = nullptr;
|
|
|
|
size_t n = 0;
|
|
|
|
|
2021-01-10 04:41:30 +01:00
|
|
|
auto line_length = getline(&password, &n, stdin);
|
2021-01-10 13:48:05 +01:00
|
|
|
auto saved_errno = errno;
|
2021-01-10 04:41:30 +01:00
|
|
|
|
2020-07-25 17:38:55 -06:00
|
|
|
tcsetattr(STDIN_FILENO, TCSAFLUSH, &original);
|
|
|
|
putchar('\n');
|
2021-01-10 04:41:30 +01:00
|
|
|
|
|
|
|
if (line_length < 0)
|
2021-11-07 11:24:26 +01:00
|
|
|
return Error::from_errno(saved_errno);
|
2021-01-10 04:41:30 +01:00
|
|
|
|
2021-02-23 20:42:32 +01:00
|
|
|
VERIFY(line_length != 0);
|
2021-01-10 04:41:30 +01:00
|
|
|
|
|
|
|
// Remove trailing '\n' read by getline().
|
|
|
|
password[line_length - 1] = '\0';
|
2020-07-25 17:38:55 -06:00
|
|
|
|
2023-02-04 18:52:06 +01:00
|
|
|
return TRY(SecretString::take_ownership(password, line_length));
|
2020-07-25 17:38:55 -06:00
|
|
|
}
|
|
|
|
}
|