3
0

bb_askpass.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. */
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include <unistd.h>
  25. #include <fcntl.h>
  26. #include <signal.h>
  27. #include <termios.h>
  28. #include <sys/ioctl.h>
  29. #define PWD_BUFFER_SIZE 256
  30. /* do nothing signal handler */
  31. static void askpass_timeout(int ignore)
  32. {
  33. }
  34. char *bb_askpass(int timeout, const char * prompt)
  35. {
  36. char *ret;
  37. int i, size;
  38. struct sigaction sa;
  39. struct termios old, new;
  40. static char passwd[PWD_BUFFER_SIZE];
  41. tcgetattr(STDIN_FILENO, &old);
  42. size = sizeof(passwd);
  43. ret = passwd;
  44. memset(passwd, 0, size);
  45. fputs(prompt, stdout);
  46. fflush(stdout);
  47. tcgetattr(STDIN_FILENO, &new);
  48. new.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
  49. new.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
  50. tcsetattr(STDIN_FILENO, TCSANOW, &new);
  51. if (timeout) {
  52. sa.sa_flags = 0;
  53. sa.sa_handler = askpass_timeout;
  54. sigaction(SIGALRM, &sa, NULL);
  55. alarm(timeout);
  56. }
  57. if (read(STDIN_FILENO, passwd, size-1) <= 0) {
  58. ret = NULL;
  59. } else {
  60. for(i = 0; i < size && passwd[i]; i++) {
  61. if (passwd[i]== '\r' || passwd[i] == '\n') {
  62. passwd[i]= 0;
  63. break;
  64. }
  65. }
  66. }
  67. if (timeout) {
  68. alarm(0);
  69. }
  70. tcsetattr(STDIN_FILENO, TCSANOW, &old);
  71. fputs("\n", stdout);
  72. fflush(stdout);
  73. return ret;
  74. }