getpass.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #define _POSIX_SOURCE
  10. #define _RESEARCH_SOURCE
  11. #include <stdio.h>
  12. #include <signal.h>
  13. #include <limits.h>
  14. #include <libv.h>
  15. char *
  16. getpass(char *prompt)
  17. {
  18. int c;
  19. char *p;
  20. FILE *fi;
  21. static char pbuf[PASS_MAX];
  22. void (*sig)(int);
  23. if ((fi = fopen("/dev/cons", "r")) == NULL)
  24. fi = stdin;
  25. else
  26. setbuf(fi, NULL);
  27. sig = signal(SIGINT, SIG_IGN);
  28. tty_echooff(fileno(fi));
  29. fprintf(stderr, "%s", prompt);
  30. fflush(stderr);
  31. for (p = pbuf; (c = getc(fi)) != '\n' && c != EOF; )
  32. if (c == ('u' & 037))
  33. p = pbuf;
  34. else if (c == '\b') {
  35. if (p > pbuf)
  36. p--;
  37. } else if (p < &pbuf[sizeof(pbuf)-1])
  38. *p++ = c;
  39. *p = '\0';
  40. fprintf(stderr, "\n");
  41. fflush(stderr);
  42. tty_echoon(fileno(fi));
  43. signal(SIGINT, sig);
  44. if (fi != stdin)
  45. fclose(fi);
  46. return(pbuf);
  47. }