getpass.c 744 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <termios.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #include <string.h>
  7. char *getpass(const char *prompt)
  8. {
  9. int fd;
  10. struct termios s, t;
  11. ssize_t l;
  12. static char password[128];
  13. if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0) return 0;
  14. tcgetattr(fd, &t);
  15. s = t;
  16. t.c_lflag &= ~(ECHO|ISIG);
  17. t.c_lflag |= ICANON;
  18. t.c_iflag &= ~(INLCR|IGNCR);
  19. t.c_iflag |= ICRNL;
  20. tcsetattr(fd, TCSAFLUSH, &t);
  21. tcdrain(fd);
  22. dprintf(fd, "%s", prompt);
  23. l = read(fd, password, sizeof password);
  24. if (l >= 0) {
  25. if (l > 0 && password[l-1] == '\n' || l==sizeof password) l--;
  26. password[l] = 0;
  27. }
  28. tcsetattr(fd, TCSAFLUSH, &s);
  29. dprintf(fd, "\n");
  30. close(fd);
  31. return l<0 ? 0 : password;
  32. }