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 parse_quoted_string (char *p);
65 static int execute_and_inline (const char *cmd, int exit_on_error);
66 static void initialize_readline (void);
67 static void cleanup_readline (void);
68 #ifdef HAVE_LIBREADLINE
69 static void add_history_line (const char *);
72 static int override_progress_bars = -1;
74 /* Currently open libguestfs handle. */
81 int remote_control_listen = 0;
82 int remote_control_csh = 0;
83 int remote_control = 0;
85 int keys_from_stdin = 0;
87 const char *libvirt_uri = NULL;
90 int have_terminfo = 0;
91 int progress_bars = 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 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
389 * previously, if we have -i without any drives but with something
390 * on the command line, it must be old-style syntax.
392 if (inspector && drvs == NULL && optind < argc) {
393 while (optind < argc) {
394 if (strchr (argv[optind], '/') ||
395 access (argv[optind], F_OK) == 0) { /* simulate -a option */
396 drv = malloc (sizeof (struct drv));
402 drv->a.filename = argv[optind];
403 drv->a.format = NULL;
406 } else { /* simulate -d option */
407 drv = malloc (sizeof (struct drv));
413 drv->d.guest = argv[optind];
422 /* If we've got drives to add, add them now. */
423 add_drives (drvs, 'a');
425 /* If we've got mountpoints or prepared drives or -i option, we must
426 * launch the guest and mount them.
428 if (next_prepared_drive > 1 || mps != NULL || inspector) {
429 /* RHBZ#612178: If --listen flag is given, then we will fork into
430 * the background in rc_listen(). However you can't do this while
431 * holding a libguestfs handle open because the recovery process
432 * will think the main program has died and kill qemu. Therefore
433 * don't use the recovery process for this case. (A better
434 * solution would be to call launch () etc after the fork, but
435 * that greatly complicates the code here).
437 if (remote_control_listen)
438 guestfs_set_recovery_proc (g, 0);
440 if (launch () == -1) exit (EXIT_FAILURE);
445 prepare_drives (drvs);
449 /* Free up data structures, no longer needed after this point. */
453 /* Remote control? */
454 if (remote_control_listen && remote_control) {
456 _("%s: cannot use --listen and --remote options at the same time\n"),
461 if (remote_control_listen) {
464 _("%s: extra parameters on the command line with --listen flag\n"),
470 _("%s: cannot use --listen and --file options at the same time\n"),
477 /* -f (file) parameter? */
480 if (open (file, O_RDONLY) == -1) {
486 /* Decide if we display progress bars. */
488 override_progress_bars >= 0
489 ? override_progress_bars
490 : (optind >= argc && isatty (0));
493 guestfs_set_event_callback (g, progress_callback,
494 GUESTFS_EVENT_PROGRESS, 0, NULL);
496 /* Interactive, shell script, or command(s) on the command line? */
497 if (optind >= argc) {
504 cmdline (argv, optind, argc);
511 /* The <term.h> header file which defines this has "issues". */
512 extern int tgetent (char *, const char *);
515 set_up_terminal (void)
517 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
518 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
520 char *term = getenv ("TERM");
522 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
526 int r = tgetent (NULL, term);
528 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
532 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
541 prepare_drives (struct drv *drv)
544 prepare_drives (drv->next);
545 if (drv->type == drv_N)
546 prepare_drive (drv->N.filename, drv->N.data, drv->device);
553 if (guestfs_is_config (g)) {
554 if (guestfs_launch (g) == -1)
572 #define FISH "><fs> "
574 static char *line_read = NULL;
579 #ifdef HAVE_LIBREADLINE
587 line_read = readline (prompt ? FISH : "");
589 if (line_read && *line_read)
590 add_history_line (line_read);
595 #endif /* HAVE_LIBREADLINE */
597 static char buf[8192];
600 if (prompt) printf (FISH);
601 line_read = fgets (buf, sizeof buf, stdin);
604 len = strlen (line_read);
605 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
615 int global_exit_on_error = !prompt;
617 struct parsed_command pcmd;
621 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
622 "editing virtual machine filesystems.\n"
624 "Type: 'help' for help on commands\n"
625 " 'man' to read the manual\n"
626 " 'quit' to quit the shell\n"
630 print_inspect_prompt ();
636 exit_on_error = global_exit_on_error;
638 buf = rl_gets (prompt);
644 pcmd = parse_command_line (buf, &exit_on_error);
645 if (pcmd.status == -1 && exit_on_error)
647 if (pcmd.status == 1) {
648 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
649 if (exit_on_error) exit (EXIT_FAILURE);
653 if (prompt) printf ("\n");
656 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
657 * This destructively updates 'buf'.
659 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
660 * setting and to return the local setting (eg. if the command begins
663 * Returns in parsed_command.status:
664 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
665 * 0 = no guestfish command, but otherwise OK
668 static struct parsed_command
669 parse_command_line (char *buf, int *exit_on_error_rtn)
671 struct parsed_command pcmd;
676 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
678 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
679 * fields do not need to be, but this silences a gcc warning.
681 memset (&pcmd, 0, sizeof pcmd);
684 /* Skip any initial whitespace before the command. */
685 while (*buf && c_isspace (*buf))
693 /* If the next character is '#' then this is a comment. */
699 /* If the next character is '!' then pass the whole lot to system(3). */
704 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
705 WEXITSTATUS (r) != 0)
712 /* If the next two characters are "<!" then pass the command to
713 * popen(3), read the result and execute it as guestfish commands.
715 if (buf[0] == '<' && buf[1] == '!') {
716 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
724 /* If the next character is '-' allow the command to fail without
725 * exiting on error (just for this one command though).
728 *exit_on_error_rtn = 0;
733 /* Get the command (cannot be quoted). */
734 len = strcspn (buf, " \t");
743 if (buf[len] == '\0') {
751 p += strspn (p, " \t");
753 /* Get the parameters. */
754 while (*p && i < argv_len) {
757 /* Parameters which start with quotes or pipes are treated
758 * specially. Bare parameters are delimited by whitespace.
762 len = parse_quoted_string (p);
767 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
769 _("%s: command arguments not separated by whitespace\n"),
774 pend = p[len+1] ? &p[len+2] : &p[len+1];
775 } else if (*p == '\'') {
777 len = strcspn (p, "'");
778 if (p[len] == '\0') {
779 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
783 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
785 _("%s: command arguments not separated by whitespace\n"),
791 pend = p[len+1] ? &p[len+2] : &p[len+1];
792 } else if (*p == '|') {
796 } else if (*p != ' ' && *p != '\t') {
797 /* If the first character is a ~ then note that this parameter
798 * is a candidate for ~username expansion. NB this does not
799 * apply to quoted parameters.
801 tilde_candidate = *p == '~';
802 len = strcspn (p, " \t");
809 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
814 if (!tilde_candidate)
817 pcmd.argv[i] = try_tilde_expansion (p);
822 p += strspn (p, " \t");
826 fprintf (stderr, _("%s: too many arguments\n"), program_name);
841 case '0'...'9': return d - '0';
842 case 'a'...'f': return d - 'a' + 10;
843 case 'A'...'F': return d - 'A' + 10;
848 /* Parse double-quoted strings, replacing backslash escape sequences
849 * with the true character. Since the string is returned in place,
850 * the escapes must make the string shorter.
853 parse_quoted_string (char *p)
857 for (; *p && *p != '"'; p++) {
863 case 'a': *p = '\a'; break;
864 case 'b': *p = '\b'; break;
865 case 'f': *p = '\f'; break;
866 case 'n': *p = '\n'; break;
867 case 'r': *p = '\r'; break;
868 case 't': *p = '\t'; break;
869 case 'v': *p = '\v'; break;
870 case '"': *p = '"'; break;
871 case '\'': *p = '\''; break;
872 case '?': *p = '?'; break;
874 case '0'...'7': /* octal escape - always 3 digits */
876 if (p[2] >= '0' && p[2] <= '7' &&
877 p[3] >= '0' && p[3] <= '7') {
878 c = (p[1] - '0') * 0100 + (p[2] - '0') * 010 + (p[3] - '0');
879 if (c < 1 || c > 255)
887 case 'x': /* hex escape - always 2 digits */
889 if (c_isxdigit (p[2]) && c_isxdigit (p[3])) {
890 c = hexdigit (p[2]) * 0x10 + hexdigit (p[3]);
891 if (c < 1 || c > 255)
901 fprintf (stderr, _("%s: invalid escape sequence in string (starting at offset %d)\n"),
902 program_name, (int) (p - start));
905 memmove (p+1, p+1+m, strlen (p+1+m) + 1);
910 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
918 /* Used to handle "<!" (execute command and inline result). */
920 execute_and_inline (const char *cmd, int global_exit_on_error)
927 struct parsed_command pcmd;
929 pp = popen (cmd, "r");
935 while ((n = getline (&line, &len, pp)) != -1) {
936 exit_on_error = global_exit_on_error;
938 /* Chomp final line ending which parse_command_line would not expect. */
939 if (n > 0 && line[n-1] == '\n')
942 pcmd = parse_command_line (line, &exit_on_error);
943 if (pcmd.status == -1 && exit_on_error)
945 if (pcmd.status == 1) {
946 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
947 if (exit_on_error) exit (EXIT_FAILURE);
954 if (pclose (pp) == -1) {
963 cmdline (char *argv[], int optind, int argc)
971 if (optind >= argc) return;
973 cmd = argv[optind++];
974 if (STREQ (cmd, ":")) {
975 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
979 /* Allow -cmd on the command line to mean (temporarily) override
980 * the normal exit on error (RHBZ#578407).
987 params = &argv[optind];
989 /* Search for end of command list or ":" ... */
990 while (optind < argc && STRNEQ (argv[optind], ":"))
993 if (optind == argc) {
994 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
998 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1000 cmdline (argv, optind+1, argc);
1004 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
1005 * pass to the remote server (when issuing --remote commands). It
1006 * does not cause issue_command itself to exit on error.
1009 issue_command (const char *cmd, char *argv[], const char *pipecmd,
1010 int rc_exit_on_error_flag)
1013 int stdout_saved_fd = -1;
1017 reset_progress_bar ();
1019 /* This counts the commands issued, starting at 1. */
1022 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1026 if (fflush (stdout) == EOF) {
1027 perror ("failed to flush standard output");
1030 if (pipe (fd) < 0) {
1031 perror ("pipe failed");
1040 if (pid == 0) { /* Child process. */
1042 if (dup2 (fd[0], 0) < 0) {
1043 perror ("dup2 of stdin failed");
1047 r = system (pipecmd);
1052 _exit (WEXITSTATUS (r));
1055 if ((stdout_saved_fd = dup (1)) < 0) {
1056 perror ("failed to dup stdout");
1060 if (dup2 (fd[1], 1) < 0) {
1061 perror ("failed to dup stdout");
1062 close (stdout_saved_fd);
1068 for (argc = 0; argv[argc] != NULL; ++argc)
1071 /* If --remote was set, then send this command to a remote process. */
1073 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1075 /* Otherwise execute it locally. */
1076 else if (STRCASEEQ (cmd, "help")) {
1081 r = display_command (argv[0]);
1083 else if (STRCASEEQ (cmd, "quit") ||
1084 STRCASEEQ (cmd, "exit") ||
1085 STRCASEEQ (cmd, "q")) {
1090 r = run_action (cmd, argc, argv);
1092 /* Always flush stdout after every command, so that messages, results
1093 * etc appear immediately.
1095 if (fflush (stdout) == EOF) {
1096 perror ("failed to flush standard output");
1102 if (dup2 (stdout_saved_fd, 1) < 0) {
1103 perror ("failed to dup2 standard output");
1106 close (stdout_saved_fd);
1107 if (waitpid (pid, NULL, 0) < 0) {
1108 perror ("waiting for command to complete");
1117 list_builtin_commands (void)
1119 /* help and quit should appear at the top */
1120 printf ("%-20s %s\n",
1121 "help", _("display a list of commands or help on a command"));
1122 printf ("%-20s %s\n",
1123 "quit", _("quit guestfish"));
1125 /* actions are printed after this (see list_commands) */
1129 display_builtin_command (const char *cmd)
1131 /* help for actions is auto-generated, see display_command */
1133 if (STRCASEEQ (cmd, "help")) {
1134 printf (_("help - display a list of commands or help on a command\n"
1139 else if (STRCASEEQ (cmd, "quit") ||
1140 STRCASEEQ (cmd, "exit") ||
1141 STRCASEEQ (cmd, "q")) {
1142 printf (_("quit - quit guestfish\n"
1147 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1153 /* This is printed when the user types in an unknown command for the
1154 * first command issued. A common case is the user doing:
1155 * guestfish disk.img
1156 * expecting guestfish to open 'disk.img' (in fact, this tried to
1157 * run a command 'disk.img').
1160 extended_help_message (void)
1163 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1164 "For a list of commands: guestfish -h\n"
1165 "For complete documentation: man guestfish\n"));
1169 free_strings (char **argv)
1173 for (argc = 0; argv[argc] != NULL; ++argc)
1179 count_strings (char *const *argv)
1183 for (c = 0; argv[c]; ++c)
1189 print_strings (char *const *argv)
1193 for (argc = 0; argv[argc] != NULL; ++argc)
1194 printf ("%s\n", argv[argc]);
1198 print_table (char *const *argv)
1202 for (i = 0; argv[i] != NULL; i += 2)
1203 printf ("%s: %s\n", argv[i], argv[i+1]);
1207 is_true (const char *str)
1210 STRCASENEQ (str, "0") &&
1211 STRCASENEQ (str, "f") &&
1212 STRCASENEQ (str, "false") &&
1213 STRCASENEQ (str, "n") &&
1214 STRCASENEQ (str, "no");
1217 /* Free strings from a non-NULL terminated char** */
1219 free_n_strings (char **str, size_t len)
1223 for (i = 0; i < len; i++) {
1230 parse_string_list (const char *str)
1233 size_t argv_len = 0;
1235 /* Current position pointer */
1236 const char *p = str;
1238 /* Token might be simple:
1241 * 'This is a single token'
1242 * or contain embedded single-quoted sections:
1243 * This' is a sing'l'e to'ken
1245 * The latter may seem over-complicated, but it's what a normal shell does.
1246 * Not doing it risks surprising somebody.
1248 * This outer loop is over complete tokens.
1254 /* Skip leading whitespace */
1255 p += strspn (p, " \t");
1259 /* This loop is over token 'fragments'. A token can be in multiple bits if
1260 * it contains single quotes. We also treat both sides of an escaped quote
1261 * as separate fragments because we can't just copy it: we have to remove
1264 while (*p && (!c_isblank (*p) || in_quote)) {
1265 const char *end = p;
1267 /* Check if the fragment starts with a quote */
1269 /* Toggle in_quote */
1270 in_quote = !in_quote;
1272 /* Skip the quote */
1276 /* If we're in a quote, look for an end quote */
1278 end += strcspn (end, "'");
1281 /* Otherwise, look for whitespace or a quote */
1283 end += strcspn (end, " \t'");
1286 /* Grow the token to accommodate the fragment */
1287 size_t tok_end = tok_len;
1289 char *tok_new = realloc (tok, tok_len + 1);
1290 if (NULL == tok_new) {
1292 free_n_strings (argv, argv_len);
1294 exit (EXIT_FAILURE);
1298 /* Check if we stopped on an escaped quote */
1299 if ('\'' == *end && end != p && *(end-1) == '\\') {
1300 /* Add everything before \' to the token */
1301 memcpy (&tok[tok_end], p, end - p - 1);
1304 tok[tok_len-1] = '\'';
1306 /* Already processed the quote */
1311 /* Add the whole fragment */
1312 memcpy (&tok[tok_end], p, end - p);
1318 /* We've reached the end of a token. We shouldn't still be in quotes. */
1320 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1322 free_n_strings (argv, argv_len);
1327 /* Add this token if there is one. There might not be if there was
1328 * whitespace at the end of the input string */
1330 /* Add the NULL terminator */
1331 tok[tok_len] = '\0';
1333 /* Add the argument to the argument list */
1335 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1336 if (NULL == argv_new) {
1338 free_n_strings (argv, argv_len-1);
1340 exit (EXIT_FAILURE);
1344 argv[argv_len-1] = tok;
1348 /* NULL terminate the argument list */
1350 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1351 if (NULL == argv_new) {
1353 free_n_strings (argv, argv_len-1);
1354 exit (EXIT_FAILURE);
1358 argv[argv_len-1] = NULL;
1363 #ifdef HAVE_LIBREADLINE
1364 static char histfile[1024];
1365 static int nr_history_lines = 0;
1369 initialize_readline (void)
1371 #ifdef HAVE_LIBREADLINE
1374 home = getenv ("HOME");
1376 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1378 (void) read_history (histfile);
1381 rl_readline_name = "guestfish";
1382 rl_attempted_completion_function = do_completion;
1384 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1385 * call the readline(), which happens later. Therefore, these
1386 * provide default values which can be overridden by the user if
1389 (void) rl_variable_bind ("completion-ignore-case", "on");
1394 cleanup_readline (void)
1396 #ifdef HAVE_LIBREADLINE
1399 if (histfile[0] != '\0') {
1400 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1407 #ifdef HAVE_APPEND_HISTORY
1408 (void) append_history (nr_history_lines, histfile);
1410 (void) write_history (histfile);
1417 #ifdef HAVE_LIBREADLINE
1419 add_history_line (const char *line)
1427 xwrite (int fd, const void *v_buf, size_t len)
1430 const char *buf = v_buf;
1433 r = write (fd, buf, len);
1445 /* Resolve the special "win:..." form for Windows-specific paths. The
1446 * generated code calls this for all device or path arguments.
1448 * The function returns a newly allocated string, and the caller must
1449 * free this string; else display an error and return NULL.
1451 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1454 win_prefix (const char *path)
1459 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1460 if (STRCASENEQLEN (path, "win:", 4)) {
1461 ret = strdup (path);
1469 /* If there is a drive letter, rewrite the path. */
1470 if (c_isalpha (path[0]) && path[1] == ':') {
1471 char drive_letter = c_tolower (path[0]);
1472 /* This returns the newly allocated string. */
1473 ret = win_prefix_drive_letter (drive_letter, path + 2);
1485 ret = strdup (path);
1492 /* Blindly convert any backslashes into forward slashes. Is this good? */
1493 for (i = 0; i < strlen (ret); ++i)
1497 char *t = guestfs_case_sensitive_path (g, ret);
1505 win_prefix_drive_letter (char drive_letter, const char *path)
1507 char **roots = NULL;
1508 char **drives = NULL;
1509 char **mountpoints = NULL;
1510 char *device, *mountpoint, *ret = NULL;
1513 /* Resolve the drive letter using the drive mappings table. */
1514 roots = guestfs_inspect_get_roots (g);
1517 if (roots[0] == NULL) {
1518 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1522 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1523 if (drives == NULL || drives[0] == NULL) {
1524 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1530 for (i = 0; drives[i] != NULL; i += 2) {
1531 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1532 device = drives[i+1];
1537 if (device == NULL) {
1538 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1539 program_name, drive_letter, roots[0]);
1543 /* This drive letter must be mounted somewhere (we won't do it). */
1544 mountpoints = guestfs_mountpoints (g);
1545 if (mountpoints == NULL)
1549 for (i = 0; mountpoints[i] != NULL; i += 2) {
1550 if (STREQ (mountpoints[i], device)) {
1551 mountpoint = mountpoints[i+1];
1556 if (mountpoint == NULL) {
1557 fprintf (stderr, _("%s: to access '%c:', mount %s first. One way to do this is:\n umount-all\n mount %s /\n"),
1558 program_name, drive_letter, device, device);
1562 /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1563 if (asprintf (&ret, "%s%s%s",
1564 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1565 perror ("asprintf");
1571 free_strings (roots);
1573 free_strings (drives);
1575 free_strings (mountpoints);
1580 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1581 * The caller (cmds.c) will call free_file_in after the command has
1582 * run which should clean up resources.
1584 static char *file_in_heredoc (const char *endmarker);
1585 static char *file_in_tmpfile = NULL;
1588 file_in (const char *arg)
1592 if (STREQ (arg, "-")) {
1593 ret = strdup ("/dev/stdin");
1599 else if (STRPREFIX (arg, "-<<")) {
1600 const char *endmarker = &arg[3];
1601 if (*endmarker == '\0') {
1602 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1606 ret = file_in_heredoc (endmarker);
1622 file_in_heredoc (const char *endmarker)
1624 TMP_TEMPLATE_ON_STACK (template);
1625 file_in_tmpfile = strdup (template);
1626 if (file_in_tmpfile == NULL) {
1631 int fd = mkstemp (file_in_tmpfile);
1637 size_t markerlen = strlen (endmarker);
1639 char buffer[BUFSIZ];
1640 int write_error = 0;
1641 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1642 /* Look for "END"<EOF> or "END\n" in input. */
1643 size_t blen = strlen (buffer);
1644 if (STREQLEN (buffer, endmarker, markerlen) &&
1645 (blen == markerlen ||
1646 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1649 if (xwrite (fd, buffer, blen) == -1) {
1650 if (!write_error) perror ("write");
1652 /* continue reading up to the end marker */
1656 /* Reached EOF of stdin without finding the end marker, which
1657 * is likely to be an error.
1659 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1660 program_name, endmarker);
1669 if (close (fd) == -1) {
1674 return file_in_tmpfile;
1677 unlink (file_in_tmpfile);
1680 free (file_in_tmpfile);
1681 file_in_tmpfile = NULL;
1686 free_file_in (char *s)
1688 if (file_in_tmpfile) {
1689 if (unlink (file_in_tmpfile) == -1)
1690 perror (file_in_tmpfile);
1691 file_in_tmpfile = NULL;
1694 /* Free the device or file name which was strdup'd in file_in().
1695 * Note it's not immediately clear, but for -<< heredocs,
1696 * s == file_in_tmpfile, so this frees up that buffer.
1701 /* Resolve the special FileOut paths ("-" or filename).
1702 * The caller (cmds.c) will call free (str) after the command has run.
1705 file_out (const char *arg)
1709 if (STREQ (arg, "-"))
1710 ret = strdup ("/dev/stdout");