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;
91 int is_interactive = 0;
93 static void __attribute__((noreturn))
96 if (status != EXIT_SUCCESS)
97 fprintf (stderr, _("Try `%s --help' for more information.\n"),
101 _("%s: guest filesystem shell\n"
102 "%s lets you edit virtual machine filesystems\n"
103 "Copyright (C) 2009-2011 Red Hat Inc.\n"
105 " %s [--options] cmd [: cmd : cmd ...]\n"
107 " -h|--cmd-help List available commands\n"
108 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
109 " -a|--add image Add image\n"
110 " -c|--connect uri Specify libvirt URI for -d option\n"
111 " --csh Make --listen csh-compatible\n"
112 " -d|--domain guest Add disks from libvirt guest\n"
113 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
114 " --echo-keys Don't turn off echo for passphrases\n"
115 " -f|--file file Read commands from file\n"
116 " --format[=raw|..] Force disk format for -a option\n"
117 " -i|--inspector Automatically mount filesystems\n"
118 " --keys-from-stdin Read passphrases from stdin\n"
119 " --listen Listen for remote commands\n"
120 " --live Connect to a live virtual machine\n"
121 " -m|--mount dev[:mnt[:opts]] Mount dev on mnt (if omitted, /)\n"
122 " -n|--no-sync Don't autosync\n"
123 " -N|--new type Create prepared disk (test1.img, ...)\n"
124 " --progress-bars Enable progress bars even when not interactive\n"
125 " --no-progress-bars Disable progress bars\n"
126 " --remote[=pid] Send commands to remote %s\n"
127 " -r|--ro Mount read-only\n"
128 " --selinux Enable SELinux support\n"
129 " -v|--verbose Verbose messages\n"
130 " -V|--version Display version and exit\n"
131 " -w|--rw Mount read-write\n"
132 " -x Echo each command before executing it\n"
134 "To examine a disk image, ISO, hard disk, filesystem etc:\n"
135 " %s [--ro|--rw] -i -a /path/to/disk.img\n"
137 " %s [--ro|--rw] -i -d name-of-libvirt-domain\n"
139 "--ro recommended to avoid any writes to the disk image. If -i option fails\n"
140 "run again without -i and use 'run' + 'list-filesystems' + 'mount' cmds.\n"
142 "For more information, see the manpage %s(1).\n"),
143 program_name, program_name, program_name,
144 program_name, program_name, program_name,
151 main (int argc, char *argv[])
153 /* Set global program name that is not polluted with libtool artifacts. */
154 set_program_name (argv[0]);
156 atexit (close_stdout);
158 setlocale (LC_ALL, "");
159 bindtextdomain (PACKAGE, LOCALEBASEDIR);
160 textdomain (PACKAGE);
166 enum { HELP_OPTION = CHAR_MAX + 1 };
168 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
169 static const struct option long_options[] = {
170 { "add", 1, 0, 'a' },
171 { "cmd-help", 2, 0, 'h' },
172 { "connect", 1, 0, 'c' },
174 { "domain", 1, 0, 'd' },
175 { "echo-keys", 0, 0, 0 },
176 { "file", 1, 0, 'f' },
177 { "format", 2, 0, 0 },
178 { "help", 0, 0, HELP_OPTION },
179 { "inspector", 0, 0, 'i' },
180 { "keys-from-stdin", 0, 0, 0 },
181 { "listen", 0, 0, 0 },
183 { "mount", 1, 0, 'm' },
184 { "new", 1, 0, 'N' },
185 { "no-dest-paths", 0, 0, 'D' },
186 { "no-sync", 0, 0, 'n' },
187 { "progress-bars", 0, 0, 0 },
188 { "no-progress-bars", 0, 0, 0 },
189 { "remote", 2, 0, 0 },
192 { "selinux", 0, 0, 0 },
193 { "verbose", 0, 0, 'v' },
194 { "version", 0, 0, 'V' },
197 struct drv *drvs = NULL;
199 struct mp *mps = NULL;
201 char *p, *file = NULL;
202 const char *format = NULL;
206 int next_prepared_drive = 1;
208 initialize_readline ();
210 memset (&sa, 0, sizeof sa);
211 sa.sa_handler = SIG_IGN;
212 sa.sa_flags = SA_RESTART;
213 sigaction (SIGPIPE, &sa, NULL);
215 /* guestfs_create is meant to be a lightweight operation, so
216 * it's OK to do it early here.
218 g = guestfs_create ();
220 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
224 /* CAUTION: we are careful to modify argv[0] here, only after
225 * using it just above.
227 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
228 * of the original, in case it's needed below.
230 //char *real_argv0 = argv[0];
231 argv[0] = bad_cast (program_name);
234 c = getopt_long (argc, argv, options, long_options, &option_index);
238 case 0: /* options which are long only */
239 if (STREQ (long_options[option_index].name, "listen"))
240 remote_control_listen = 1;
241 else if (STREQ (long_options[option_index].name, "remote")) {
243 if (sscanf (optarg, "%d", &remote_control) != 1) {
244 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
245 program_name, optarg);
249 p = getenv ("GUESTFISH_PID");
250 if (!p || sscanf (p, "%d", &remote_control) != 1) {
251 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
252 " to the PID of the remote process\n"),
257 } else if (STREQ (long_options[option_index].name, "selinux")) {
258 guestfs_set_selinux (g, 1);
259 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
261 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
262 override_progress_bars = 1;
263 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
264 override_progress_bars = 0;
265 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
267 } else if (STREQ (long_options[option_index].name, "format")) {
268 if (!optarg || STREQ (optarg, ""))
272 } else if (STREQ (long_options[option_index].name, "csh")) {
273 remote_control_csh = 1;
274 } else if (STREQ (long_options[option_index].name, "live")) {
277 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
278 program_name, long_options[option_index].name, option_index);
296 complete_dest_paths = 0;
301 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
312 r = display_command (optarg);
313 else if (argv[optind] && argv[optind][0] != '-')
314 r = display_command (argv[optind++]);
318 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
334 if (STRCASEEQ (optarg, "list") ||
335 STRCASEEQ (optarg, "help") ||
336 STRCASEEQ (optarg, "h") ||
337 STRCASEEQ (optarg, "?")) {
338 list_prepared_drives ();
341 drv = malloc (sizeof (struct drv));
349 if (asprintf (&drv->N.filename, "test%d.img",
350 next_prepared_drive++) == -1) {
354 drv->N.data = create_prepared_file (optarg, drv->N.filename);
355 drv->N.data_free = free_prep_data;
381 usage (EXIT_SUCCESS);
384 usage (EXIT_FAILURE);
388 /* Decide here if this will be an interactive session. We have to
389 * do this as soon as possible after processing the command line
392 is_interactive = !file && isatty (0);
394 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
395 * previously, if we have -i without any drives but with something
396 * on the command line, it must be old-style syntax.
398 if (inspector && drvs == NULL && optind < argc) {
399 while (optind < argc) {
400 if (strchr (argv[optind], '/') ||
401 access (argv[optind], F_OK) == 0) { /* simulate -a option */
402 drv = malloc (sizeof (struct drv));
408 drv->a.filename = argv[optind];
409 drv->a.format = NULL;
412 } else { /* simulate -d option */
413 drv = malloc (sizeof (struct drv));
419 drv->d.guest = argv[optind];
428 /* If we've got drives to add, add them now. */
429 add_drives (drvs, 'a');
431 /* If we've got mountpoints or prepared drives or -i option, we must
432 * launch the guest and mount them.
434 if (next_prepared_drive > 1 || mps != NULL || inspector) {
435 /* RHBZ#612178: If --listen flag is given, then we will fork into
436 * the background in rc_listen(). However you can't do this while
437 * holding a libguestfs handle open because the recovery process
438 * will think the main program has died and kill qemu. Therefore
439 * don't use the recovery process for this case. (A better
440 * solution would be to call launch () etc after the fork, but
441 * that greatly complicates the code here).
443 if (remote_control_listen)
444 guestfs_set_recovery_proc (g, 0);
446 if (launch () == -1) exit (EXIT_FAILURE);
451 prepare_drives (drvs);
455 /* Free up data structures, no longer needed after this point. */
459 /* Remote control? */
460 if (remote_control_listen && remote_control) {
462 _("%s: cannot use --listen and --remote options at the same time\n"),
467 if (remote_control_listen) {
470 _("%s: extra parameters on the command line with --listen flag\n"),
476 _("%s: cannot use --listen and --file options at the same time\n"),
483 /* -f (file) parameter? */
486 if (open (file, O_RDONLY) == -1) {
492 /* Decide if we display progress bars. */
494 override_progress_bars >= 0
495 ? override_progress_bars
496 : (optind >= argc && is_interactive);
499 guestfs_set_event_callback (g, progress_callback,
500 GUESTFS_EVENT_PROGRESS, 0, NULL);
502 /* Interactive, shell script, or command(s) on the command line? */
503 if (optind >= argc) {
510 cmdline (argv, optind, argc);
517 /* The <term.h> header file which defines this has "issues". */
518 extern int tgetent (char *, const char *);
521 set_up_terminal (void)
523 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
524 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
526 char *term = getenv ("TERM");
528 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
532 int r = tgetent (NULL, term);
534 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
538 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
547 prepare_drives (struct drv *drv)
550 prepare_drives (drv->next);
551 if (drv->type == drv_N)
552 prepare_drive (drv->N.filename, drv->N.data, drv->device);
559 if (guestfs_is_config (g)) {
560 if (guestfs_launch (g) == -1)
578 #define FISH "><fs> "
580 static char *line_read = NULL;
585 #ifdef HAVE_LIBREADLINE
593 line_read = readline (prompt ? FISH : "");
595 if (line_read && *line_read)
596 add_history_line (line_read);
601 #endif /* HAVE_LIBREADLINE */
603 static char buf[8192];
606 if (prompt) printf (FISH);
607 line_read = fgets (buf, sizeof buf, stdin);
610 len = strlen (line_read);
611 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
621 int global_exit_on_error = !prompt;
623 struct parsed_command pcmd;
627 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
628 "editing virtual machine filesystems.\n"
630 "Type: 'help' for help on commands\n"
631 " 'man' to read the manual\n"
632 " 'quit' to quit the shell\n"
636 print_inspect_prompt ();
642 exit_on_error = global_exit_on_error;
644 buf = rl_gets (prompt);
650 pcmd = parse_command_line (buf, &exit_on_error);
651 if (pcmd.status == -1 && exit_on_error)
653 if (pcmd.status == 1) {
654 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
655 if (exit_on_error) exit (EXIT_FAILURE);
659 if (prompt) printf ("\n");
662 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
663 * This destructively updates 'buf'.
665 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
666 * setting and to return the local setting (eg. if the command begins
669 * Returns in parsed_command.status:
670 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
671 * 0 = no guestfish command, but otherwise OK
674 static struct parsed_command
675 parse_command_line (char *buf, int *exit_on_error_rtn)
677 struct parsed_command pcmd;
682 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
684 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
685 * fields do not need to be, but this silences a gcc warning.
687 memset (&pcmd, 0, sizeof pcmd);
690 /* Skip any initial whitespace before the command. */
691 while (*buf && c_isspace (*buf))
699 /* If the next character is '#' then this is a comment. */
705 /* If the next character is '!' then pass the whole lot to system(3). */
710 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
711 WEXITSTATUS (r) != 0)
718 /* If the next two characters are "<!" then pass the command to
719 * popen(3), read the result and execute it as guestfish commands.
721 if (buf[0] == '<' && buf[1] == '!') {
722 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
730 /* If the next character is '-' allow the command to fail without
731 * exiting on error (just for this one command though).
734 *exit_on_error_rtn = 0;
739 /* Get the command (cannot be quoted). */
740 len = strcspn (buf, " \t");
749 if (buf[len] == '\0') {
757 p += strspn (p, " \t");
759 /* Get the parameters. */
760 while (*p && i < argv_len) {
763 /* Parameters which start with quotes or pipes are treated
764 * specially. Bare parameters are delimited by whitespace.
768 len = strcspn (p, "\"");
769 if (p[len] == '\0') {
770 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
774 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
776 _("%s: command arguments not separated by whitespace\n"),
782 pend = p[len+1] ? &p[len+2] : &p[len+1];
783 } else if (*p == '\'') {
785 len = strcspn (p, "'");
786 if (p[len] == '\0') {
787 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
791 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
793 _("%s: command arguments not separated by whitespace\n"),
799 pend = p[len+1] ? &p[len+2] : &p[len+1];
800 } else if (*p == '|') {
804 } else if (*p != ' ' && *p != '\t') {
805 /* If the first character is a ~ then note that this parameter
806 * is a candidate for ~username expansion. NB this does not
807 * apply to quoted parameters.
809 tilde_candidate = *p == '~';
810 len = strcspn (p, " \t");
817 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
822 if (!tilde_candidate)
825 pcmd.argv[i] = try_tilde_expansion (p);
830 p += strspn (p, " \t");
834 fprintf (stderr, _("%s: too many arguments\n"), program_name);
845 /* Used to handle "<!" (execute command and inline result). */
847 execute_and_inline (const char *cmd, int global_exit_on_error)
854 struct parsed_command pcmd;
856 pp = popen (cmd, "r");
862 while ((n = getline (&line, &len, pp)) != -1) {
863 exit_on_error = global_exit_on_error;
865 /* Chomp final line ending which parse_command_line would not expect. */
866 if (n > 0 && line[n-1] == '\n')
869 pcmd = parse_command_line (line, &exit_on_error);
870 if (pcmd.status == -1 && exit_on_error)
872 if (pcmd.status == 1) {
873 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
874 if (exit_on_error) exit (EXIT_FAILURE);
881 if (pclose (pp) == -1) {
890 cmdline (char *argv[], int optind, int argc)
898 if (optind >= argc) return;
900 cmd = argv[optind++];
901 if (STREQ (cmd, ":")) {
902 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
906 /* Allow -cmd on the command line to mean (temporarily) override
907 * the normal exit on error (RHBZ#578407).
914 params = &argv[optind];
916 /* Search for end of command list or ":" ... */
917 while (optind < argc && STRNEQ (argv[optind], ":"))
920 if (optind == argc) {
921 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
925 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
927 cmdline (argv, optind+1, argc);
931 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
932 * pass to the remote server (when issuing --remote commands). It
933 * does not cause issue_command itself to exit on error.
936 issue_command (const char *cmd, char *argv[], const char *pipecmd,
937 int rc_exit_on_error_flag)
940 int stdout_saved_fd = -1;
944 reset_progress_bar ();
946 /* This counts the commands issued, starting at 1. */
949 /* For | ... commands. Annoyingly we can't use popen(3) here. */
953 if (fflush (stdout) == EOF) {
954 perror ("failed to flush standard output");
958 perror ("pipe failed");
967 if (pid == 0) { /* Child process. */
969 if (dup2 (fd[0], 0) < 0) {
970 perror ("dup2 of stdin failed");
974 r = system (pipecmd);
979 _exit (WEXITSTATUS (r));
982 if ((stdout_saved_fd = dup (1)) < 0) {
983 perror ("failed to dup stdout");
987 if (dup2 (fd[1], 1) < 0) {
988 perror ("failed to dup stdout");
989 close (stdout_saved_fd);
995 for (argc = 0; argv[argc] != NULL; ++argc)
998 /* If --remote was set, then send this command to a remote process. */
1000 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1002 /* Otherwise execute it locally. */
1003 else if (STRCASEEQ (cmd, "help")) {
1008 r = display_command (argv[0]);
1010 else if (STRCASEEQ (cmd, "quit") ||
1011 STRCASEEQ (cmd, "exit") ||
1012 STRCASEEQ (cmd, "q")) {
1017 r = run_action (cmd, argc, argv);
1019 /* Always flush stdout after every command, so that messages, results
1020 * etc appear immediately.
1022 if (fflush (stdout) == EOF) {
1023 perror ("failed to flush standard output");
1029 if (dup2 (stdout_saved_fd, 1) < 0) {
1030 perror ("failed to dup2 standard output");
1033 close (stdout_saved_fd);
1034 if (waitpid (pid, NULL, 0) < 0) {
1035 perror ("waiting for command to complete");
1044 list_builtin_commands (void)
1046 /* help and quit should appear at the top */
1047 printf ("%-20s %s\n",
1048 "help", _("display a list of commands or help on a command"));
1049 printf ("%-20s %s\n",
1050 "quit", _("quit guestfish"));
1052 /* actions are printed after this (see list_commands) */
1056 display_builtin_command (const char *cmd)
1058 /* help for actions is auto-generated, see display_command */
1060 if (STRCASEEQ (cmd, "help")) {
1061 printf (_("help - display a list of commands or help on a command\n"
1066 else if (STRCASEEQ (cmd, "quit") ||
1067 STRCASEEQ (cmd, "exit") ||
1068 STRCASEEQ (cmd, "q")) {
1069 printf (_("quit - quit guestfish\n"
1074 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1080 /* This is printed when the user types in an unknown command for the
1081 * first command issued. A common case is the user doing:
1082 * guestfish disk.img
1083 * expecting guestfish to open 'disk.img' (in fact, this tried to
1084 * run a command 'disk.img').
1087 extended_help_message (void)
1090 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1091 "For a list of commands: guestfish -h\n"
1092 "For complete documentation: man guestfish\n"));
1096 free_strings (char **argv)
1100 for (argc = 0; argv[argc] != NULL; ++argc)
1106 count_strings (char *const *argv)
1110 for (c = 0; argv[c]; ++c)
1116 print_strings (char *const *argv)
1120 for (argc = 0; argv[argc] != NULL; ++argc)
1121 printf ("%s\n", argv[argc]);
1125 print_table (char *const *argv)
1129 for (i = 0; argv[i] != NULL; i += 2)
1130 printf ("%s: %s\n", argv[i], argv[i+1]);
1134 is_true (const char *str)
1137 STRCASENEQ (str, "0") &&
1138 STRCASENEQ (str, "f") &&
1139 STRCASENEQ (str, "false") &&
1140 STRCASENEQ (str, "n") &&
1141 STRCASENEQ (str, "no");
1144 /* Free strings from a non-NULL terminated char** */
1146 free_n_strings (char **str, size_t len)
1150 for (i = 0; i < len; i++) {
1157 parse_string_list (const char *str)
1160 size_t argv_len = 0;
1162 /* Current position pointer */
1163 const char *p = str;
1165 /* Token might be simple:
1168 * 'This is a single token'
1169 * or contain embedded single-quoted sections:
1170 * This' is a sing'l'e to'ken
1172 * The latter may seem over-complicated, but it's what a normal shell does.
1173 * Not doing it risks surprising somebody.
1175 * This outer loop is over complete tokens.
1181 /* Skip leading whitespace */
1182 p += strspn (p, " \t");
1186 /* This loop is over token 'fragments'. A token can be in multiple bits if
1187 * it contains single quotes. We also treat both sides of an escaped quote
1188 * as separate fragments because we can't just copy it: we have to remove
1191 while (*p && (!c_isblank (*p) || in_quote)) {
1192 const char *end = p;
1194 /* Check if the fragment starts with a quote */
1196 /* Toggle in_quote */
1197 in_quote = !in_quote;
1199 /* Skip the quote */
1203 /* If we're in a quote, look for an end quote */
1205 end += strcspn (end, "'");
1208 /* Otherwise, look for whitespace or a quote */
1210 end += strcspn (end, " \t'");
1213 /* Grow the token to accommodate the fragment */
1214 size_t tok_end = tok_len;
1216 char *tok_new = realloc (tok, tok_len + 1);
1217 if (NULL == tok_new) {
1219 free_n_strings (argv, argv_len);
1221 exit (EXIT_FAILURE);
1225 /* Check if we stopped on an escaped quote */
1226 if ('\'' == *end && end != p && *(end-1) == '\\') {
1227 /* Add everything before \' to the token */
1228 memcpy (&tok[tok_end], p, end - p - 1);
1231 tok[tok_len-1] = '\'';
1233 /* Already processed the quote */
1238 /* Add the whole fragment */
1239 memcpy (&tok[tok_end], p, end - p);
1245 /* We've reached the end of a token. We shouldn't still be in quotes. */
1247 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1249 free_n_strings (argv, argv_len);
1254 /* Add this token if there is one. There might not be if there was
1255 * whitespace at the end of the input string */
1257 /* Add the NULL terminator */
1258 tok[tok_len] = '\0';
1260 /* Add the argument to the argument list */
1262 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1263 if (NULL == argv_new) {
1265 free_n_strings (argv, argv_len-1);
1267 exit (EXIT_FAILURE);
1271 argv[argv_len-1] = tok;
1275 /* NULL terminate the argument list */
1277 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1278 if (NULL == argv_new) {
1280 free_n_strings (argv, argv_len-1);
1281 exit (EXIT_FAILURE);
1285 argv[argv_len-1] = NULL;
1290 #ifdef HAVE_LIBREADLINE
1291 static char histfile[1024];
1292 static int nr_history_lines = 0;
1296 initialize_readline (void)
1298 #ifdef HAVE_LIBREADLINE
1301 home = getenv ("HOME");
1303 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1305 (void) read_history (histfile);
1308 rl_readline_name = "guestfish";
1309 rl_attempted_completion_function = do_completion;
1311 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1312 * call the readline(), which happens later. Therefore, these
1313 * provide default values which can be overridden by the user if
1316 (void) rl_variable_bind ("completion-ignore-case", "on");
1321 cleanup_readline (void)
1323 #ifdef HAVE_LIBREADLINE
1326 if (histfile[0] != '\0') {
1327 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1334 #ifdef HAVE_APPEND_HISTORY
1335 (void) append_history (nr_history_lines, histfile);
1337 (void) write_history (histfile);
1344 #ifdef HAVE_LIBREADLINE
1346 add_history_line (const char *line)
1354 xwrite (int fd, const void *v_buf, size_t len)
1357 const char *buf = v_buf;
1360 r = write (fd, buf, len);
1372 /* Resolve the special "win:..." form for Windows-specific paths. The
1373 * generated code calls this for all device or path arguments.
1375 * The function returns a newly allocated string, and the caller must
1376 * free this string; else display an error and return NULL.
1378 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1381 win_prefix (const char *path)
1386 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1387 if (STRCASENEQLEN (path, "win:", 4)) {
1388 ret = strdup (path);
1396 /* If there is a drive letter, rewrite the path. */
1397 if (c_isalpha (path[0]) && path[1] == ':') {
1398 char drive_letter = c_tolower (path[0]);
1399 /* This returns the newly allocated string. */
1400 ret = win_prefix_drive_letter (drive_letter, path + 2);
1412 ret = strdup (path);
1419 /* Blindly convert any backslashes into forward slashes. Is this good? */
1420 for (i = 0; i < strlen (ret); ++i)
1424 char *t = guestfs_case_sensitive_path (g, ret);
1432 win_prefix_drive_letter (char drive_letter, const char *path)
1434 char **roots = NULL;
1435 char **drives = NULL;
1436 char **mountpoints = NULL;
1437 char *device, *mountpoint, *ret = NULL;
1440 /* Resolve the drive letter using the drive mappings table. */
1441 roots = guestfs_inspect_get_roots (g);
1444 if (roots[0] == NULL) {
1445 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1449 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1450 if (drives == NULL || drives[0] == NULL) {
1451 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1457 for (i = 0; drives[i] != NULL; i += 2) {
1458 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1459 device = drives[i+1];
1464 if (device == NULL) {
1465 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1466 program_name, drive_letter, roots[0]);
1470 /* This drive letter must be mounted somewhere (we won't do it). */
1471 mountpoints = guestfs_mountpoints (g);
1472 if (mountpoints == NULL)
1476 for (i = 0; mountpoints[i] != NULL; i += 2) {
1477 if (STREQ (mountpoints[i], device)) {
1478 mountpoint = mountpoints[i+1];
1483 if (mountpoint == NULL) {
1484 fprintf (stderr, _("%s: to access '%c:', mount %s first. One way to do this is:\n umount-all\n mount %s /\n"),
1485 program_name, drive_letter, device, device);
1489 /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1490 if (asprintf (&ret, "%s%s%s",
1491 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1492 perror ("asprintf");
1498 free_strings (roots);
1500 free_strings (drives);
1502 free_strings (mountpoints);
1507 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1508 * The caller (cmds.c) will call free_file_in after the command has
1509 * run which should clean up resources.
1511 static char *file_in_heredoc (const char *endmarker);
1512 static char *file_in_tmpfile = NULL;
1515 file_in (const char *arg)
1519 if (STREQ (arg, "-")) {
1520 ret = strdup ("/dev/stdin");
1526 else if (STRPREFIX (arg, "-<<")) {
1527 const char *endmarker = &arg[3];
1528 if (*endmarker == '\0') {
1529 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1533 ret = file_in_heredoc (endmarker);
1549 file_in_heredoc (const char *endmarker)
1551 TMP_TEMPLATE_ON_STACK (template);
1552 file_in_tmpfile = strdup (template);
1553 if (file_in_tmpfile == NULL) {
1558 int fd = mkstemp (file_in_tmpfile);
1564 size_t markerlen = strlen (endmarker);
1566 char buffer[BUFSIZ];
1567 int write_error = 0;
1568 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1569 /* Look for "END"<EOF> or "END\n" in input. */
1570 size_t blen = strlen (buffer);
1571 if (STREQLEN (buffer, endmarker, markerlen) &&
1572 (blen == markerlen ||
1573 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1576 if (xwrite (fd, buffer, blen) == -1) {
1577 if (!write_error) perror ("write");
1579 /* continue reading up to the end marker */
1583 /* Reached EOF of stdin without finding the end marker, which
1584 * is likely to be an error.
1586 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1587 program_name, endmarker);
1596 if (close (fd) == -1) {
1601 return file_in_tmpfile;
1604 unlink (file_in_tmpfile);
1607 free (file_in_tmpfile);
1608 file_in_tmpfile = NULL;
1613 free_file_in (char *s)
1615 if (file_in_tmpfile) {
1616 if (unlink (file_in_tmpfile) == -1)
1617 perror (file_in_tmpfile);
1618 file_in_tmpfile = NULL;
1621 /* Free the device or file name which was strdup'd in file_in().
1622 * Note it's not immediately clear, but for -<< heredocs,
1623 * s == file_in_tmpfile, so this frees up that buffer.
1628 /* Resolve the special FileOut paths ("-" or filename).
1629 * The caller (cmds.c) will call free (str) after the command has run.
1632 file_out (const char *arg)
1636 if (STREQ (arg, "-"))
1637 ret = strdup ("/dev/stdout");