secure_input.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * u3-tool - U3 USB stick manager
  3. * Copyright (C) 2007 Daviedev, daviedev@users.sourceforge.net
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. */
  19. #include "secure_input.h"
  20. #include <stdio.h>
  21. #include <unistd.h>
  22. #ifndef WIN32
  23. # include <termios.h>
  24. # include <sys/ioctl.h>
  25. #endif
  26. void
  27. secure_input(char *buf, size_t buf_size)
  28. {
  29. #ifndef WIN32
  30. struct termio ttymode;
  31. #endif
  32. int pos;
  33. int ch;
  34. #ifndef WIN32
  35. // hide input
  36. ioctl(STDIN_FILENO, TCGETA, &ttymode);
  37. ttymode.c_lflag &= ~( ECHO | ECHOE | ECHONL );
  38. ioctl(STDIN_FILENO, TCSETAF, &ttymode);
  39. #endif
  40. pos=0;
  41. ch=fgetc(stdin);
  42. while (pos < buf_size-1 && ch != '\n' && ch != EOF) {
  43. buf[pos] = ch;
  44. pos++;
  45. ch=fgetc(stdin);
  46. }
  47. buf[pos] = '\0';
  48. // flush the stdin buffer of remaining unused characters
  49. while (ch != '\n' && ch != EOF)
  50. ch = fgetc(stdin);
  51. #ifndef WIN32
  52. // unhide input
  53. ttymode.c_lflag |= ECHO | ECHOE | ECHONL;
  54. ioctl(STDIN_FILENO, TCSETAF, &ttymode);
  55. fputc('\n', stdout);
  56. #endif
  57. }