bb_askpass.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. fputs(prompt, stdout);
  29. fflush_all();
  30. tcflush(fd, TCIFLUSH);
  31. tcgetattr(fd, &oldtio);
  32. tio = oldtio;
  33. #if 0
  34. /* Switch off UPPERCASE->lowercase conversion (never used since 198x)
  35. * and XON/XOFF (why we want to mess with this??)
  36. */
  37. # ifndef IUCLC
  38. # define IUCLC 0
  39. # endif
  40. tio.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
  41. #endif
  42. /* Switch off echo */
  43. tio.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);
  44. tcsetattr(fd, TCSANOW, &tio);
  45. memset(&sa, 0, sizeof(sa));
  46. /* sa.sa_flags = 0; - no SA_RESTART! */
  47. /* SIGINT and SIGALRM will interrupt reads below */
  48. sa.sa_handler = askpass_timeout;
  49. sigaction(SIGINT, &sa, &oldsa);
  50. if (timeout) {
  51. sigaction_set(SIGALRM, &sa);
  52. alarm(timeout);
  53. }
  54. if (!passwd)
  55. passwd = xmalloc(sizeof_passwd);
  56. ret = passwd;
  57. i = 0;
  58. while (1) {
  59. int r = read(fd, &ret[i], 1);
  60. if (r < 0) {
  61. /* read is interrupted by timeout or ^C */
  62. ret = NULL;
  63. break;
  64. }
  65. if (r == 0 /* EOF */
  66. || ret[i] == '\r' || ret[i] == '\n' /* EOL */
  67. || ++i == sizeof_passwd-1 /* line limit */
  68. ) {
  69. ret[i] = '\0';
  70. break;
  71. }
  72. }
  73. if (timeout) {
  74. alarm(0);
  75. }
  76. sigaction_set(SIGINT, &oldsa);
  77. tcsetattr(fd, TCSANOW, &oldtio);
  78. bb_putchar('\n');
  79. fflush_all();
  80. return ret;
  81. }