bb_askpass.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 source tree.
  9. */
  10. #include "libbb.h"
  11. /* do nothing signal handler */
  12. static void askpass_timeout(int UNUSED_PARAM ignore)
  13. {
  14. }
  15. char* FAST_FUNC bb_ask_stdin(const char *prompt)
  16. {
  17. return bb_ask(STDIN_FILENO, 0, prompt);
  18. }
  19. char* FAST_FUNC bb_ask(const int fd, int timeout, const char *prompt)
  20. {
  21. /* Was static char[BIGNUM] */
  22. enum { sizeof_passwd = 128 };
  23. static char *passwd;
  24. char *ret;
  25. int i;
  26. struct sigaction sa, oldsa;
  27. struct termios tio, oldtio;
  28. tcgetattr(fd, &oldtio);
  29. tcflush(fd, TCIFLUSH);
  30. tio = oldtio;
  31. #ifndef IUCLC
  32. # define IUCLC 0
  33. #endif
  34. tio.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
  35. tio.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
  36. tcsetattr(fd, TCSANOW, &tio);
  37. memset(&sa, 0, sizeof(sa));
  38. /* sa.sa_flags = 0; - no SA_RESTART! */
  39. /* SIGINT and SIGALRM will interrupt reads below */
  40. sa.sa_handler = askpass_timeout;
  41. sigaction(SIGINT, &sa, &oldsa);
  42. if (timeout) {
  43. sigaction_set(SIGALRM, &sa);
  44. alarm(timeout);
  45. }
  46. fputs(prompt, stdout);
  47. fflush_all();
  48. if (!passwd)
  49. passwd = xmalloc(sizeof_passwd);
  50. ret = passwd;
  51. i = 0;
  52. while (1) {
  53. int r = read(fd, &ret[i], 1);
  54. if (r < 0) {
  55. /* read is interrupted by timeout or ^C */
  56. ret = NULL;
  57. break;
  58. }
  59. if (r == 0 /* EOF */
  60. || ret[i] == '\r' || ret[i] == '\n' /* EOL */
  61. || ++i == sizeof_passwd-1 /* line limit */
  62. ) {
  63. ret[i] = '\0';
  64. break;
  65. }
  66. }
  67. if (timeout) {
  68. alarm(0);
  69. }
  70. sigaction_set(SIGINT, &oldsa);
  71. tcsetattr(fd, TCSANOW, &oldtio);
  72. bb_putchar('\n');
  73. fflush_all();
  74. return ret;
  75. }