bb_askpass.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Ask for a password
  4. * I use a static buffer in this function. Plan accordingly.
  5. *
  6. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  9. */
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <fcntl.h>
  14. #include <signal.h>
  15. #include <termios.h>
  16. #include <sys/ioctl.h>
  17. #include "libbb.h"
  18. /* do nothing signal handler */
  19. static void askpass_timeout(int ATTRIBUTE_UNUSED ignore)
  20. {
  21. }
  22. char *bb_askpass(int timeout, const char * prompt)
  23. {
  24. static char passwd[64];
  25. char *ret;
  26. int i;
  27. struct sigaction sa;
  28. struct termios old, new;
  29. tcgetattr(STDIN_FILENO, &old);
  30. tcflush(STDIN_FILENO, TCIFLUSH);
  31. memset(passwd, 0, sizeof(passwd));
  32. fputs(prompt, stdout);
  33. fflush(stdout);
  34. tcgetattr(STDIN_FILENO, &new);
  35. new.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
  36. new.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
  37. tcsetattr(STDIN_FILENO, TCSANOW, &new);
  38. if (timeout) {
  39. sa.sa_flags = 0;
  40. sa.sa_handler = askpass_timeout;
  41. sigaction(SIGALRM, &sa, NULL);
  42. alarm(timeout);
  43. }
  44. ret = NULL;
  45. if (read(STDIN_FILENO, passwd, sizeof(passwd)-1) > 0) {
  46. ret = passwd;
  47. i = 0;
  48. /* Last byte is guaranteed to be 0
  49. (read did not overwrite it) */
  50. do {
  51. if (passwd[i] == '\r' || passwd[i] == '\n')
  52. passwd[i] = '\0';
  53. } while (passwd[i++]);
  54. }
  55. if (timeout) {
  56. alarm(0);
  57. }
  58. tcsetattr(STDIN_FILENO, TCSANOW, &old);
  59. puts("");
  60. fflush(stdout);
  61. return ret;
  62. }