bb_askpass.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 tarball for details.
  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. if (!passwd)
  29. passwd = xmalloc(sizeof_passwd);
  30. memset(passwd, 0, sizeof_passwd);
  31. tcgetattr(fd, &oldtio);
  32. tcflush(fd, TCIFLUSH);
  33. tio = oldtio;
  34. #ifndef IUCLC
  35. # define IUCLC 0
  36. #endif
  37. tio.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
  38. tio.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
  39. tcsetattr_stdin_TCSANOW(&tio);
  40. memset(&sa, 0, sizeof(sa));
  41. /* sa.sa_flags = 0; - no SA_RESTART! */
  42. /* SIGINT and SIGALRM will interrupt read below */
  43. sa.sa_handler = askpass_timeout;
  44. sigaction(SIGINT, &sa, &oldsa);
  45. if (timeout) {
  46. sigaction_set(SIGALRM, &sa);
  47. alarm(timeout);
  48. }
  49. fputs(prompt, stdout);
  50. fflush_all();
  51. ret = NULL;
  52. /* On timeout or Ctrl-C, read will hopefully be interrupted,
  53. * and we return NULL */
  54. if (read(fd, passwd, sizeof_passwd - 1) > 0) {
  55. ret = passwd;
  56. i = 0;
  57. /* Last byte is guaranteed to be 0
  58. (read did not overwrite it) */
  59. do {
  60. if (passwd[i] == '\r' || passwd[i] == '\n')
  61. passwd[i] = '\0';
  62. } while (passwd[i++]);
  63. }
  64. if (timeout) {
  65. alarm(0);
  66. }
  67. sigaction_set(SIGINT, &oldsa);
  68. tcsetattr_stdin_TCSANOW(&oldtio);
  69. bb_putchar('\n');
  70. fflush_all();
  71. return ret;
  72. }