1
0

secure_input.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #ifdef WIN32
  23. # include <windows.h>
  24. #else
  25. # include <termios.h>
  26. # include <sys/ioctl.h>
  27. #endif
  28. void
  29. secure_input(char *buf, size_t buf_size)
  30. {
  31. #ifdef WIN32
  32. DWORD mode;
  33. HANDLE ih;
  34. #else
  35. struct termio ttymode;
  36. #endif
  37. int pos;
  38. int ch;
  39. // input checking
  40. if (buf_size < 1) return;
  41. buf[0] = '\n';
  42. // hide input
  43. #ifdef WIN32
  44. ih = GetStdHandle(STD_INPUT_HANDLE);
  45. if (!GetConsoleMode(ih, &mode)) {
  46. fprintf(stderr, "Failed to obtain handle to console\n");
  47. return;
  48. }
  49. SetConsoleMode(ih, mode & ~(ENABLE_ECHO_INPUT ));
  50. #else
  51. ioctl(STDIN_FILENO, TCGETA, &ttymode);
  52. ttymode.c_lflag &= ~( ECHO | ECHOE | ECHONL );
  53. ioctl(STDIN_FILENO, TCSETAF, &ttymode);
  54. #endif
  55. pos=0;
  56. ch=fgetc(stdin);
  57. while (pos < buf_size-1 && ch != '\n' && ch != EOF) {
  58. buf[pos] = ch;
  59. pos++;
  60. ch=fgetc(stdin);
  61. }
  62. buf[pos] = '\0';
  63. // flush the stdin buffer of remaining unused characters
  64. while (ch != '\n' && ch != EOF)
  65. ch = fgetc(stdin);
  66. // unhide input
  67. #ifdef WIN32
  68. SetConsoleMode(ih, mode);
  69. fputc('\n', stdout);
  70. #else
  71. ttymode.c_lflag |= ECHO | ECHOE | ECHONL;
  72. ioctl(STDIN_FILENO, TCSETAF, &ttymode);
  73. fputc('\n', stdout);
  74. #endif
  75. }