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 /* If developing, add ./appliance to the path. Note that libtools
224 * interferes with this because uninstalled guestfish is a shell
225 * script that runs the real program with an absolute path. Detect
228 * BUT if LIBGUESTFS_PATH environment variable is already set by
229 * the user, then don't override it.
231 if (getenv ("LIBGUESTFS_PATH") == NULL &&
233 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
234 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
236 /* CAUTION: we are careful to modify argv[0] here, only after
237 * using it just above.
239 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
240 * of the original, in case it's needed below.
242 //char *real_argv0 = argv[0];
243 argv[0] = bad_cast (program_name);
246 c = getopt_long (argc, argv, options, long_options, &option_index);
250 case 0: /* options which are long only */
251 if (STREQ (long_options[option_index].name, "listen"))
252 remote_control_listen = 1;
253 else if (STREQ (long_options[option_index].name, "remote")) {
255 if (sscanf (optarg, "%d", &remote_control) != 1) {
256 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
257 program_name, optarg);
261 p = getenv ("GUESTFISH_PID");
262 if (!p || sscanf (p, "%d", &remote_control) != 1) {
263 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
264 " to the PID of the remote process\n"),
269 } else if (STREQ (long_options[option_index].name, "selinux")) {
270 guestfs_set_selinux (g, 1);
271 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
273 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
274 override_progress_bars = 1;
275 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
276 override_progress_bars = 0;
277 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
279 } else if (STREQ (long_options[option_index].name, "format")) {
280 if (!optarg || STREQ (optarg, ""))
284 } else if (STREQ (long_options[option_index].name, "csh")) {
285 remote_control_csh = 1;
286 } else if (STREQ (long_options[option_index].name, "live")) {
289 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
290 program_name, long_options[option_index].name, option_index);
308 complete_dest_paths = 0;
313 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
324 r = display_command (optarg);
325 else if (argv[optind] && argv[optind][0] != '-')
326 r = display_command (argv[optind++]);
330 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
346 if (STRCASEEQ (optarg, "list") ||
347 STRCASEEQ (optarg, "help") ||
348 STRCASEEQ (optarg, "h") ||
349 STRCASEEQ (optarg, "?")) {
350 list_prepared_drives ();
353 drv = malloc (sizeof (struct drv));
361 if (asprintf (&drv->N.filename, "test%d.img",
362 next_prepared_drive++) == -1) {
366 drv->N.data = create_prepared_file (optarg, drv->N.filename);
367 drv->N.data_free = free_prep_data;
393 usage (EXIT_SUCCESS);
396 usage (EXIT_FAILURE);
400 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
401 * previously, if we have -i without any drives but with something
402 * on the command line, it must be old-style syntax.
404 if (inspector && drvs == NULL && optind < argc) {
405 while (optind < argc) {
406 if (strchr (argv[optind], '/') ||
407 access (argv[optind], F_OK) == 0) { /* simulate -a option */
408 drv = malloc (sizeof (struct drv));
414 drv->a.filename = argv[optind];
415 drv->a.format = NULL;
418 } else { /* simulate -d option */
419 drv = malloc (sizeof (struct drv));
425 drv->d.guest = argv[optind];
434 /* If we've got drives to add, add them now. */
435 add_drives (drvs, 'a');
437 /* If we've got mountpoints or prepared drives or -i option, we must
438 * launch the guest and mount them.
440 if (next_prepared_drive > 1 || mps != NULL || inspector) {
441 /* RHBZ#612178: If --listen flag is given, then we will fork into
442 * the background in rc_listen(). However you can't do this while
443 * holding a libguestfs handle open because the recovery process
444 * will think the main program has died and kill qemu. Therefore
445 * don't use the recovery process for this case. (A better
446 * solution would be to call launch () etc after the fork, but
447 * that greatly complicates the code here).
449 if (remote_control_listen)
450 guestfs_set_recovery_proc (g, 0);
452 if (launch () == -1) exit (EXIT_FAILURE);
457 prepare_drives (drvs);
461 /* Free up data structures, no longer needed after this point. */
465 /* Remote control? */
466 if (remote_control_listen && remote_control) {
468 _("%s: cannot use --listen and --remote options at the same time\n"),
473 if (remote_control_listen) {
476 _("%s: extra parameters on the command line with --listen flag\n"),
482 _("%s: cannot use --listen and --file options at the same time\n"),
489 /* -f (file) parameter? */
492 if (open (file, O_RDONLY) == -1) {
498 /* Decide if we display progress bars. */
500 override_progress_bars >= 0
501 ? override_progress_bars
502 : (optind >= argc && isatty (0));
505 guestfs_set_event_callback (g, progress_callback,
506 GUESTFS_EVENT_PROGRESS, 0, NULL);
508 /* Interactive, shell script, or command(s) on the command line? */
509 if (optind >= argc) {
516 cmdline (argv, optind, argc);
523 /* The <term.h> header file which defines this has "issues". */
524 extern int tgetent (char *, const char *);
527 set_up_terminal (void)
529 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
530 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
532 char *term = getenv ("TERM");
534 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
538 int r = tgetent (NULL, term);
540 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
544 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
553 prepare_drives (struct drv *drv)
556 prepare_drives (drv->next);
557 if (drv->type == drv_N)
558 prepare_drive (drv->N.filename, drv->N.data, drv->device);
565 if (guestfs_is_config (g)) {
566 if (guestfs_launch (g) == -1)
584 #define FISH "><fs> "
586 static char *line_read = NULL;
591 #ifdef HAVE_LIBREADLINE
599 line_read = readline (prompt ? FISH : "");
601 if (line_read && *line_read)
602 add_history_line (line_read);
607 #endif /* HAVE_LIBREADLINE */
609 static char buf[8192];
612 if (prompt) printf (FISH);
613 line_read = fgets (buf, sizeof buf, stdin);
616 len = strlen (line_read);
617 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
627 int global_exit_on_error = !prompt;
629 struct parsed_command pcmd;
633 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
634 "editing virtual machine filesystems.\n"
636 "Type: 'help' for help on commands\n"
637 " 'man' to read the manual\n"
638 " 'quit' to quit the shell\n"
642 print_inspect_prompt ();
648 exit_on_error = global_exit_on_error;
650 buf = rl_gets (prompt);
656 pcmd = parse_command_line (buf, &exit_on_error);
657 if (pcmd.status == -1 && exit_on_error)
659 if (pcmd.status == 1) {
660 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
661 if (exit_on_error) exit (EXIT_FAILURE);
665 if (prompt) printf ("\n");
668 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
669 * This destructively updates 'buf'.
671 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
672 * setting and to return the local setting (eg. if the command begins
675 * Returns in parsed_command.status:
676 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
677 * 0 = no guestfish command, but otherwise OK
680 static struct parsed_command
681 parse_command_line (char *buf, int *exit_on_error_rtn)
683 struct parsed_command pcmd;
688 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
690 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
691 * fields do not need to be, but this silences a gcc warning.
693 memset (&pcmd, 0, sizeof pcmd);
696 /* Skip any initial whitespace before the command. */
697 while (*buf && c_isspace (*buf))
705 /* If the next character is '#' then this is a comment. */
711 /* If the next character is '!' then pass the whole lot to system(3). */
716 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
717 WEXITSTATUS (r) != 0)
724 /* If the next two characters are "<!" then pass the command to
725 * popen(3), read the result and execute it as guestfish commands.
727 if (buf[0] == '<' && buf[1] == '!') {
728 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
736 /* If the next character is '-' allow the command to fail without
737 * exiting on error (just for this one command though).
740 *exit_on_error_rtn = 0;
745 /* Get the command (cannot be quoted). */
746 len = strcspn (buf, " \t");
755 if (buf[len] == '\0') {
763 p += strspn (p, " \t");
765 /* Get the parameters. */
766 while (*p && i < argv_len) {
769 /* Parameters which start with quotes or pipes are treated
770 * specially. Bare parameters are delimited by whitespace.
774 len = strcspn (p, "\"");
775 if (p[len] == '\0') {
776 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
780 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
782 _("%s: command arguments not separated by whitespace\n"),
788 pend = p[len+1] ? &p[len+2] : &p[len+1];
789 } else if (*p == '\'') {
791 len = strcspn (p, "'");
792 if (p[len] == '\0') {
793 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
797 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
799 _("%s: command arguments not separated by whitespace\n"),
805 pend = p[len+1] ? &p[len+2] : &p[len+1];
806 } else if (*p == '|') {
810 } else if (*p != ' ' && *p != '\t') {
811 /* If the first character is a ~ then note that this parameter
812 * is a candidate for ~username expansion. NB this does not
813 * apply to quoted parameters.
815 tilde_candidate = *p == '~';
816 len = strcspn (p, " \t");
823 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
828 if (!tilde_candidate)
831 pcmd.argv[i] = try_tilde_expansion (p);
836 p += strspn (p, " \t");
840 fprintf (stderr, _("%s: too many arguments\n"), program_name);
851 /* Used to handle "<!" (execute command and inline result). */
853 execute_and_inline (const char *cmd, int global_exit_on_error)
860 struct parsed_command pcmd;
862 pp = popen (cmd, "r");
868 while ((n = getline (&line, &len, pp)) != -1) {
869 exit_on_error = global_exit_on_error;
871 /* Chomp final line ending which parse_command_line would not expect. */
872 if (n > 0 && line[n-1] == '\n')
875 pcmd = parse_command_line (line, &exit_on_error);
876 if (pcmd.status == -1 && exit_on_error)
878 if (pcmd.status == 1) {
879 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
880 if (exit_on_error) exit (EXIT_FAILURE);
887 if (pclose (pp) == -1) {
896 cmdline (char *argv[], int optind, int argc)
904 if (optind >= argc) return;
906 cmd = argv[optind++];
907 if (STREQ (cmd, ":")) {
908 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
912 /* Allow -cmd on the command line to mean (temporarily) override
913 * the normal exit on error (RHBZ#578407).
920 params = &argv[optind];
922 /* Search for end of command list or ":" ... */
923 while (optind < argc && STRNEQ (argv[optind], ":"))
926 if (optind == argc) {
927 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
931 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
933 cmdline (argv, optind+1, argc);
937 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
938 * pass to the remote server (when issuing --remote commands). It
939 * does not cause issue_command itself to exit on error.
942 issue_command (const char *cmd, char *argv[], const char *pipecmd,
943 int rc_exit_on_error_flag)
946 int stdout_saved_fd = -1;
950 reset_progress_bar ();
952 /* This counts the commands issued, starting at 1. */
955 /* For | ... commands. Annoyingly we can't use popen(3) here. */
959 if (fflush (stdout) == EOF) {
960 perror ("failed to flush standard output");
964 perror ("pipe failed");
973 if (pid == 0) { /* Child process. */
975 if (dup2 (fd[0], 0) < 0) {
976 perror ("dup2 of stdin failed");
980 r = system (pipecmd);
985 _exit (WEXITSTATUS (r));
988 if ((stdout_saved_fd = dup (1)) < 0) {
989 perror ("failed to dup stdout");
993 if (dup2 (fd[1], 1) < 0) {
994 perror ("failed to dup stdout");
995 close (stdout_saved_fd);
1001 for (argc = 0; argv[argc] != NULL; ++argc)
1004 /* If --remote was set, then send this command to a remote process. */
1006 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1008 /* Otherwise execute it locally. */
1009 else if (STRCASEEQ (cmd, "help")) {
1014 r = display_command (argv[0]);
1016 else if (STRCASEEQ (cmd, "quit") ||
1017 STRCASEEQ (cmd, "exit") ||
1018 STRCASEEQ (cmd, "q")) {
1023 r = run_action (cmd, argc, argv);
1025 /* Always flush stdout after every command, so that messages, results
1026 * etc appear immediately.
1028 if (fflush (stdout) == EOF) {
1029 perror ("failed to flush standard output");
1035 if (dup2 (stdout_saved_fd, 1) < 0) {
1036 perror ("failed to dup2 standard output");
1039 close (stdout_saved_fd);
1040 if (waitpid (pid, NULL, 0) < 0) {
1041 perror ("waiting for command to complete");
1050 list_builtin_commands (void)
1052 /* help and quit should appear at the top */
1053 printf ("%-20s %s\n",
1054 "help", _("display a list of commands or help on a command"));
1055 printf ("%-20s %s\n",
1056 "quit", _("quit guestfish"));
1058 /* actions are printed after this (see list_commands) */
1062 display_builtin_command (const char *cmd)
1064 /* help for actions is auto-generated, see display_command */
1066 if (STRCASEEQ (cmd, "help")) {
1067 printf (_("help - display a list of commands or help on a command\n"
1072 else if (STRCASEEQ (cmd, "quit") ||
1073 STRCASEEQ (cmd, "exit") ||
1074 STRCASEEQ (cmd, "q")) {
1075 printf (_("quit - quit guestfish\n"
1080 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1086 /* This is printed when the user types in an unknown command for the
1087 * first command issued. A common case is the user doing:
1088 * guestfish disk.img
1089 * expecting guestfish to open 'disk.img' (in fact, this tried to
1090 * run a command 'disk.img').
1093 extended_help_message (void)
1096 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1097 "For a list of commands: guestfish -h\n"
1098 "For complete documentation: man guestfish\n"));
1102 free_strings (char **argv)
1106 for (argc = 0; argv[argc] != NULL; ++argc)
1112 count_strings (char *const *argv)
1116 for (c = 0; argv[c]; ++c)
1122 print_strings (char *const *argv)
1126 for (argc = 0; argv[argc] != NULL; ++argc)
1127 printf ("%s\n", argv[argc]);
1131 print_table (char *const *argv)
1135 for (i = 0; argv[i] != NULL; i += 2)
1136 printf ("%s: %s\n", argv[i], argv[i+1]);
1140 is_true (const char *str)
1143 STRCASENEQ (str, "0") &&
1144 STRCASENEQ (str, "f") &&
1145 STRCASENEQ (str, "false") &&
1146 STRCASENEQ (str, "n") &&
1147 STRCASENEQ (str, "no");
1150 /* Free strings from a non-NULL terminated char** */
1152 free_n_strings (char **str, size_t len)
1156 for (i = 0; i < len; i++) {
1163 parse_string_list (const char *str)
1166 size_t argv_len = 0;
1168 /* Current position pointer */
1169 const char *p = str;
1171 /* Token might be simple:
1174 * 'This is a single token'
1175 * or contain embedded single-quoted sections:
1176 * This' is a sing'l'e to'ken
1178 * The latter may seem over-complicated, but it's what a normal shell does.
1179 * Not doing it risks surprising somebody.
1181 * This outer loop is over complete tokens.
1187 /* Skip leading whitespace */
1188 p += strspn (p, " \t");
1192 /* This loop is over token 'fragments'. A token can be in multiple bits if
1193 * it contains single quotes. We also treat both sides of an escaped quote
1194 * as separate fragments because we can't just copy it: we have to remove
1197 while (*p && (!c_isblank (*p) || in_quote)) {
1198 const char *end = p;
1200 /* Check if the fragment starts with a quote */
1202 /* Toggle in_quote */
1203 in_quote = !in_quote;
1205 /* Skip the quote */
1209 /* If we're in a quote, look for an end quote */
1211 end += strcspn (end, "'");
1214 /* Otherwise, look for whitespace or a quote */
1216 end += strcspn (end, " \t'");
1219 /* Grow the token to accommodate the fragment */
1220 size_t tok_end = tok_len;
1222 char *tok_new = realloc (tok, tok_len + 1);
1223 if (NULL == tok_new) {
1225 free_n_strings (argv, argv_len);
1227 exit (EXIT_FAILURE);
1231 /* Check if we stopped on an escaped quote */
1232 if ('\'' == *end && end != p && *(end-1) == '\\') {
1233 /* Add everything before \' to the token */
1234 memcpy (&tok[tok_end], p, end - p - 1);
1237 tok[tok_len-1] = '\'';
1239 /* Already processed the quote */
1244 /* Add the whole fragment */
1245 memcpy (&tok[tok_end], p, end - p);
1251 /* We've reached the end of a token. We shouldn't still be in quotes. */
1253 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1255 free_n_strings (argv, argv_len);
1260 /* Add this token if there is one. There might not be if there was
1261 * whitespace at the end of the input string */
1263 /* Add the NULL terminator */
1264 tok[tok_len] = '\0';
1266 /* Add the argument to the argument list */
1268 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1269 if (NULL == argv_new) {
1271 free_n_strings (argv, argv_len-1);
1273 exit (EXIT_FAILURE);
1277 argv[argv_len-1] = tok;
1281 /* NULL terminate the argument list */
1283 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1284 if (NULL == argv_new) {
1286 free_n_strings (argv, argv_len-1);
1287 exit (EXIT_FAILURE);
1291 argv[argv_len-1] = NULL;
1296 #ifdef HAVE_LIBREADLINE
1297 static char histfile[1024];
1298 static int nr_history_lines = 0;
1302 initialize_readline (void)
1304 #ifdef HAVE_LIBREADLINE
1307 home = getenv ("HOME");
1309 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1311 (void) read_history (histfile);
1314 rl_readline_name = "guestfish";
1315 rl_attempted_completion_function = do_completion;
1317 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1318 * call the readline(), which happens later. Therefore, these
1319 * provide default values which can be overridden by the user if
1322 (void) rl_variable_bind ("completion-ignore-case", "on");
1327 cleanup_readline (void)
1329 #ifdef HAVE_LIBREADLINE
1332 if (histfile[0] != '\0') {
1333 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1340 #ifdef HAVE_APPEND_HISTORY
1341 (void) append_history (nr_history_lines, histfile);
1343 (void) write_history (histfile);
1350 #ifdef HAVE_LIBREADLINE
1352 add_history_line (const char *line)
1360 xwrite (int fd, const void *v_buf, size_t len)
1363 const char *buf = v_buf;
1366 r = write (fd, buf, len);
1378 /* Resolve the special "win:..." form for Windows-specific paths. The
1379 * generated code calls this for all device or path arguments. The
1380 * function must return a newly allocated string (caller frees) or
1381 * display an error and return NULL.
1384 win_prefix (const char *path)
1389 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1390 if (STRCASENEQLEN (path, "win:", 4)) {
1391 ret = strdup (path);
1399 /* Is there a drive letter? */
1400 if (c_isalpha (path[0]) && path[1] == ':') {
1402 char **roots, **drives, **mountpoints, *device;
1405 drive_letter = c_tolower (path[0]);
1408 /* Resolve the drive letter using the drive mappings table. */
1409 roots = guestfs_inspect_get_roots (g);
1412 if (roots[0] == NULL) {
1413 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1415 free_strings (roots);
1418 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1419 if (drives == NULL || drives[0] == NULL) {
1420 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1422 free_strings (roots);
1423 free_strings (drives);
1428 for (i = 0; drives[i] != NULL; i += 2) {
1429 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1430 device = drives[i+1];
1435 if (device == NULL) {
1436 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1437 program_name, drive_letter, roots[0]);
1438 free_strings (roots);
1439 free_strings (drives);
1443 /* This drive letter must be mounted on / (we won't do it). */
1444 mountpoints = guestfs_mountpoints (g);
1445 if (mountpoints == NULL) {
1446 free_strings (roots);
1447 free_strings (drives);
1451 for (i = 0; mountpoints[i] != NULL; i += 2) {
1452 if (STREQ (mountpoints[i+1], "/")) {
1453 if (STRNEQ (mountpoints[i], device)) {
1454 fprintf (stderr, _("%s: to access '%c:', mount %s on / first. One way to do this is:\n umount-all\n mount %s /\n"),
1455 program_name, drive_letter, device, device);
1456 free_strings (roots);
1457 free_strings (drives);
1458 free_strings (mountpoints);
1464 free_strings (roots);
1465 free_strings (drives);
1466 free_strings (mountpoints);
1476 ret = strdup (path);
1482 /* Blindly convert any backslashes into forward slashes. Is this good? */
1483 for (i = 0; i < strlen (ret); ++i)
1487 char *t = guestfs_case_sensitive_path (g, ret);
1494 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1495 * The caller (cmds.c) will call free_file_in after the command has
1496 * run which should clean up resources.
1498 static char *file_in_heredoc (const char *endmarker);
1499 static char *file_in_tmpfile = NULL;
1502 file_in (const char *arg)
1506 if (STREQ (arg, "-")) {
1507 ret = strdup ("/dev/stdin");
1513 else if (STRPREFIX (arg, "-<<")) {
1514 const char *endmarker = &arg[3];
1515 if (*endmarker == '\0') {
1516 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1520 ret = file_in_heredoc (endmarker);
1536 file_in_heredoc (const char *endmarker)
1538 TMP_TEMPLATE_ON_STACK (template);
1539 file_in_tmpfile = strdup (template);
1540 if (file_in_tmpfile == NULL) {
1545 int fd = mkstemp (file_in_tmpfile);
1551 size_t markerlen = strlen (endmarker);
1553 char buffer[BUFSIZ];
1554 int write_error = 0;
1555 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1556 /* Look for "END"<EOF> or "END\n" in input. */
1557 size_t blen = strlen (buffer);
1558 if (STREQLEN (buffer, endmarker, markerlen) &&
1559 (blen == markerlen ||
1560 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1563 if (xwrite (fd, buffer, blen) == -1) {
1564 if (!write_error) perror ("write");
1566 /* continue reading up to the end marker */
1570 /* Reached EOF of stdin without finding the end marker, which
1571 * is likely to be an error.
1573 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1574 program_name, endmarker);
1583 if (close (fd) == -1) {
1588 return file_in_tmpfile;
1591 unlink (file_in_tmpfile);
1594 free (file_in_tmpfile);
1595 file_in_tmpfile = NULL;
1600 free_file_in (char *s)
1602 if (file_in_tmpfile) {
1603 if (unlink (file_in_tmpfile) == -1)
1604 perror (file_in_tmpfile);
1605 file_in_tmpfile = NULL;
1608 /* Free the device or file name which was strdup'd in file_in().
1609 * Note it's not immediately clear, but for -<< heredocs,
1610 * s == file_in_tmpfile, so this frees up that buffer.
1615 /* Resolve the special FileOut paths ("-" or filename).
1616 * The caller (cmds.c) will call free (str) after the command has run.
1619 file_out (const char *arg)
1623 if (STREQ (arg, "-"))
1624 ret = strdup ("/dev/stdout");