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);
541 user_cancel (int sig)
544 guestfs_user_cancel (g);
548 prepare_drives (struct drv *drv)
551 prepare_drives (drv->next);
552 if (drv->type == drv_N)
553 prepare_drive (drv->N.filename, drv->N.data, drv->device);
560 if (guestfs_is_config (g)) {
561 if (guestfs_launch (g) == -1)
579 #define FISH "><fs> "
581 static char *line_read = NULL;
586 #ifdef HAVE_LIBREADLINE
594 line_read = readline (prompt ? FISH : "");
596 if (line_read && *line_read)
597 add_history_line (line_read);
602 #endif /* HAVE_LIBREADLINE */
604 static char buf[8192];
607 if (prompt) printf (FISH);
608 line_read = fgets (buf, sizeof buf, stdin);
611 len = strlen (line_read);
612 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
622 int global_exit_on_error = !prompt;
624 struct parsed_command pcmd;
628 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
629 "editing virtual machine filesystems.\n"
631 "Type: 'help' for help on commands\n"
632 " 'man' to read the manual\n"
633 " 'quit' to quit the shell\n"
637 print_inspect_prompt ();
643 exit_on_error = global_exit_on_error;
645 buf = rl_gets (prompt);
651 pcmd = parse_command_line (buf, &exit_on_error);
652 if (pcmd.status == -1 && exit_on_error)
654 if (pcmd.status == 1) {
655 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
656 if (exit_on_error) exit (EXIT_FAILURE);
660 if (prompt) printf ("\n");
663 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
664 * This destructively updates 'buf'.
666 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
667 * setting and to return the local setting (eg. if the command begins
670 * Returns in parsed_command.status:
671 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
672 * 0 = no guestfish command, but otherwise OK
675 static struct parsed_command
676 parse_command_line (char *buf, int *exit_on_error_rtn)
678 struct parsed_command pcmd;
683 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
685 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
686 * fields do not need to be, but this silences a gcc warning.
688 memset (&pcmd, 0, sizeof pcmd);
691 /* Skip any initial whitespace before the command. */
692 while (*buf && c_isspace (*buf))
700 /* If the next character is '#' then this is a comment. */
706 /* If the next character is '!' then pass the whole lot to system(3). */
711 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
712 WEXITSTATUS (r) != 0)
719 /* If the next two characters are "<!" then pass the command to
720 * popen(3), read the result and execute it as guestfish commands.
722 if (buf[0] == '<' && buf[1] == '!') {
723 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
731 /* If the next character is '-' allow the command to fail without
732 * exiting on error (just for this one command though).
735 *exit_on_error_rtn = 0;
740 /* Get the command (cannot be quoted). */
741 len = strcspn (buf, " \t");
750 if (buf[len] == '\0') {
758 p += strspn (p, " \t");
760 /* Get the parameters. */
761 while (*p && i < argv_len) {
764 /* Parameters which start with quotes or pipes are treated
765 * specially. Bare parameters are delimited by whitespace.
769 len = parse_quoted_string (p);
774 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
776 _("%s: command arguments not separated by whitespace\n"),
781 pend = p[len+1] ? &p[len+2] : &p[len+1];
782 } else if (*p == '\'') {
784 len = strcspn (p, "'");
785 if (p[len] == '\0') {
786 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
790 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
792 _("%s: command arguments not separated by whitespace\n"),
798 pend = p[len+1] ? &p[len+2] : &p[len+1];
799 } else if (*p == '|') {
803 } else if (*p != ' ' && *p != '\t') {
804 /* If the first character is a ~ then note that this parameter
805 * is a candidate for ~username expansion. NB this does not
806 * apply to quoted parameters.
808 tilde_candidate = *p == '~';
809 len = strcspn (p, " \t");
816 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
821 if (!tilde_candidate)
824 pcmd.argv[i] = try_tilde_expansion (p);
829 p += strspn (p, " \t");
833 fprintf (stderr, _("%s: too many arguments\n"), program_name);
848 case '0'...'9': return d - '0';
849 case 'a'...'f': return d - 'a' + 10;
850 case 'A'...'F': return d - 'A' + 10;
855 /* Parse double-quoted strings, replacing backslash escape sequences
856 * with the true character. Since the string is returned in place,
857 * the escapes must make the string shorter.
860 parse_quoted_string (char *p)
864 for (; *p && *p != '"'; p++) {
870 case 'a': *p = '\a'; break;
871 case 'b': *p = '\b'; break;
872 case 'f': *p = '\f'; break;
873 case 'n': *p = '\n'; break;
874 case 'r': *p = '\r'; break;
875 case 't': *p = '\t'; break;
876 case 'v': *p = '\v'; break;
877 case '"': *p = '"'; break;
878 case '\'': *p = '\''; break;
879 case '?': *p = '?'; break;
881 case '0'...'7': /* octal escape - always 3 digits */
883 if (p[2] >= '0' && p[2] <= '7' &&
884 p[3] >= '0' && p[3] <= '7') {
885 c = (p[1] - '0') * 0100 + (p[2] - '0') * 010 + (p[3] - '0');
886 if (c < 1 || c > 255)
894 case 'x': /* hex escape - always 2 digits */
896 if (c_isxdigit (p[2]) && c_isxdigit (p[3])) {
897 c = hexdigit (p[2]) * 0x10 + hexdigit (p[3]);
898 if (c < 1 || c > 255)
908 fprintf (stderr, _("%s: invalid escape sequence in string (starting at offset %d)\n"),
909 program_name, (int) (p - start));
912 memmove (p+1, p+1+m, strlen (p+1+m) + 1);
917 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
925 /* Used to handle "<!" (execute command and inline result). */
927 execute_and_inline (const char *cmd, int global_exit_on_error)
934 struct parsed_command pcmd;
936 pp = popen (cmd, "r");
942 while ((n = getline (&line, &len, pp)) != -1) {
943 exit_on_error = global_exit_on_error;
945 /* Chomp final line ending which parse_command_line would not expect. */
946 if (n > 0 && line[n-1] == '\n')
949 pcmd = parse_command_line (line, &exit_on_error);
950 if (pcmd.status == -1 && exit_on_error)
952 if (pcmd.status == 1) {
953 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
954 if (exit_on_error) exit (EXIT_FAILURE);
961 if (pclose (pp) != 0) {
970 cmdline (char *argv[], int optind, int argc)
978 if (optind >= argc) return;
980 cmd = argv[optind++];
981 if (STREQ (cmd, ":")) {
982 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
986 /* Allow -cmd on the command line to mean (temporarily) override
987 * the normal exit on error (RHBZ#578407).
994 params = &argv[optind];
996 /* Search for end of command list or ":" ... */
997 while (optind < argc && STRNEQ (argv[optind], ":"))
1000 if (optind == argc) {
1001 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1002 exit (EXIT_FAILURE);
1004 argv[optind] = NULL;
1005 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1006 exit (EXIT_FAILURE);
1007 cmdline (argv, optind+1, argc);
1011 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
1012 * pass to the remote server (when issuing --remote commands). It
1013 * does not cause issue_command itself to exit on error.
1016 issue_command (const char *cmd, char *argv[], const char *pipecmd,
1017 int rc_exit_on_error_flag)
1020 int stdout_saved_fd = -1;
1025 progress_bar_reset (bar);
1027 /* This counts the commands issued, starting at 1. */
1030 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1034 if (fflush (stdout) == EOF) {
1035 perror ("failed to flush standard output");
1038 if (pipe (fd) < 0) {
1039 perror ("pipe failed");
1048 if (pid == 0) { /* Child process. */
1050 if (dup2 (fd[0], 0) < 0) {
1051 perror ("dup2 of stdin failed");
1055 r = system (pipecmd);
1060 _exit (WEXITSTATUS (r));
1063 if ((stdout_saved_fd = dup (1)) < 0) {
1064 perror ("failed to dup stdout");
1068 if (dup2 (fd[1], 1) < 0) {
1069 perror ("failed to dup stdout");
1070 close (stdout_saved_fd);
1076 for (argc = 0; argv[argc] != NULL; ++argc)
1079 /* If --remote was set, then send this command to a remote process. */
1081 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1083 /* Otherwise execute it locally. */
1084 else if (STRCASEEQ (cmd, "help")) {
1089 r = display_command (argv[0]);
1091 else if (STRCASEEQ (cmd, "quit") ||
1092 STRCASEEQ (cmd, "exit") ||
1093 STRCASEEQ (cmd, "q")) {
1098 r = run_action (cmd, argc, argv);
1100 /* Always flush stdout after every command, so that messages, results
1101 * etc appear immediately.
1103 if (fflush (stdout) == EOF) {
1104 perror ("failed to flush standard output");
1110 if (dup2 (stdout_saved_fd, 1) < 0) {
1111 perror ("failed to dup2 standard output");
1114 close (stdout_saved_fd);
1115 if (waitpid (pid, NULL, 0) < 0) {
1116 perror ("waiting for command to complete");
1125 list_builtin_commands (void)
1127 /* help and quit should appear at the top */
1128 printf ("%-20s %s\n",
1129 "help", _("display a list of commands or help on a command"));
1130 printf ("%-20s %s\n",
1131 "quit", _("quit guestfish"));
1133 /* actions are printed after this (see list_commands) */
1137 display_builtin_command (const char *cmd)
1139 /* help for actions is auto-generated, see display_command */
1141 if (STRCASEEQ (cmd, "help")) {
1142 printf (_("help - display a list of commands or help on a command\n"
1147 else if (STRCASEEQ (cmd, "quit") ||
1148 STRCASEEQ (cmd, "exit") ||
1149 STRCASEEQ (cmd, "q")) {
1150 printf (_("quit - quit guestfish\n"
1155 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1161 /* This is printed when the user types in an unknown command for the
1162 * first command issued. A common case is the user doing:
1163 * guestfish disk.img
1164 * expecting guestfish to open 'disk.img' (in fact, this tried to
1165 * run a command 'disk.img').
1168 extended_help_message (void)
1171 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1172 "For a list of commands: guestfish -h\n"
1173 "For complete documentation: man guestfish\n"));
1177 free_strings (char **argv)
1181 for (argc = 0; argv[argc] != NULL; ++argc)
1187 count_strings (char *const *argv)
1191 for (c = 0; argv[c]; ++c)
1197 print_strings (char *const *argv)
1201 for (argc = 0; argv[argc] != NULL; ++argc)
1202 printf ("%s\n", argv[argc]);
1206 print_table (char *const *argv)
1210 for (i = 0; argv[i] != NULL; i += 2)
1211 printf ("%s: %s\n", argv[i], argv[i+1]);
1215 is_true (const char *str)
1218 STRCASENEQ (str, "0") &&
1219 STRCASENEQ (str, "f") &&
1220 STRCASENEQ (str, "false") &&
1221 STRCASENEQ (str, "n") &&
1222 STRCASENEQ (str, "no");
1225 /* Free strings from a non-NULL terminated char** */
1227 free_n_strings (char **str, size_t len)
1231 for (i = 0; i < len; i++) {
1238 parse_string_list (const char *str)
1241 size_t argv_len = 0;
1243 /* Current position pointer */
1244 const char *p = str;
1246 /* Token might be simple:
1249 * 'This is a single token'
1250 * or contain embedded single-quoted sections:
1251 * This' is a sing'l'e to'ken
1253 * The latter may seem over-complicated, but it's what a normal shell does.
1254 * Not doing it risks surprising somebody.
1256 * This outer loop is over complete tokens.
1262 /* Skip leading whitespace */
1263 p += strspn (p, " \t");
1267 /* This loop is over token 'fragments'. A token can be in multiple bits if
1268 * it contains single quotes. We also treat both sides of an escaped quote
1269 * as separate fragments because we can't just copy it: we have to remove
1272 while (*p && (!c_isblank (*p) || in_quote)) {
1273 const char *end = p;
1275 /* Check if the fragment starts with a quote */
1277 /* Toggle in_quote */
1278 in_quote = !in_quote;
1280 /* Skip the quote */
1284 /* If we're in a quote, look for an end quote */
1286 end += strcspn (end, "'");
1289 /* Otherwise, look for whitespace or a quote */
1291 end += strcspn (end, " \t'");
1294 /* Grow the token to accommodate the fragment */
1295 size_t tok_end = tok_len;
1297 char *tok_new = realloc (tok, tok_len + 1);
1298 if (NULL == tok_new) {
1300 free_n_strings (argv, argv_len);
1302 exit (EXIT_FAILURE);
1306 /* Check if we stopped on an escaped quote */
1307 if ('\'' == *end && end != p && *(end-1) == '\\') {
1308 /* Add everything before \' to the token */
1309 memcpy (&tok[tok_end], p, end - p - 1);
1312 tok[tok_len-1] = '\'';
1314 /* Already processed the quote */
1319 /* Add the whole fragment */
1320 memcpy (&tok[tok_end], p, end - p);
1326 /* We've reached the end of a token. We shouldn't still be in quotes. */
1328 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1329 free_n_strings (argv, argv_len);
1334 /* Add this token if there is one. There might not be if there was
1335 * whitespace at the end of the input string */
1337 /* Add the NULL terminator */
1338 tok[tok_len] = '\0';
1340 /* Add the argument to the argument list */
1342 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1343 if (NULL == argv_new) {
1345 free_n_strings (argv, argv_len-1);
1347 exit (EXIT_FAILURE);
1351 argv[argv_len-1] = tok;
1355 /* NULL terminate the argument list */
1357 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1358 if (NULL == argv_new) {
1360 free_n_strings (argv, argv_len-1);
1361 exit (EXIT_FAILURE);
1365 argv[argv_len-1] = NULL;
1370 #ifdef HAVE_LIBREADLINE
1371 static char histfile[1024];
1372 static int nr_history_lines = 0;
1376 initialize_readline (void)
1378 #ifdef HAVE_LIBREADLINE
1381 home = getenv ("HOME");
1383 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1385 (void) read_history (histfile);
1388 rl_readline_name = "guestfish";
1389 rl_attempted_completion_function = do_completion;
1391 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1392 * call the readline(), which happens later. Therefore, these
1393 * provide default values which can be overridden by the user if
1396 (void) rl_variable_bind ("completion-ignore-case", "on");
1401 cleanup_readline (void)
1403 #ifdef HAVE_LIBREADLINE
1406 if (histfile[0] != '\0') {
1407 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1414 #ifdef HAVE_APPEND_HISTORY
1415 (void) append_history (nr_history_lines, histfile);
1417 (void) write_history (histfile);
1424 #ifdef HAVE_LIBREADLINE
1426 add_history_line (const char *line)
1434 xwrite (int fd, const void *v_buf, size_t len)
1437 const char *buf = v_buf;
1440 r = write (fd, buf, len);
1452 /* Resolve the special "win:..." form for Windows-specific paths. The
1453 * generated code calls this for all device or path arguments.
1455 * The function returns a newly allocated string, and the caller must
1456 * free this string; else display an error and return NULL.
1458 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1461 win_prefix (const char *path)
1466 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1467 if (STRCASENEQLEN (path, "win:", 4)) {
1468 ret = strdup (path);
1476 /* If there is a drive letter, rewrite the path. */
1477 if (c_isalpha (path[0]) && path[1] == ':') {
1478 char drive_letter = c_tolower (path[0]);
1479 /* This returns the newly allocated string. */
1480 ret = win_prefix_drive_letter (drive_letter, path + 2);
1492 ret = strdup (path);
1499 /* Blindly convert any backslashes into forward slashes. Is this good? */
1500 for (i = 0; i < strlen (ret); ++i)
1504 char *t = guestfs_case_sensitive_path (g, ret);
1512 win_prefix_drive_letter (char drive_letter, const char *path)
1514 char **roots = NULL;
1515 char **drives = NULL;
1516 char **mountpoints = NULL;
1517 char *device, *mountpoint, *ret = NULL;
1520 /* Resolve the drive letter using the drive mappings table. */
1521 roots = guestfs_inspect_get_roots (g);
1524 if (roots[0] == NULL) {
1525 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1529 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1530 if (drives == NULL || drives[0] == NULL) {
1531 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1537 for (i = 0; drives[i] != NULL; i += 2) {
1538 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1539 device = drives[i+1];
1544 if (device == NULL) {
1545 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1546 program_name, drive_letter, roots[0]);
1550 /* This drive letter must be mounted somewhere (we won't do it). */
1551 mountpoints = guestfs_mountpoints (g);
1552 if (mountpoints == NULL)
1556 for (i = 0; mountpoints[i] != NULL; i += 2) {
1557 if (STREQ (mountpoints[i], device)) {
1558 mountpoint = mountpoints[i+1];
1563 if (mountpoint == NULL) {
1564 fprintf (stderr, _("%s: to access '%c:', mount %s first. One way to do this is:\n umount-all\n mount %s /\n"),
1565 program_name, drive_letter, device, device);
1569 /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1570 if (asprintf (&ret, "%s%s%s",
1571 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1572 perror ("asprintf");
1578 free_strings (roots);
1580 free_strings (drives);
1582 free_strings (mountpoints);
1587 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1588 * The caller (cmds.c) will call free_file_in after the command has
1589 * run which should clean up resources.
1591 static char *file_in_heredoc (const char *endmarker);
1592 static char *file_in_tmpfile = NULL;
1595 file_in (const char *arg)
1599 if (STREQ (arg, "-")) {
1600 ret = strdup ("/dev/stdin");
1606 else if (STRPREFIX (arg, "-<<")) {
1607 const char *endmarker = &arg[3];
1608 if (*endmarker == '\0') {
1609 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1613 ret = file_in_heredoc (endmarker);
1629 file_in_heredoc (const char *endmarker)
1631 TMP_TEMPLATE_ON_STACK (template);
1632 file_in_tmpfile = strdup (template);
1633 if (file_in_tmpfile == NULL) {
1638 int fd = mkstemp (file_in_tmpfile);
1644 size_t markerlen = strlen (endmarker);
1646 char buffer[BUFSIZ];
1647 int write_error = 0;
1648 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1649 /* Look for "END"<EOF> or "END\n" in input. */
1650 size_t blen = strlen (buffer);
1651 if (STREQLEN (buffer, endmarker, markerlen) &&
1652 (blen == markerlen ||
1653 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1656 if (xwrite (fd, buffer, blen) == -1) {
1657 if (!write_error) perror ("write");
1659 /* continue reading up to the end marker */
1663 /* Reached EOF of stdin without finding the end marker, which
1664 * is likely to be an error.
1666 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1667 program_name, endmarker);
1676 if (close (fd) == -1) {
1681 return file_in_tmpfile;
1684 unlink (file_in_tmpfile);
1687 free (file_in_tmpfile);
1688 file_in_tmpfile = NULL;
1693 free_file_in (char *s)
1695 if (file_in_tmpfile) {
1696 if (unlink (file_in_tmpfile) == -1)
1697 perror (file_in_tmpfile);
1698 file_in_tmpfile = NULL;
1701 /* Free the device or file name which was strdup'd in file_in().
1702 * Note it's not immediately clear, but for -<< heredocs,
1703 * s == file_in_tmpfile, so this frees up that buffer.
1708 /* Resolve the special FileOut paths ("-" or filename).
1709 * The caller (cmds.c) will call free (str) after the command has run.
1712 file_out (const char *arg)
1716 if (STREQ (arg, "-"))
1717 ret = strdup ("/dev/stdout");
1728 /* Callback which displays a progress bar. */
1730 progress_callback (guestfs_h *g, void *data,
1731 uint64_t event, int event_handle, int flags,
1732 const char *buf, size_t buf_len,
1733 const uint64_t *array, size_t array_len)
1738 /*uint64_t proc_nr = array[0];*/
1739 /*uint64_t serial = array[1];*/
1740 uint64_t position = array[2];
1741 uint64_t total = array[3];
1743 progress_bar_set (bar, position, total);