getpass.c 935 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * getpass - ask for a password
  3. */
  4. /* $Id$ */
  5. #include <stdlib.h>
  6. #include <signal.h>
  7. #include <string.h>
  8. #include <sgtty.h>
  9. #include <fcntl.h>
  10. int _open(const char *path, int flags);
  11. int _write(int d, const char *buf, int nbytes);
  12. int _read(int d, char *buf, int nbytes);
  13. int _close(int d);
  14. int _stty(int, struct sgttyb *);
  15. int _gtty(int, struct sgttyb *);
  16. char *
  17. getpass(const char *prompt)
  18. {
  19. int i = 0;
  20. struct sgttyb tty, ttysave;
  21. static char pwdbuf[9];
  22. int fd;
  23. void (*savesig)(int);
  24. if ((fd = _open("/dev/tty", O_RDONLY)) < 0) fd = 0;
  25. savesig = signal(SIGINT, SIG_IGN);
  26. _write(2, prompt, strlen(prompt));
  27. _gtty(fd, &tty);
  28. ttysave = tty;
  29. tty.sg_flags &= ~ECHO;
  30. _stty(fd, &tty);
  31. i = _read(fd, pwdbuf, 9);
  32. while (pwdbuf[i - 1] != '\n')
  33. _read(fd, &pwdbuf[i - 1], 1);
  34. pwdbuf[i - 1] = '\0';
  35. _stty(fd, &ttysave);
  36. _write(2, "\n", 1);
  37. if (fd != 0) _close(fd);
  38. signal(SIGINT, savesig);
  39. return(pwdbuf);
  40. }