read.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* read.c - Command to read variables from user. */
  2. /*
  3. * GRUB -- GRand Unified Bootloader
  4. * Copyright (C) 2006,2007,2008 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/dl.h>
  20. #include <grub/misc.h>
  21. #include <grub/mm.h>
  22. #include <grub/env.h>
  23. #include <grub/term.h>
  24. #include <grub/types.h>
  25. #include <grub/extcmd.h>
  26. #include <grub/i18n.h>
  27. GRUB_MOD_LICENSE ("GPLv3+");
  28. static const struct grub_arg_option options[] =
  29. {
  30. {"silent", 's', 0, N_("Do not echo input"), 0, 0},
  31. {0, 0, 0, 0, 0, 0}
  32. };
  33. static char *
  34. grub_getline (int silent)
  35. {
  36. int i;
  37. char *line;
  38. char *tmp;
  39. int c;
  40. i = 0;
  41. line = grub_malloc (1 + i + sizeof('\0'));
  42. if (! line)
  43. return NULL;
  44. while (1)
  45. {
  46. c = grub_getkey ();
  47. if ((c == '\n') || (c == '\r'))
  48. break;
  49. if (!grub_isprint (c))
  50. continue;
  51. line[i] = (char) c;
  52. if (!silent)
  53. grub_printf ("%c", c);
  54. i++;
  55. tmp = grub_realloc (line, 1 + i + sizeof('\0'));
  56. if (! tmp)
  57. {
  58. grub_free (line);
  59. return NULL;
  60. }
  61. line = tmp;
  62. }
  63. line[i] = '\0';
  64. return line;
  65. }
  66. static grub_err_t
  67. grub_cmd_read (grub_extcmd_context_t ctxt, int argc, char **args)
  68. {
  69. struct grub_arg_list *state = ctxt->state;
  70. char *line = grub_getline (state[0].set);
  71. if (! line)
  72. return grub_errno;
  73. if (argc > 0)
  74. grub_env_set (args[0], line);
  75. grub_free (line);
  76. return 0;
  77. }
  78. static grub_extcmd_t cmd;
  79. GRUB_MOD_INIT(read)
  80. {
  81. cmd = grub_register_extcmd ("read", grub_cmd_read, 0,
  82. N_("[-s] [ENVVAR]"),
  83. N_("Set variable with user input."), options);
  84. }
  85. GRUB_MOD_FINI(read)
  86. {
  87. grub_unregister_extcmd (cmd);
  88. }