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>
49 /* Return from parse_command_line. See description below. */
50 struct parsed_command {
57 static void user_cancel (int);
58 static void prepare_drives (struct drv *drv);
59 static int launch (void);
60 static void interactive (void);
61 static void shell_script (void);
62 static void script (int prompt);
63 static void cmdline (char *argv[], int optind, int argc);
64 static struct parsed_command parse_command_line (char *buf, int *exit_on_error_rtn);
65 static int parse_quoted_string (char *p);
66 static int execute_and_inline (const char *cmd, int exit_on_error);
67 static void initialize_readline (void);
68 static void cleanup_readline (void);
69 #ifdef HAVE_LIBREADLINE
70 static void add_history_line (const char *);
73 static int override_progress_bars = -1;
74 static struct progress_bar *bar = NULL;
76 /* Currently open libguestfs handle. */
83 int remote_control_listen = 0;
84 int remote_control_csh = 0;
85 int remote_control = 0;
87 int keys_from_stdin = 0;
89 const char *libvirt_uri = NULL;
91 int progress_bars = 0;
92 int is_interactive = 0;
94 static void __attribute__((noreturn))
97 if (status != EXIT_SUCCESS)
98 fprintf (stderr, _("Try `%s --help' for more information.\n"),
102 _("%s: guest filesystem shell\n"
103 "%s lets you edit virtual machine filesystems\n"
104 "Copyright (C) 2009-2011 Red Hat Inc.\n"
106 " %s [--options] cmd [: cmd : cmd ...]\n"
108 " -h|--cmd-help List available commands\n"
109 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
110 " -a|--add image Add image\n"
111 " -c|--connect uri Specify libvirt URI for -d option\n"
112 " --csh Make --listen csh-compatible\n"
113 " -d|--domain guest Add disks from libvirt guest\n"
114 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
115 " --echo-keys Don't turn off echo for passphrases\n"
116 " -f|--file file Read commands from file\n"
117 " --format[=raw|..] Force disk format for -a option\n"
118 " -i|--inspector Automatically mount filesystems\n"
119 " --keys-from-stdin Read passphrases from stdin\n"
120 " --listen Listen for remote commands\n"
121 " --live Connect to a live virtual machine\n"
122 " -m|--mount dev[:mnt[:opts]] Mount dev on mnt (if omitted, /)\n"
123 " -n|--no-sync Don't autosync\n"
124 " -N|--new type Create prepared disk (test1.img, ...)\n"
125 " --progress-bars Enable progress bars even when not interactive\n"
126 " --no-progress-bars Disable progress bars\n"
127 " --remote[=pid] Send commands to remote %s\n"
128 " -r|--ro Mount read-only\n"
129 " --selinux Enable SELinux support\n"
130 " -v|--verbose Verbose messages\n"
131 " -V|--version Display version and exit\n"
132 " -w|--rw Mount read-write\n"
133 " -x Echo each command before executing it\n"
135 "To examine a disk image, ISO, hard disk, filesystem etc:\n"
136 " %s [--ro|--rw] -i -a /path/to/disk.img\n"
138 " %s [--ro|--rw] -i -d name-of-libvirt-domain\n"
140 "--ro recommended to avoid any writes to the disk image. If -i option fails\n"
141 "run again without -i and use 'run' + 'list-filesystems' + 'mount' cmds.\n"
143 "For more information, see the manpage %s(1).\n"),
144 program_name, program_name, program_name,
145 program_name, program_name, program_name,
152 main (int argc, char *argv[])
154 /* Set global program name that is not polluted with libtool artifacts. */
155 set_program_name (argv[0]);
157 atexit (close_stdout);
159 setlocale (LC_ALL, "");
160 bindtextdomain (PACKAGE, LOCALEBASEDIR);
161 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 /* Decide here if this will be an interactive session. We have to
388 * do this as soon as possible after processing the command line
391 is_interactive = !file && isatty (0);
393 /* Register a ^C handler. We have to do this before launch could
394 * possibly be called below.
396 if (is_interactive) {
397 memset (&sa, 0, sizeof sa);
398 sa.sa_handler = user_cancel;
399 sa.sa_flags = SA_RESTART;
400 sigaction (SIGINT, &sa, NULL);
402 guestfs_set_pgroup (g, 1);
405 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
406 * previously, if we have -i without any drives but with something
407 * on the command line, it must be old-style syntax.
409 if (inspector && drvs == NULL && optind < argc) {
410 while (optind < argc) {
411 if (strchr (argv[optind], '/') ||
412 access (argv[optind], F_OK) == 0) { /* simulate -a option */
413 drv = malloc (sizeof (struct drv));
419 drv->a.filename = argv[optind];
420 drv->a.format = NULL;
423 } else { /* simulate -d option */
424 drv = malloc (sizeof (struct drv));
430 drv->d.guest = argv[optind];
439 /* If we've got drives to add, add them now. */
440 add_drives (drvs, 'a');
442 /* If we've got mountpoints or prepared drives or -i option, we must
443 * launch the guest and mount them.
445 if (next_prepared_drive > 1 || mps != NULL || inspector) {
446 /* RHBZ#612178: If --listen flag is given, then we will fork into
447 * the background in rc_listen(). However you can't do this while
448 * holding a libguestfs handle open because the recovery process
449 * will think the main program has died and kill qemu. Therefore
450 * don't use the recovery process for this case. (A better
451 * solution would be to call launch () etc after the fork, but
452 * that greatly complicates the code here).
454 if (remote_control_listen)
455 guestfs_set_recovery_proc (g, 0);
457 if (launch () == -1) exit (EXIT_FAILURE);
462 prepare_drives (drvs);
466 /* Free up data structures, no longer needed after this point. */
470 /* Remote control? */
471 if (remote_control_listen && remote_control) {
473 _("%s: cannot use --listen and --remote options at the same time\n"),
478 if (remote_control_listen) {
481 _("%s: extra parameters on the command line with --listen flag\n"),
487 _("%s: cannot use --listen and --file options at the same time\n"),
494 /* -f (file) parameter? */
497 if (open (file, O_RDONLY) == -1) {
503 /* Decide if we display progress bars. */
505 override_progress_bars >= 0
506 ? override_progress_bars
507 : (optind >= argc && is_interactive);
510 bar = progress_bar_init (0);
512 perror ("progress_bar_init");
516 guestfs_set_event_callback (g, progress_callback,
517 GUESTFS_EVENT_PROGRESS, 0, NULL);
520 /* Interactive, shell script, or command(s) on the command line? */
521 if (optind >= argc) {
528 cmdline (argv, optind, argc);
533 progress_bar_free (bar);
539 user_cancel (int sig)
542 guestfs_user_cancel (g);
546 prepare_drives (struct drv *drv)
549 prepare_drives (drv->next);
550 if (drv->type == drv_N)
551 prepare_drive (drv->N.filename, drv->N.data, drv->device);
558 if (guestfs_is_config (g)) {
559 if (guestfs_launch (g) == -1)
577 #define FISH "><fs> "
579 static char *line_read = NULL;
584 #ifdef HAVE_LIBREADLINE
592 line_read = readline (prompt ? FISH : "");
594 if (line_read && *line_read)
595 add_history_line (line_read);
600 #endif /* HAVE_LIBREADLINE */
602 static char buf[8192];
605 if (prompt) printf (FISH);
606 line_read = fgets (buf, sizeof buf, stdin);
609 len = strlen (line_read);
610 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
620 int global_exit_on_error = !prompt;
622 struct parsed_command pcmd;
626 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
627 "editing virtual machine filesystems.\n"
629 "Type: 'help' for help on commands\n"
630 " 'man' to read the manual\n"
631 " 'quit' to quit the shell\n"
635 print_inspect_prompt ();
641 exit_on_error = global_exit_on_error;
643 buf = rl_gets (prompt);
649 pcmd = parse_command_line (buf, &exit_on_error);
650 if (pcmd.status == -1 && exit_on_error)
652 if (pcmd.status == 1) {
653 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
654 if (exit_on_error) exit (EXIT_FAILURE);
658 if (prompt) printf ("\n");
661 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
662 * This destructively updates 'buf'.
664 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
665 * setting and to return the local setting (eg. if the command begins
668 * Returns in parsed_command.status:
669 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
670 * 0 = no guestfish command, but otherwise OK
673 static struct parsed_command
674 parse_command_line (char *buf, int *exit_on_error_rtn)
676 struct parsed_command pcmd;
681 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
683 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
684 * fields do not need to be, but this silences a gcc warning.
686 memset (&pcmd, 0, sizeof pcmd);
689 /* Skip any initial whitespace before the command. */
690 while (*buf && c_isspace (*buf))
698 /* If the next character is '#' then this is a comment. */
704 /* If the next character is '!' then pass the whole lot to system(3). */
709 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
710 WEXITSTATUS (r) != 0)
717 /* If the next two characters are "<!" then pass the command to
718 * popen(3), read the result and execute it as guestfish commands.
720 if (buf[0] == '<' && buf[1] == '!') {
721 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
729 /* If the next character is '-' allow the command to fail without
730 * exiting on error (just for this one command though).
733 *exit_on_error_rtn = 0;
738 /* Get the command (cannot be quoted). */
739 len = strcspn (buf, " \t");
748 if (buf[len] == '\0') {
756 p += strspn (p, " \t");
758 /* Get the parameters. */
759 while (*p && i < argv_len) {
762 /* Parameters which start with quotes or pipes are treated
763 * specially. Bare parameters are delimited by whitespace.
767 len = parse_quoted_string (p);
772 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
774 _("%s: command arguments not separated by whitespace\n"),
779 pend = p[len+1] ? &p[len+2] : &p[len+1];
780 } else if (*p == '\'') {
782 len = strcspn (p, "'");
783 if (p[len] == '\0') {
784 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
788 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
790 _("%s: command arguments not separated by whitespace\n"),
796 pend = p[len+1] ? &p[len+2] : &p[len+1];
797 } else if (*p == '|') {
801 } else if (*p != ' ' && *p != '\t') {
802 /* If the first character is a ~ then note that this parameter
803 * is a candidate for ~username expansion. NB this does not
804 * apply to quoted parameters.
806 tilde_candidate = *p == '~';
807 len = strcspn (p, " \t");
814 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
819 if (!tilde_candidate)
822 pcmd.argv[i] = try_tilde_expansion (p);
827 p += strspn (p, " \t");
831 fprintf (stderr, _("%s: too many arguments\n"), program_name);
846 case '0'...'9': return d - '0';
847 case 'a'...'f': return d - 'a' + 10;
848 case 'A'...'F': return d - 'A' + 10;
853 /* Parse double-quoted strings, replacing backslash escape sequences
854 * with the true character. Since the string is returned in place,
855 * the escapes must make the string shorter.
858 parse_quoted_string (char *p)
862 for (; *p && *p != '"'; p++) {
868 case 'a': *p = '\a'; break;
869 case 'b': *p = '\b'; break;
870 case 'f': *p = '\f'; break;
871 case 'n': *p = '\n'; break;
872 case 'r': *p = '\r'; break;
873 case 't': *p = '\t'; break;
874 case 'v': *p = '\v'; break;
875 case '"': *p = '"'; break;
876 case '\'': *p = '\''; break;
877 case '?': *p = '?'; break;
879 case '0'...'7': /* octal escape - always 3 digits */
881 if (p[2] >= '0' && p[2] <= '7' &&
882 p[3] >= '0' && p[3] <= '7') {
883 c = (p[1] - '0') * 0100 + (p[2] - '0') * 010 + (p[3] - '0');
884 if (c < 1 || c > 255)
892 case 'x': /* hex escape - always 2 digits */
894 if (c_isxdigit (p[2]) && c_isxdigit (p[3])) {
895 c = hexdigit (p[2]) * 0x10 + hexdigit (p[3]);
896 if (c < 1 || c > 255)
906 fprintf (stderr, _("%s: invalid escape sequence in string (starting at offset %d)\n"),
907 program_name, (int) (p - start));
910 memmove (p+1, p+1+m, strlen (p+1+m) + 1);
915 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
923 /* Used to handle "<!" (execute command and inline result). */
925 execute_and_inline (const char *cmd, int global_exit_on_error)
932 struct parsed_command pcmd;
934 pp = popen (cmd, "r");
940 while ((n = getline (&line, &len, pp)) != -1) {
941 exit_on_error = global_exit_on_error;
943 /* Chomp final line ending which parse_command_line would not expect. */
944 if (n > 0 && line[n-1] == '\n')
947 pcmd = parse_command_line (line, &exit_on_error);
948 if (pcmd.status == -1 && exit_on_error)
950 if (pcmd.status == 1) {
951 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
952 if (exit_on_error) exit (EXIT_FAILURE);
959 if (pclose (pp) != 0) {
968 cmdline (char *argv[], int optind, int argc)
976 if (optind >= argc) return;
978 cmd = argv[optind++];
979 if (STREQ (cmd, ":")) {
980 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
984 /* Allow -cmd on the command line to mean (temporarily) override
985 * the normal exit on error (RHBZ#578407).
992 params = &argv[optind];
994 /* Search for end of command list or ":" ... */
995 while (optind < argc && STRNEQ (argv[optind], ":"))
998 if (optind == argc) {
999 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1000 exit (EXIT_FAILURE);
1002 argv[optind] = NULL;
1003 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1004 exit (EXIT_FAILURE);
1005 cmdline (argv, optind+1, argc);
1009 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
1010 * pass to the remote server (when issuing --remote commands). It
1011 * does not cause issue_command itself to exit on error.
1014 issue_command (const char *cmd, char *argv[], const char *pipecmd,
1015 int rc_exit_on_error_flag)
1018 int stdout_saved_fd = -1;
1023 progress_bar_reset (bar);
1025 /* This counts the commands issued, starting at 1. */
1028 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1032 if (fflush (stdout) == EOF) {
1033 perror ("failed to flush standard output");
1036 if (pipe (fd) < 0) {
1037 perror ("pipe failed");
1046 if (pid == 0) { /* Child process. */
1048 if (dup2 (fd[0], 0) < 0) {
1049 perror ("dup2 of stdin failed");
1053 r = system (pipecmd);
1058 _exit (WEXITSTATUS (r));
1061 if ((stdout_saved_fd = dup (1)) < 0) {
1062 perror ("failed to dup stdout");
1066 if (dup2 (fd[1], 1) < 0) {
1067 perror ("failed to dup stdout");
1068 close (stdout_saved_fd);
1074 for (argc = 0; argv[argc] != NULL; ++argc)
1077 /* If --remote was set, then send this command to a remote process. */
1079 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1081 /* Otherwise execute it locally. */
1082 else if (STRCASEEQ (cmd, "help")) {
1087 r = display_command (argv[0]);
1089 else if (STRCASEEQ (cmd, "quit") ||
1090 STRCASEEQ (cmd, "exit") ||
1091 STRCASEEQ (cmd, "q")) {
1096 r = run_action (cmd, argc, argv);
1098 /* Always flush stdout after every command, so that messages, results
1099 * etc appear immediately.
1101 if (fflush (stdout) == EOF) {
1102 perror ("failed to flush standard output");
1108 if (dup2 (stdout_saved_fd, 1) < 0) {
1109 perror ("failed to dup2 standard output");
1112 close (stdout_saved_fd);
1113 if (waitpid (pid, NULL, 0) < 0) {
1114 perror ("waiting for command to complete");
1123 list_builtin_commands (void)
1125 /* help and quit should appear at the top */
1126 printf ("%-20s %s\n",
1127 "help", _("display a list of commands or help on a command"));
1128 printf ("%-20s %s\n",
1129 "quit", _("quit guestfish"));
1131 /* actions are printed after this (see list_commands) */
1135 display_builtin_command (const char *cmd)
1137 /* help for actions is auto-generated, see display_command */
1139 if (STRCASEEQ (cmd, "help")) {
1140 printf (_("help - display a list of commands or help on a command\n"
1145 else if (STRCASEEQ (cmd, "quit") ||
1146 STRCASEEQ (cmd, "exit") ||
1147 STRCASEEQ (cmd, "q")) {
1148 printf (_("quit - quit guestfish\n"
1153 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1159 /* This is printed when the user types in an unknown command for the
1160 * first command issued. A common case is the user doing:
1161 * guestfish disk.img
1162 * expecting guestfish to open 'disk.img' (in fact, this tried to
1163 * run a command 'disk.img').
1166 extended_help_message (void)
1169 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1170 "For a list of commands: guestfish -h\n"
1171 "For complete documentation: man guestfish\n"));
1175 free_strings (char **argv)
1179 for (argc = 0; argv[argc] != NULL; ++argc)
1185 count_strings (char *const *argv)
1189 for (c = 0; argv[c]; ++c)
1195 print_strings (char *const *argv)
1199 for (argc = 0; argv[argc] != NULL; ++argc)
1200 printf ("%s\n", argv[argc]);
1204 print_table (char *const *argv)
1208 for (i = 0; argv[i] != NULL; i += 2)
1209 printf ("%s: %s\n", argv[i], argv[i+1]);
1213 is_true (const char *str)
1216 STRCASENEQ (str, "0") &&
1217 STRCASENEQ (str, "f") &&
1218 STRCASENEQ (str, "false") &&
1219 STRCASENEQ (str, "n") &&
1220 STRCASENEQ (str, "no");
1223 /* Free strings from a non-NULL terminated char** */
1225 free_n_strings (char **str, size_t len)
1229 for (i = 0; i < len; i++) {
1236 parse_string_list (const char *str)
1239 size_t argv_len = 0;
1241 /* Current position pointer */
1242 const char *p = str;
1244 /* Token might be simple:
1247 * 'This is a single token'
1248 * or contain embedded single-quoted sections:
1249 * This' is a sing'l'e to'ken
1251 * The latter may seem over-complicated, but it's what a normal shell does.
1252 * Not doing it risks surprising somebody.
1254 * This outer loop is over complete tokens.
1260 /* Skip leading whitespace */
1261 p += strspn (p, " \t");
1265 /* This loop is over token 'fragments'. A token can be in multiple bits if
1266 * it contains single quotes. We also treat both sides of an escaped quote
1267 * as separate fragments because we can't just copy it: we have to remove
1270 while (*p && (!c_isblank (*p) || in_quote)) {
1271 const char *end = p;
1273 /* Check if the fragment starts with a quote */
1275 /* Toggle in_quote */
1276 in_quote = !in_quote;
1278 /* Skip the quote */
1282 /* If we're in a quote, look for an end quote */
1284 end += strcspn (end, "'");
1287 /* Otherwise, look for whitespace or a quote */
1289 end += strcspn (end, " \t'");
1292 /* Grow the token to accommodate the fragment */
1293 size_t tok_end = tok_len;
1295 char *tok_new = realloc (tok, tok_len + 1);
1296 if (NULL == tok_new) {
1298 free_n_strings (argv, argv_len);
1300 exit (EXIT_FAILURE);
1304 /* Check if we stopped on an escaped quote */
1305 if ('\'' == *end && end != p && *(end-1) == '\\') {
1306 /* Add everything before \' to the token */
1307 memcpy (&tok[tok_end], p, end - p - 1);
1310 tok[tok_len-1] = '\'';
1312 /* Already processed the quote */
1317 /* Add the whole fragment */
1318 memcpy (&tok[tok_end], p, end - p);
1324 /* We've reached the end of a token. We shouldn't still be in quotes. */
1326 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1327 free_n_strings (argv, argv_len);
1332 /* Add this token if there is one. There might not be if there was
1333 * whitespace at the end of the input string */
1335 /* Add the NULL terminator */
1336 tok[tok_len] = '\0';
1338 /* Add the argument to the argument list */
1340 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1341 if (NULL == argv_new) {
1343 free_n_strings (argv, argv_len-1);
1345 exit (EXIT_FAILURE);
1349 argv[argv_len-1] = tok;
1353 /* NULL terminate the argument list */
1355 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1356 if (NULL == argv_new) {
1358 free_n_strings (argv, argv_len-1);
1359 exit (EXIT_FAILURE);
1363 argv[argv_len-1] = NULL;
1368 #ifdef HAVE_LIBREADLINE
1369 static char histfile[1024];
1370 static int nr_history_lines = 0;
1374 initialize_readline (void)
1376 #ifdef HAVE_LIBREADLINE
1379 home = getenv ("HOME");
1381 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1383 (void) read_history (histfile);
1386 rl_readline_name = "guestfish";
1387 rl_attempted_completion_function = do_completion;
1389 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1390 * call the readline(), which happens later. Therefore, these
1391 * provide default values which can be overridden by the user if
1394 (void) rl_variable_bind ("completion-ignore-case", "on");
1399 cleanup_readline (void)
1401 #ifdef HAVE_LIBREADLINE
1404 if (histfile[0] != '\0') {
1405 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1412 #ifdef HAVE_APPEND_HISTORY
1413 (void) append_history (nr_history_lines, histfile);
1415 (void) write_history (histfile);
1422 #ifdef HAVE_LIBREADLINE
1424 add_history_line (const char *line)
1432 xwrite (int fd, const void *v_buf, size_t len)
1435 const char *buf = v_buf;
1438 r = write (fd, buf, len);
1450 /* Resolve the special "win:..." form for Windows-specific paths. The
1451 * generated code calls this for all device or path arguments.
1453 * The function returns a newly allocated string, and the caller must
1454 * free this string; else display an error and return NULL.
1456 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1459 win_prefix (const char *path)
1464 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1465 if (STRCASENEQLEN (path, "win:", 4)) {
1466 ret = strdup (path);
1474 /* If there is a drive letter, rewrite the path. */
1475 if (c_isalpha (path[0]) && path[1] == ':') {
1476 char drive_letter = c_tolower (path[0]);
1477 /* This returns the newly allocated string. */
1478 ret = win_prefix_drive_letter (drive_letter, path + 2);
1490 ret = strdup (path);
1497 /* Blindly convert any backslashes into forward slashes. Is this good? */
1498 for (i = 0; i < strlen (ret); ++i)
1502 char *t = guestfs_case_sensitive_path (g, ret);
1510 win_prefix_drive_letter (char drive_letter, const char *path)
1512 char **roots = NULL;
1513 char **drives = NULL;
1514 char **mountpoints = NULL;
1515 char *device, *mountpoint, *ret = NULL;
1518 /* Resolve the drive letter using the drive mappings table. */
1519 roots = guestfs_inspect_get_roots (g);
1522 if (roots[0] == NULL) {
1523 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1527 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1528 if (drives == NULL || drives[0] == NULL) {
1529 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1535 for (i = 0; drives[i] != NULL; i += 2) {
1536 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1537 device = drives[i+1];
1542 if (device == NULL) {
1543 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1544 program_name, drive_letter, roots[0]);
1548 /* This drive letter must be mounted somewhere (we won't do it). */
1549 mountpoints = guestfs_mountpoints (g);
1550 if (mountpoints == NULL)
1554 for (i = 0; mountpoints[i] != NULL; i += 2) {
1555 if (STREQ (mountpoints[i], device)) {
1556 mountpoint = mountpoints[i+1];
1561 if (mountpoint == NULL) {
1562 fprintf (stderr, _("%s: to access '%c:', mount %s first. One way to do this is:\n umount-all\n mount %s /\n"),
1563 program_name, drive_letter, device, device);
1567 /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1568 if (asprintf (&ret, "%s%s%s",
1569 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1570 perror ("asprintf");
1576 free_strings (roots);
1578 free_strings (drives);
1580 free_strings (mountpoints);
1585 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1586 * The caller (cmds.c) will call free_file_in after the command has
1587 * run which should clean up resources.
1589 static char *file_in_heredoc (const char *endmarker);
1590 static char *file_in_tmpfile = NULL;
1593 file_in (const char *arg)
1597 if (STREQ (arg, "-")) {
1598 ret = strdup ("/dev/stdin");
1604 else if (STRPREFIX (arg, "-<<")) {
1605 const char *endmarker = &arg[3];
1606 if (*endmarker == '\0') {
1607 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1611 ret = file_in_heredoc (endmarker);
1627 file_in_heredoc (const char *endmarker)
1629 TMP_TEMPLATE_ON_STACK (template);
1630 file_in_tmpfile = strdup (template);
1631 if (file_in_tmpfile == NULL) {
1636 int fd = mkstemp (file_in_tmpfile);
1642 size_t markerlen = strlen (endmarker);
1644 char buffer[BUFSIZ];
1645 int write_error = 0;
1646 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1647 /* Look for "END"<EOF> or "END\n" in input. */
1648 size_t blen = strlen (buffer);
1649 if (STREQLEN (buffer, endmarker, markerlen) &&
1650 (blen == markerlen ||
1651 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1654 if (xwrite (fd, buffer, blen) == -1) {
1655 if (!write_error) perror ("write");
1657 /* continue reading up to the end marker */
1661 /* Reached EOF of stdin without finding the end marker, which
1662 * is likely to be an error.
1664 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1665 program_name, endmarker);
1674 if (close (fd) == -1) {
1679 return file_in_tmpfile;
1682 unlink (file_in_tmpfile);
1685 free (file_in_tmpfile);
1686 file_in_tmpfile = NULL;
1691 free_file_in (char *s)
1693 if (file_in_tmpfile) {
1694 if (unlink (file_in_tmpfile) == -1)
1695 perror (file_in_tmpfile);
1696 file_in_tmpfile = NULL;
1699 /* Free the device or file name which was strdup'd in file_in().
1700 * Note it's not immediately clear, but for -<< heredocs,
1701 * s == file_in_tmpfile, so this frees up that buffer.
1706 /* Resolve the special FileOut paths ("-" or filename).
1707 * The caller (cmds.c) will call free (str) after the command has run.
1710 file_out (const char *arg)
1714 if (STREQ (arg, "-"))
1715 ret = strdup ("/dev/stdout");
1726 /* Callback which displays a progress bar. */
1728 progress_callback (guestfs_h *g, void *data,
1729 uint64_t event, int event_handle, int flags,
1730 const char *buf, size_t buf_len,
1731 const uint64_t *array, size_t array_len)
1736 /*uint64_t proc_nr = array[0];*/
1737 /*uint64_t serial = array[1];*/
1738 uint64_t position = array[2];
1739 uint64_t total = array[3];
1741 progress_bar_set (bar, position, total);