GetPassword.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. #include <LibCore/GetPassword.h>
  8. #include <LibCore/System.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <termios.h>
  12. #include <unistd.h>
  13. namespace Core {
  14. ErrorOr<SecretString> get_password(StringView prompt)
  15. {
  16. TRY(Core::System::write(STDOUT_FILENO, prompt.bytes()));
  17. auto original = TRY(Core::System::tcgetattr(STDIN_FILENO));
  18. termios no_echo = original;
  19. no_echo.c_lflag &= ~ECHO;
  20. TRY(Core::System::tcsetattr(STDIN_FILENO, TCSAFLUSH, no_echo));
  21. char* password = nullptr;
  22. size_t n = 0;
  23. auto line_length = getline(&password, &n, stdin);
  24. auto saved_errno = errno;
  25. tcsetattr(STDIN_FILENO, TCSAFLUSH, &original);
  26. putchar('\n');
  27. if (line_length < 0)
  28. return Error::from_errno(saved_errno);
  29. VERIFY(line_length != 0);
  30. // Remove trailing '\n' read by getline().
  31. password[line_length - 1] = '\0';
  32. return SecretString::take_ownership(password, line_length);
  33. }
  34. }