bb_askpass.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 ((i == 0 && r == 0) /* EOF (^D) with no password */
  61. || r < 0
  62. ) {
  63. /* read is interrupted by timeout or ^C */
  64. ret = NULL;
  65. break;
  66. }
  67. if (r == 0 /* EOF */
  68. || ret[i] == '\r' || ret[i] == '\n' /* EOL */
  69. || ++i == sizeof_passwd-1 /* line limit */
  70. ) {
  71. ret[i] = '\0';
  72. break;
  73. }
  74. }
  75. if (timeout) {
  76. alarm(0);
  77. }
  78. sigaction_set(SIGINT, &oldsa);
  79. tcsetattr(fd, TCSANOW, &oldtio);
  80. bb_putchar('\n');
  81. fflush_all();
  82. return ret;
  83. }