3
0

bb_askpass.c 2.0 KB

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