GetPassword.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright (c) 2020, Peter Elliott <pelliott@ualberta.ca>
  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 <stdio.h>
  9. #include <stdlib.h>
  10. #include <termios.h>
  11. #include <unistd.h>
  12. namespace Core {
  13. Result<String, OSError> get_password(const StringView& prompt)
  14. {
  15. if (write(STDOUT_FILENO, prompt.characters_without_null_termination(), prompt.length()) < 0)
  16. return OSError(errno);
  17. termios original {};
  18. if (tcgetattr(STDIN_FILENO, &original) < 0)
  19. return OSError(errno);
  20. termios no_echo = original;
  21. no_echo.c_lflag &= ~ECHO;
  22. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &no_echo) < 0)
  23. return OSError(errno);
  24. char* password = nullptr;
  25. size_t n = 0;
  26. auto line_length = getline(&password, &n, stdin);
  27. auto saved_errno = errno;
  28. tcsetattr(STDIN_FILENO, TCSAFLUSH, &original);
  29. putchar('\n');
  30. if (line_length < 0)
  31. return OSError(saved_errno);
  32. VERIFY(line_length != 0);
  33. // Remove trailing '\n' read by getline().
  34. password[line_length - 1] = '\0';
  35. String s(password);
  36. free(password);
  37. return s;
  38. }
  39. }