getpass.c 687 B

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