bb_askpass.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Ask for a password
  4. *
  5. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. #include "libbb.h"
  10. /* do nothing signal handler */
  11. static void askpass_timeout(int UNUSED_PARAM ignore)
  12. {
  13. }
  14. char* FAST_FUNC bb_ask_stdin(const char *prompt)
  15. {
  16. return bb_ask(STDIN_FILENO, 0, prompt);
  17. }
  18. char* FAST_FUNC bb_ask(const int fd, int timeout, const char *prompt)
  19. {
  20. /* Was static char[BIGNUM] */
  21. enum { sizeof_passwd = 128 };
  22. char *passwd;
  23. char *ret;
  24. int i;
  25. struct sigaction sa, oldsa;
  26. struct termios tio, oldtio;
  27. tcflush(fd, TCIFLUSH);
  28. /* Was buggy: was printing prompt *before* flushing input,
  29. * which was upsetting "expect" based scripts of some users.
  30. */
  31. fputs(prompt, stdout);
  32. fflush_all();
  33. tcgetattr(fd, &oldtio);
  34. tio = oldtio;
  35. #if 0
  36. /* Switch off UPPERCASE->lowercase conversion (never used since 198x)
  37. * and XON/XOFF (why we want to mess with this??)
  38. */
  39. # ifndef IUCLC
  40. # define IUCLC 0
  41. # endif
  42. tio.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
  43. #endif
  44. /* Switch off echo */
  45. tio.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);
  46. tcsetattr(fd, TCSANOW, &tio);
  47. memset(&sa, 0, sizeof(sa));
  48. /* sa.sa_flags = 0; - no SA_RESTART! */
  49. /* SIGINT and SIGALRM will interrupt reads below */
  50. sa.sa_handler = askpass_timeout;
  51. sigaction(SIGINT, &sa, &oldsa);
  52. if (timeout) {
  53. sigaction_set(SIGALRM, &sa);
  54. alarm(timeout);
  55. }
  56. passwd = auto_string(xmalloc(sizeof_passwd));
  57. ret = passwd;
  58. i = 0;
  59. while (1) {
  60. int r = read(fd, &ret[i], 1);
  61. if ((i == 0 && r == 0) /* EOF (^D) with no password */
  62. || r < 0
  63. ) {
  64. /* read is interrupted by timeout or ^C */
  65. ret = NULL;
  66. break;
  67. }
  68. if (r == 0 /* EOF */
  69. || ret[i] == '\r' || ret[i] == '\n' /* EOL */
  70. || ++i == sizeof_passwd-1 /* line limit */
  71. ) {
  72. ret[i] = '\0';
  73. break;
  74. }
  75. }
  76. if (timeout) {
  77. alarm(0);
  78. }
  79. sigaction_set(SIGINT, &oldsa);
  80. tcsetattr(fd, TCSANOW, &oldtio);
  81. bb_putchar('\n');
  82. fflush_all();
  83. return ret;
  84. }