read.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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/command.h>
  26. #include <grub/i18n.h>
  27. GRUB_MOD_LICENSE ("GPLv3+");
  28. static char *
  29. grub_getline (void)
  30. {
  31. int i;
  32. char *line;
  33. char *tmp;
  34. char c;
  35. i = 0;
  36. line = grub_malloc (1 + i + sizeof('\0'));
  37. if (! line)
  38. return NULL;
  39. while (1)
  40. {
  41. c = grub_getkey ();
  42. if ((c == '\n') || (c == '\r'))
  43. break;
  44. line[i] = c;
  45. if (grub_isprint (c))
  46. grub_printf ("%c", c);
  47. i++;
  48. tmp = grub_realloc (line, 1 + i + sizeof('\0'));
  49. if (! tmp)
  50. {
  51. grub_free (line);
  52. return NULL;
  53. }
  54. line = tmp;
  55. }
  56. line[i] = '\0';
  57. return line;
  58. }
  59. static grub_err_t
  60. grub_cmd_read (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
  61. {
  62. char *line = grub_getline ();
  63. if (! line)
  64. return grub_errno;
  65. if (argc > 0)
  66. grub_env_set (args[0], line);
  67. grub_free (line);
  68. return 0;
  69. }
  70. static grub_command_t cmd;
  71. GRUB_MOD_INIT(read)
  72. {
  73. cmd = grub_register_command ("read", grub_cmd_read,
  74. N_("[ENVVAR]"),
  75. N_("Set variable with user input."));
  76. }
  77. GRUB_MOD_FINI(read)
  78. {
  79. grub_unregister_command (cmd);
  80. }