Serenity Operating System
1/*
2 * Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
3 * Copyright (c) 2021, Emanuele Torre <torreemanuele6@gmail.com>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8#include <LibCore/GetPassword.h>
9#include <LibCore/System.h>
10#include <stdio.h>
11#include <termios.h>
12#include <unistd.h>
13
14namespace Core {
15
16ErrorOr<SecretString> get_password(StringView prompt)
17{
18 TRY(Core::System::write(STDOUT_FILENO, prompt.bytes()));
19
20 auto original = TRY(Core::System::tcgetattr(STDIN_FILENO));
21
22 termios no_echo = original;
23 no_echo.c_lflag &= ~ECHO;
24 TRY(Core::System::tcsetattr(STDIN_FILENO, TCSAFLUSH, no_echo));
25
26 char* password = nullptr;
27 size_t n = 0;
28
29 auto line_length = getline(&password, &n, stdin);
30 auto saved_errno = errno;
31
32 tcsetattr(STDIN_FILENO, TCSAFLUSH, &original);
33 putchar('\n');
34
35 if (line_length < 0)
36 return Error::from_errno(saved_errno);
37
38 VERIFY(line_length != 0);
39
40 // Remove trailing '\n' read by getline().
41 password[line_length - 1] = '\0';
42
43 return TRY(SecretString::take_ownership(password, line_length));
44}
45}