1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2011 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #include <sys/types.h>
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
48 /* Return from parse_command_line. See description below. */
49 struct parsed_command {
56 static void set_up_terminal (void);
57 static void prepare_drives (struct drv *drv);
58 static int launch (void);
59 static void interactive (void);
60 static void shell_script (void);
61 static void script (int prompt);
62 static void cmdline (char *argv[], int optind, int argc);
63 static struct parsed_command parse_command_line (char *buf, int *exit_on_error_rtn);
64 static int execute_and_inline (const char *cmd, int exit_on_error);
65 static void initialize_readline (void);
66 static void cleanup_readline (void);
67 #ifdef HAVE_LIBREADLINE
68 static void add_history_line (const char *);
71 static int override_progress_bars = -1;
73 /* Currently open libguestfs handle. */
80 int remote_control_listen = 0;
81 int remote_control_csh = 0;
82 int remote_control = 0;
84 int keys_from_stdin = 0;
86 const char *libvirt_uri = NULL;
89 int have_terminfo = 0;
90 int progress_bars = 0;
92 static void __attribute__((noreturn))
95 if (status != EXIT_SUCCESS)
96 fprintf (stderr, _("Try `%s --help' for more information.\n"),
100 _("%s: guest filesystem shell\n"
101 "%s lets you edit virtual machine filesystems\n"
102 "Copyright (C) 2009-2011 Red Hat Inc.\n"
104 " %s [--options] cmd [: cmd : cmd ...]\n"
106 " -h|--cmd-help List available commands\n"
107 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
108 " -a|--add image Add image\n"
109 " -c|--connect uri Specify libvirt URI for -d option\n"
110 " --csh Make --listen csh-compatible\n"
111 " -d|--domain guest Add disks from libvirt guest\n"
112 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
113 " --echo-keys Don't turn off echo for passphrases\n"
114 " -f|--file file Read commands from file\n"
115 " --format[=raw|..] Force disk format for -a option\n"
116 " -i|--inspector Automatically mount filesystems\n"
117 " --keys-from-stdin Read passphrases from stdin\n"
118 " --listen Listen for remote commands\n"
119 " --live Connect to a live virtual machine\n"
120 " -m|--mount dev[:mnt[:opts]] Mount dev on mnt (if omitted, /)\n"
121 " -n|--no-sync Don't autosync\n"
122 " -N|--new type Create prepared disk (test1.img, ...)\n"
123 " --progress-bars Enable progress bars even when not interactive\n"
124 " --no-progress-bars Disable progress bars\n"
125 " --remote[=pid] Send commands to remote %s\n"
126 " -r|--ro Mount read-only\n"
127 " --selinux Enable SELinux support\n"
128 " -v|--verbose Verbose messages\n"
129 " -V|--version Display version and exit\n"
130 " -w|--rw Mount read-write\n"
131 " -x Echo each command before executing it\n"
133 "To examine a disk image, ISO, hard disk, filesystem etc:\n"
134 " %s [--ro|--rw] -i -a /path/to/disk.img\n"
136 " %s [--ro|--rw] -i -d name-of-libvirt-domain\n"
138 "--ro recommended to avoid any writes to the disk image. If -i option fails\n"
139 "run again without -i and use 'run' + 'list-filesystems' + 'mount' cmds.\n"
141 "For more information, see the manpage %s(1).\n"),
142 program_name, program_name, program_name,
143 program_name, program_name, program_name,
150 main (int argc, char *argv[])
152 /* Set global program name that is not polluted with libtool artifacts. */
153 set_program_name (argv[0]);
155 atexit (close_stdout);
157 setlocale (LC_ALL, "");
158 bindtextdomain (PACKAGE, LOCALEBASEDIR);
159 textdomain (PACKAGE);
165 enum { HELP_OPTION = CHAR_MAX + 1 };
167 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
168 static const struct option long_options[] = {
169 { "add", 1, 0, 'a' },
170 { "cmd-help", 2, 0, 'h' },
171 { "connect", 1, 0, 'c' },
173 { "domain", 1, 0, 'd' },
174 { "echo-keys", 0, 0, 0 },
175 { "file", 1, 0, 'f' },
176 { "format", 2, 0, 0 },
177 { "help", 0, 0, HELP_OPTION },
178 { "inspector", 0, 0, 'i' },
179 { "keys-from-stdin", 0, 0, 0 },
180 { "listen", 0, 0, 0 },
182 { "mount", 1, 0, 'm' },
183 { "new", 1, 0, 'N' },
184 { "no-dest-paths", 0, 0, 'D' },
185 { "no-sync", 0, 0, 'n' },
186 { "progress-bars", 0, 0, 0 },
187 { "no-progress-bars", 0, 0, 0 },
188 { "remote", 2, 0, 0 },
191 { "selinux", 0, 0, 0 },
192 { "verbose", 0, 0, 'v' },
193 { "version", 0, 0, 'V' },
196 struct drv *drvs = NULL;
198 struct mp *mps = NULL;
200 char *p, *file = NULL;
201 const char *format = NULL;
205 int next_prepared_drive = 1;
207 initialize_readline ();
209 memset (&sa, 0, sizeof sa);
210 sa.sa_handler = SIG_IGN;
211 sa.sa_flags = SA_RESTART;
212 sigaction (SIGPIPE, &sa, NULL);
214 /* guestfs_create is meant to be a lightweight operation, so
215 * it's OK to do it early here.
217 g = guestfs_create ();
219 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
223 /* CAUTION: we are careful to modify argv[0] here, only after
224 * using it just above.
226 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
227 * of the original, in case it's needed below.
229 //char *real_argv0 = argv[0];
230 argv[0] = bad_cast (program_name);
233 c = getopt_long (argc, argv, options, long_options, &option_index);
237 case 0: /* options which are long only */
238 if (STREQ (long_options[option_index].name, "listen"))
239 remote_control_listen = 1;
240 else if (STREQ (long_options[option_index].name, "remote")) {
242 if (sscanf (optarg, "%d", &remote_control) != 1) {
243 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
244 program_name, optarg);
248 p = getenv ("GUESTFISH_PID");
249 if (!p || sscanf (p, "%d", &remote_control) != 1) {
250 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
251 " to the PID of the remote process\n"),
256 } else if (STREQ (long_options[option_index].name, "selinux")) {
257 guestfs_set_selinux (g, 1);
258 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
260 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
261 override_progress_bars = 1;
262 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
263 override_progress_bars = 0;
264 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
266 } else if (STREQ (long_options[option_index].name, "format")) {
267 if (!optarg || STREQ (optarg, ""))
271 } else if (STREQ (long_options[option_index].name, "csh")) {
272 remote_control_csh = 1;
273 } else if (STREQ (long_options[option_index].name, "live")) {
276 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
277 program_name, long_options[option_index].name, option_index);
295 complete_dest_paths = 0;
300 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
311 r = display_command (optarg);
312 else if (argv[optind] && argv[optind][0] != '-')
313 r = display_command (argv[optind++]);
317 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
333 if (STRCASEEQ (optarg, "list") ||
334 STRCASEEQ (optarg, "help") ||
335 STRCASEEQ (optarg, "h") ||
336 STRCASEEQ (optarg, "?")) {
337 list_prepared_drives ();
340 drv = malloc (sizeof (struct drv));
348 if (asprintf (&drv->N.filename, "test%d.img",
349 next_prepared_drive++) == -1) {
353 drv->N.data = create_prepared_file (optarg, drv->N.filename);
354 drv->N.data_free = free_prep_data;
380 usage (EXIT_SUCCESS);
383 usage (EXIT_FAILURE);
387 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
388 * previously, if we have -i without any drives but with something
389 * on the command line, it must be old-style syntax.
391 if (inspector && drvs == NULL && optind < argc) {
392 while (optind < argc) {
393 if (strchr (argv[optind], '/') ||
394 access (argv[optind], F_OK) == 0) { /* simulate -a option */
395 drv = malloc (sizeof (struct drv));
401 drv->a.filename = argv[optind];
402 drv->a.format = NULL;
405 } else { /* simulate -d option */
406 drv = malloc (sizeof (struct drv));
412 drv->d.guest = argv[optind];
421 /* If we've got drives to add, add them now. */
422 add_drives (drvs, 'a');
424 /* If we've got mountpoints or prepared drives or -i option, we must
425 * launch the guest and mount them.
427 if (next_prepared_drive > 1 || mps != NULL || inspector) {
428 /* RHBZ#612178: If --listen flag is given, then we will fork into
429 * the background in rc_listen(). However you can't do this while
430 * holding a libguestfs handle open because the recovery process
431 * will think the main program has died and kill qemu. Therefore
432 * don't use the recovery process for this case. (A better
433 * solution would be to call launch () etc after the fork, but
434 * that greatly complicates the code here).
436 if (remote_control_listen)
437 guestfs_set_recovery_proc (g, 0);
439 if (launch () == -1) exit (EXIT_FAILURE);
444 prepare_drives (drvs);
448 /* Free up data structures, no longer needed after this point. */
452 /* Remote control? */
453 if (remote_control_listen && remote_control) {
455 _("%s: cannot use --listen and --remote options at the same time\n"),
460 if (remote_control_listen) {
463 _("%s: extra parameters on the command line with --listen flag\n"),
469 _("%s: cannot use --listen and --file options at the same time\n"),
476 /* -f (file) parameter? */
479 if (open (file, O_RDONLY) == -1) {
485 /* Decide if we display progress bars. */
487 override_progress_bars >= 0
488 ? override_progress_bars
489 : (optind >= argc && isatty (0));
492 guestfs_set_event_callback (g, progress_callback,
493 GUESTFS_EVENT_PROGRESS, 0, NULL);
495 /* Interactive, shell script, or command(s) on the command line? */
496 if (optind >= argc) {
503 cmdline (argv, optind, argc);
510 /* The <term.h> header file which defines this has "issues". */
511 extern int tgetent (char *, const char *);
514 set_up_terminal (void)
516 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
517 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
519 char *term = getenv ("TERM");
521 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
525 int r = tgetent (NULL, term);
527 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
531 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
540 prepare_drives (struct drv *drv)
543 prepare_drives (drv->next);
544 if (drv->type == drv_N)
545 prepare_drive (drv->N.filename, drv->N.data, drv->device);
552 if (guestfs_is_config (g)) {
553 if (guestfs_launch (g) == -1)
571 #define FISH "><fs> "
573 static char *line_read = NULL;
578 #ifdef HAVE_LIBREADLINE
586 line_read = readline (prompt ? FISH : "");
588 if (line_read && *line_read)
589 add_history_line (line_read);
594 #endif /* HAVE_LIBREADLINE */
596 static char buf[8192];
599 if (prompt) printf (FISH);
600 line_read = fgets (buf, sizeof buf, stdin);
603 len = strlen (line_read);
604 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
614 int global_exit_on_error = !prompt;
616 struct parsed_command pcmd;
620 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
621 "editing virtual machine filesystems.\n"
623 "Type: 'help' for help on commands\n"
624 " 'man' to read the manual\n"
625 " 'quit' to quit the shell\n"
629 print_inspect_prompt ();
635 exit_on_error = global_exit_on_error;
637 buf = rl_gets (prompt);
643 pcmd = parse_command_line (buf, &exit_on_error);
644 if (pcmd.status == -1 && exit_on_error)
646 if (pcmd.status == 1) {
647 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
648 if (exit_on_error) exit (EXIT_FAILURE);
652 if (prompt) printf ("\n");
655 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
656 * This destructively updates 'buf'.
658 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
659 * setting and to return the local setting (eg. if the command begins
662 * Returns in parsed_command.status:
663 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
664 * 0 = no guestfish command, but otherwise OK
667 static struct parsed_command
668 parse_command_line (char *buf, int *exit_on_error_rtn)
670 struct parsed_command pcmd;
675 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
677 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
678 * fields do not need to be, but this silences a gcc warning.
680 memset (&pcmd, 0, sizeof pcmd);
683 /* Skip any initial whitespace before the command. */
684 while (*buf && c_isspace (*buf))
692 /* If the next character is '#' then this is a comment. */
698 /* If the next character is '!' then pass the whole lot to system(3). */
703 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
704 WEXITSTATUS (r) != 0)
711 /* If the next two characters are "<!" then pass the command to
712 * popen(3), read the result and execute it as guestfish commands.
714 if (buf[0] == '<' && buf[1] == '!') {
715 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
723 /* If the next character is '-' allow the command to fail without
724 * exiting on error (just for this one command though).
727 *exit_on_error_rtn = 0;
732 /* Get the command (cannot be quoted). */
733 len = strcspn (buf, " \t");
742 if (buf[len] == '\0') {
750 p += strspn (p, " \t");
752 /* Get the parameters. */
753 while (*p && i < argv_len) {
756 /* Parameters which start with quotes or pipes are treated
757 * specially. Bare parameters are delimited by whitespace.
761 len = strcspn (p, "\"");
762 if (p[len] == '\0') {
763 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
767 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
769 _("%s: command arguments not separated by whitespace\n"),
775 pend = p[len+1] ? &p[len+2] : &p[len+1];
776 } else if (*p == '\'') {
778 len = strcspn (p, "'");
779 if (p[len] == '\0') {
780 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
784 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
786 _("%s: command arguments not separated by whitespace\n"),
792 pend = p[len+1] ? &p[len+2] : &p[len+1];
793 } else if (*p == '|') {
797 } else if (*p != ' ' && *p != '\t') {
798 /* If the first character is a ~ then note that this parameter
799 * is a candidate for ~username expansion. NB this does not
800 * apply to quoted parameters.
802 tilde_candidate = *p == '~';
803 len = strcspn (p, " \t");
810 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
815 if (!tilde_candidate)
818 pcmd.argv[i] = try_tilde_expansion (p);
823 p += strspn (p, " \t");
827 fprintf (stderr, _("%s: too many arguments\n"), program_name);
838 /* Used to handle "<!" (execute command and inline result). */
840 execute_and_inline (const char *cmd, int global_exit_on_error)
847 struct parsed_command pcmd;
849 pp = popen (cmd, "r");
855 while ((n = getline (&line, &len, pp)) != -1) {
856 exit_on_error = global_exit_on_error;
858 /* Chomp final line ending which parse_command_line would not expect. */
859 if (n > 0 && line[n-1] == '\n')
862 pcmd = parse_command_line (line, &exit_on_error);
863 if (pcmd.status == -1 && exit_on_error)
865 if (pcmd.status == 1) {
866 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
867 if (exit_on_error) exit (EXIT_FAILURE);
874 if (pclose (pp) == -1) {
883 cmdline (char *argv[], int optind, int argc)
891 if (optind >= argc) return;
893 cmd = argv[optind++];
894 if (STREQ (cmd, ":")) {
895 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
899 /* Allow -cmd on the command line to mean (temporarily) override
900 * the normal exit on error (RHBZ#578407).
907 params = &argv[optind];
909 /* Search for end of command list or ":" ... */
910 while (optind < argc && STRNEQ (argv[optind], ":"))
913 if (optind == argc) {
914 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
918 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
920 cmdline (argv, optind+1, argc);
924 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
925 * pass to the remote server (when issuing --remote commands). It
926 * does not cause issue_command itself to exit on error.
929 issue_command (const char *cmd, char *argv[], const char *pipecmd,
930 int rc_exit_on_error_flag)
933 int stdout_saved_fd = -1;
937 reset_progress_bar ();
939 /* This counts the commands issued, starting at 1. */
942 /* For | ... commands. Annoyingly we can't use popen(3) here. */
946 if (fflush (stdout) == EOF) {
947 perror ("failed to flush standard output");
951 perror ("pipe failed");
960 if (pid == 0) { /* Child process. */
962 if (dup2 (fd[0], 0) < 0) {
963 perror ("dup2 of stdin failed");
967 r = system (pipecmd);
972 _exit (WEXITSTATUS (r));
975 if ((stdout_saved_fd = dup (1)) < 0) {
976 perror ("failed to dup stdout");
980 if (dup2 (fd[1], 1) < 0) {
981 perror ("failed to dup stdout");
982 close (stdout_saved_fd);
988 for (argc = 0; argv[argc] != NULL; ++argc)
991 /* If --remote was set, then send this command to a remote process. */
993 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
995 /* Otherwise execute it locally. */
996 else if (STRCASEEQ (cmd, "help")) {
1001 r = display_command (argv[0]);
1003 else if (STRCASEEQ (cmd, "quit") ||
1004 STRCASEEQ (cmd, "exit") ||
1005 STRCASEEQ (cmd, "q")) {
1010 r = run_action (cmd, argc, argv);
1012 /* Always flush stdout after every command, so that messages, results
1013 * etc appear immediately.
1015 if (fflush (stdout) == EOF) {
1016 perror ("failed to flush standard output");
1022 if (dup2 (stdout_saved_fd, 1) < 0) {
1023 perror ("failed to dup2 standard output");
1026 close (stdout_saved_fd);
1027 if (waitpid (pid, NULL, 0) < 0) {
1028 perror ("waiting for command to complete");
1037 list_builtin_commands (void)
1039 /* help and quit should appear at the top */
1040 printf ("%-20s %s\n",
1041 "help", _("display a list of commands or help on a command"));
1042 printf ("%-20s %s\n",
1043 "quit", _("quit guestfish"));
1045 /* actions are printed after this (see list_commands) */
1049 display_builtin_command (const char *cmd)
1051 /* help for actions is auto-generated, see display_command */
1053 if (STRCASEEQ (cmd, "help")) {
1054 printf (_("help - display a list of commands or help on a command\n"
1059 else if (STRCASEEQ (cmd, "quit") ||
1060 STRCASEEQ (cmd, "exit") ||
1061 STRCASEEQ (cmd, "q")) {
1062 printf (_("quit - quit guestfish\n"
1067 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1073 /* This is printed when the user types in an unknown command for the
1074 * first command issued. A common case is the user doing:
1075 * guestfish disk.img
1076 * expecting guestfish to open 'disk.img' (in fact, this tried to
1077 * run a command 'disk.img').
1080 extended_help_message (void)
1083 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1084 "For a list of commands: guestfish -h\n"
1085 "For complete documentation: man guestfish\n"));
1089 free_strings (char **argv)
1093 for (argc = 0; argv[argc] != NULL; ++argc)
1099 count_strings (char *const *argv)
1103 for (c = 0; argv[c]; ++c)
1109 print_strings (char *const *argv)
1113 for (argc = 0; argv[argc] != NULL; ++argc)
1114 printf ("%s\n", argv[argc]);
1118 print_table (char *const *argv)
1122 for (i = 0; argv[i] != NULL; i += 2)
1123 printf ("%s: %s\n", argv[i], argv[i+1]);
1127 is_true (const char *str)
1130 STRCASENEQ (str, "0") &&
1131 STRCASENEQ (str, "f") &&
1132 STRCASENEQ (str, "false") &&
1133 STRCASENEQ (str, "n") &&
1134 STRCASENEQ (str, "no");
1137 /* Free strings from a non-NULL terminated char** */
1139 free_n_strings (char **str, size_t len)
1143 for (i = 0; i < len; i++) {
1150 parse_string_list (const char *str)
1153 size_t argv_len = 0;
1155 /* Current position pointer */
1156 const char *p = str;
1158 /* Token might be simple:
1161 * 'This is a single token'
1162 * or contain embedded single-quoted sections:
1163 * This' is a sing'l'e to'ken
1165 * The latter may seem over-complicated, but it's what a normal shell does.
1166 * Not doing it risks surprising somebody.
1168 * This outer loop is over complete tokens.
1174 /* Skip leading whitespace */
1175 p += strspn (p, " \t");
1179 /* This loop is over token 'fragments'. A token can be in multiple bits if
1180 * it contains single quotes. We also treat both sides of an escaped quote
1181 * as separate fragments because we can't just copy it: we have to remove
1184 while (*p && (!c_isblank (*p) || in_quote)) {
1185 const char *end = p;
1187 /* Check if the fragment starts with a quote */
1189 /* Toggle in_quote */
1190 in_quote = !in_quote;
1192 /* Skip the quote */
1196 /* If we're in a quote, look for an end quote */
1198 end += strcspn (end, "'");
1201 /* Otherwise, look for whitespace or a quote */
1203 end += strcspn (end, " \t'");
1206 /* Grow the token to accommodate the fragment */
1207 size_t tok_end = tok_len;
1209 char *tok_new = realloc (tok, tok_len + 1);
1210 if (NULL == tok_new) {
1212 free_n_strings (argv, argv_len);
1214 exit (EXIT_FAILURE);
1218 /* Check if we stopped on an escaped quote */
1219 if ('\'' == *end && end != p && *(end-1) == '\\') {
1220 /* Add everything before \' to the token */
1221 memcpy (&tok[tok_end], p, end - p - 1);
1224 tok[tok_len-1] = '\'';
1226 /* Already processed the quote */
1231 /* Add the whole fragment */
1232 memcpy (&tok[tok_end], p, end - p);
1238 /* We've reached the end of a token. We shouldn't still be in quotes. */
1240 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1242 free_n_strings (argv, argv_len);
1247 /* Add this token if there is one. There might not be if there was
1248 * whitespace at the end of the input string */
1250 /* Add the NULL terminator */
1251 tok[tok_len] = '\0';
1253 /* Add the argument to the argument list */
1255 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1256 if (NULL == argv_new) {
1258 free_n_strings (argv, argv_len-1);
1260 exit (EXIT_FAILURE);
1264 argv[argv_len-1] = tok;
1268 /* NULL terminate the argument list */
1270 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1271 if (NULL == argv_new) {
1273 free_n_strings (argv, argv_len-1);
1274 exit (EXIT_FAILURE);
1278 argv[argv_len-1] = NULL;
1283 #ifdef HAVE_LIBREADLINE
1284 static char histfile[1024];
1285 static int nr_history_lines = 0;
1289 initialize_readline (void)
1291 #ifdef HAVE_LIBREADLINE
1294 home = getenv ("HOME");
1296 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1298 (void) read_history (histfile);
1301 rl_readline_name = "guestfish";
1302 rl_attempted_completion_function = do_completion;
1304 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1305 * call the readline(), which happens later. Therefore, these
1306 * provide default values which can be overridden by the user if
1309 (void) rl_variable_bind ("completion-ignore-case", "on");
1314 cleanup_readline (void)
1316 #ifdef HAVE_LIBREADLINE
1319 if (histfile[0] != '\0') {
1320 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1327 #ifdef HAVE_APPEND_HISTORY
1328 (void) append_history (nr_history_lines, histfile);
1330 (void) write_history (histfile);
1337 #ifdef HAVE_LIBREADLINE
1339 add_history_line (const char *line)
1347 xwrite (int fd, const void *v_buf, size_t len)
1350 const char *buf = v_buf;
1353 r = write (fd, buf, len);
1365 /* Resolve the special "win:..." form for Windows-specific paths. The
1366 * generated code calls this for all device or path arguments.
1368 * The function returns a newly allocated string, and the caller must
1369 * free this string; else display an error and return NULL.
1371 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1374 win_prefix (const char *path)
1379 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1380 if (STRCASENEQLEN (path, "win:", 4)) {
1381 ret = strdup (path);
1389 /* If there is a drive letter, rewrite the path. */
1390 if (c_isalpha (path[0]) && path[1] == ':') {
1391 char drive_letter = c_tolower (path[0]);
1392 /* This returns the newly allocated string. */
1393 ret = win_prefix_drive_letter (drive_letter, path + 2);
1405 ret = strdup (path);
1412 /* Blindly convert any backslashes into forward slashes. Is this good? */
1413 for (i = 0; i < strlen (ret); ++i)
1417 char *t = guestfs_case_sensitive_path (g, ret);
1425 win_prefix_drive_letter (char drive_letter, const char *path)
1427 char **roots = NULL;
1428 char **drives = NULL;
1429 char **mountpoints = NULL;
1430 char *device, *mountpoint, *ret = NULL;
1433 /* Resolve the drive letter using the drive mappings table. */
1434 roots = guestfs_inspect_get_roots (g);
1437 if (roots[0] == NULL) {
1438 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1442 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1443 if (drives == NULL || drives[0] == NULL) {
1444 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1450 for (i = 0; drives[i] != NULL; i += 2) {
1451 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1452 device = drives[i+1];
1457 if (device == NULL) {
1458 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1459 program_name, drive_letter, roots[0]);
1463 /* This drive letter must be mounted somewhere (we won't do it). */
1464 mountpoints = guestfs_mountpoints (g);
1465 if (mountpoints == NULL)
1469 for (i = 0; mountpoints[i] != NULL; i += 2) {
1470 if (STREQ (mountpoints[i], device)) {
1471 mountpoint = mountpoints[i+1];
1476 if (mountpoint == NULL) {
1477 fprintf (stderr, _("%s: to access '%c:', mount %s first. One way to do this is:\n umount-all\n mount %s /\n"),
1478 program_name, drive_letter, device, device);
1482 /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1483 if (asprintf (&ret, "%s%s%s",
1484 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1485 perror ("asprintf");
1491 free_strings (roots);
1493 free_strings (drives);
1495 free_strings (mountpoints);
1500 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1501 * The caller (cmds.c) will call free_file_in after the command has
1502 * run which should clean up resources.
1504 static char *file_in_heredoc (const char *endmarker);
1505 static char *file_in_tmpfile = NULL;
1508 file_in (const char *arg)
1512 if (STREQ (arg, "-")) {
1513 ret = strdup ("/dev/stdin");
1519 else if (STRPREFIX (arg, "-<<")) {
1520 const char *endmarker = &arg[3];
1521 if (*endmarker == '\0') {
1522 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1526 ret = file_in_heredoc (endmarker);
1542 file_in_heredoc (const char *endmarker)
1544 TMP_TEMPLATE_ON_STACK (template);
1545 file_in_tmpfile = strdup (template);
1546 if (file_in_tmpfile == NULL) {
1551 int fd = mkstemp (file_in_tmpfile);
1557 size_t markerlen = strlen (endmarker);
1559 char buffer[BUFSIZ];
1560 int write_error = 0;
1561 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1562 /* Look for "END"<EOF> or "END\n" in input. */
1563 size_t blen = strlen (buffer);
1564 if (STREQLEN (buffer, endmarker, markerlen) &&
1565 (blen == markerlen ||
1566 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1569 if (xwrite (fd, buffer, blen) == -1) {
1570 if (!write_error) perror ("write");
1572 /* continue reading up to the end marker */
1576 /* Reached EOF of stdin without finding the end marker, which
1577 * is likely to be an error.
1579 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1580 program_name, endmarker);
1589 if (close (fd) == -1) {
1594 return file_in_tmpfile;
1597 unlink (file_in_tmpfile);
1600 free (file_in_tmpfile);
1601 file_in_tmpfile = NULL;
1606 free_file_in (char *s)
1608 if (file_in_tmpfile) {
1609 if (unlink (file_in_tmpfile) == -1)
1610 perror (file_in_tmpfile);
1611 file_in_tmpfile = NULL;
1614 /* Free the device or file name which was strdup'd in file_in().
1615 * Note it's not immediately clear, but for -<< heredocs,
1616 * s == file_in_tmpfile, so this frees up that buffer.
1621 /* Resolve the special FileOut paths ("-" or filename).
1622 * The caller (cmds.c) will call free (str) after the command has run.
1625 file_out (const char *arg)
1629 if (STREQ (arg, "-"))
1630 ret = strdup ("/dev/stdout");