password.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * GRUB -- GRand Unified Bootloader
  3. * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2006
  4. * 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
  5. *
  6. * GRUB is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * GRUB is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <grub/crypto.h>
  20. #include <grub/mm.h>
  21. #include <grub/term.h>
  22. #include <termios.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <stdio.h>
  26. int
  27. grub_password_get (char buf[], unsigned buf_size)
  28. {
  29. FILE *in;
  30. struct termios s, t;
  31. int tty_changed = 0;
  32. char *ptr;
  33. grub_refresh ();
  34. /* Disable echoing. Based on glibc. */
  35. in = fopen ("/dev/tty", "w+c");
  36. if (in == NULL)
  37. in = stdin;
  38. if (tcgetattr (fileno (in), &t) == 0)
  39. {
  40. /* Save the old one. */
  41. s = t;
  42. /* Tricky, tricky. */
  43. t.c_lflag &= ~(ECHO|ISIG);
  44. tty_changed = (tcsetattr (fileno (in), TCSAFLUSH, &t) == 0);
  45. }
  46. else
  47. tty_changed = 0;
  48. grub_memset (buf, 0, buf_size);
  49. if (!fgets (buf, buf_size, stdin))
  50. {
  51. if (in != stdin)
  52. fclose (in);
  53. return 0;
  54. }
  55. ptr = buf + strlen (buf) - 1;
  56. while (buf <= ptr && (*ptr == '\n' || *ptr == '\r'))
  57. *ptr-- = 0;
  58. /* Restore the original setting. */
  59. if (tty_changed)
  60. (void) tcsetattr (fileno (in), TCSAFLUSH, &s);
  61. grub_xputs ("\n");
  62. grub_refresh ();
  63. if (in != stdin)
  64. fclose (in);
  65. return 1;
  66. }