GetPassword.cpp 1.1 KB

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