1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2011 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #include <sys/types.h>
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
48 /* Return from parse_command_line. See description below. */
49 struct parsed_command {
56 static void set_up_terminal (void);
57 static void prepare_drives (struct drv *drv);
58 static int launch (void);
59 static void interactive (void);
60 static void shell_script (void);
61 static void script (int prompt);
62 static void cmdline (char *argv[], int optind, int argc);
63 static struct parsed_command parse_command_line (char *buf, int *exit_on_error_rtn);
64 static int execute_and_inline (const char *cmd, int exit_on_error);
65 static void initialize_readline (void);
66 static void cleanup_readline (void);
67 #ifdef HAVE_LIBREADLINE
68 static void add_history_line (const char *);
71 static int override_progress_bars = -1;
73 /* Currently open libguestfs handle. */
80 int remote_control_listen = 0;
81 int remote_control_csh = 0;
82 int remote_control = 0;
84 int keys_from_stdin = 0;
86 const char *libvirt_uri = NULL;
89 int have_terminfo = 0;
90 int progress_bars = 0;
92 static void __attribute__((noreturn))
95 if (status != EXIT_SUCCESS)
96 fprintf (stderr, _("Try `%s --help' for more information.\n"),
100 _("%s: guest filesystem shell\n"
101 "%s lets you edit virtual machine filesystems\n"
102 "Copyright (C) 2009-2010 Red Hat Inc.\n"
104 " %s [--options] cmd [: cmd : cmd ...]\n"
105 " %s [--ro] -i -a disk-image\n"
106 " %s [--ro] -i -d libvirt-domain\n"
107 "or for interactive use:\n"
109 "or from a shell script:\n"
115 " -h|--cmd-help List available commands\n"
116 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
117 " -a|--add image Add image\n"
118 " -c|--connect uri Specify libvirt URI for -d option\n"
119 " --csh Make --listen csh-compatible\n"
120 " -d|--domain guest Add disks from libvirt guest\n"
121 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
122 " --echo-keys Don't turn off echo for passphrases\n"
123 " -f|--file file Read commands from file\n"
124 " --format[=raw|..] Force disk format for -a option\n"
125 " -i|--inspector Automatically mount filesystems\n"
126 " --keys-from-stdin Read passphrases from stdin\n"
127 " --listen Listen for remote commands\n"
128 " --live Connect to a live virtual machine\n"
129 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
130 " -n|--no-sync Don't autosync\n"
131 " -N|--new type Create prepared disk (test1.img, ...)\n"
132 " --progress-bars Enable progress bars even when not interactive\n"
133 " --no-progress-bars Disable progress bars\n"
134 " --remote[=pid] Send commands to remote %s\n"
135 " -r|--ro Mount read-only\n"
136 " --selinux Enable SELinux support\n"
137 " -v|--verbose Verbose messages\n"
138 " -V|--version Display version and exit\n"
139 " -x Echo each command before executing it\n"
140 "For more information, see the manpage %s(1).\n"),
141 program_name, program_name, program_name,
142 program_name, program_name, program_name,
143 program_name, program_name, program_name);
149 main (int argc, char *argv[])
151 /* Set global program name that is not polluted with libtool artifacts. */
152 set_program_name (argv[0]);
154 atexit (close_stdout);
156 setlocale (LC_ALL, "");
157 bindtextdomain (PACKAGE, LOCALEBASEDIR);
158 textdomain (PACKAGE);
162 enum { HELP_OPTION = CHAR_MAX + 1 };
164 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
165 static const struct option long_options[] = {
166 { "add", 1, 0, 'a' },
167 { "cmd-help", 2, 0, 'h' },
168 { "connect", 1, 0, 'c' },
170 { "domain", 1, 0, 'd' },
171 { "echo-keys", 0, 0, 0 },
172 { "file", 1, 0, 'f' },
173 { "format", 2, 0, 0 },
174 { "help", 0, 0, HELP_OPTION },
175 { "inspector", 0, 0, 'i' },
176 { "keys-from-stdin", 0, 0, 0 },
177 { "listen", 0, 0, 0 },
179 { "mount", 1, 0, 'm' },
180 { "new", 1, 0, 'N' },
181 { "no-dest-paths", 0, 0, 'D' },
182 { "no-sync", 0, 0, 'n' },
183 { "progress-bars", 0, 0, 0 },
184 { "no-progress-bars", 0, 0, 0 },
185 { "remote", 2, 0, 0 },
188 { "selinux", 0, 0, 0 },
189 { "verbose", 0, 0, 'v' },
190 { "version", 0, 0, 'V' },
193 struct drv *drvs = NULL;
195 struct mp *mps = NULL;
197 char *p, *file = NULL;
198 const char *format = NULL;
202 int next_prepared_drive = 1;
204 initialize_readline ();
206 memset (&sa, 0, sizeof sa);
207 sa.sa_handler = SIG_IGN;
208 sa.sa_flags = SA_RESTART;
209 sigaction (SIGPIPE, &sa, NULL);
211 /* guestfs_create is meant to be a lightweight operation, so
212 * it's OK to do it early here.
214 g = guestfs_create ();
216 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
220 /* If developing, add ./appliance to the path. Note that libtools
221 * interferes with this because uninstalled guestfish is a shell
222 * script that runs the real program with an absolute path. Detect
225 * BUT if LIBGUESTFS_PATH environment variable is already set by
226 * the user, then don't override it.
228 if (getenv ("LIBGUESTFS_PATH") == NULL &&
230 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
231 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
233 /* CAUTION: we are careful to modify argv[0] here, only after
234 * using it just above.
236 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
237 * of the original, in case it's needed below.
239 //char *real_argv0 = argv[0];
240 argv[0] = bad_cast (program_name);
243 c = getopt_long (argc, argv, options, long_options, &option_index);
247 case 0: /* options which are long only */
248 if (STREQ (long_options[option_index].name, "listen"))
249 remote_control_listen = 1;
250 else if (STREQ (long_options[option_index].name, "remote")) {
252 if (sscanf (optarg, "%d", &remote_control) != 1) {
253 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
254 program_name, optarg);
258 p = getenv ("GUESTFISH_PID");
259 if (!p || sscanf (p, "%d", &remote_control) != 1) {
260 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
261 " to the PID of the remote process\n"),
266 } else if (STREQ (long_options[option_index].name, "selinux")) {
267 guestfs_set_selinux (g, 1);
268 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
270 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
271 override_progress_bars = 1;
272 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
273 override_progress_bars = 0;
274 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
276 } else if (STREQ (long_options[option_index].name, "format")) {
277 if (!optarg || STREQ (optarg, ""))
281 } else if (STREQ (long_options[option_index].name, "csh")) {
282 remote_control_csh = 1;
283 } else if (STREQ (long_options[option_index].name, "live")) {
286 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
287 program_name, long_options[option_index].name, option_index);
305 complete_dest_paths = 0;
310 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
321 r = display_command (optarg);
322 else if (argv[optind] && argv[optind][0] != '-')
323 r = display_command (argv[optind++]);
327 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
343 if (STRCASEEQ (optarg, "list") ||
344 STRCASEEQ (optarg, "help") ||
345 STRCASEEQ (optarg, "h") ||
346 STRCASEEQ (optarg, "?")) {
347 list_prepared_drives ();
350 drv = malloc (sizeof (struct drv));
358 if (asprintf (&drv->N.filename, "test%d.img",
359 next_prepared_drive++) == -1) {
363 drv->N.data = create_prepared_file (optarg, drv->N.filename);
364 drv->N.data_free = free_prep_data;
390 usage (EXIT_SUCCESS);
393 usage (EXIT_FAILURE);
397 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
398 * previously, if we have -i without any drives but with something
399 * on the command line, it must be old-style syntax.
401 if (inspector && drvs == NULL && optind < argc) {
402 while (optind < argc) {
403 if (strchr (argv[optind], '/') ||
404 access (argv[optind], F_OK) == 0) { /* simulate -a option */
405 drv = malloc (sizeof (struct drv));
411 drv->a.filename = argv[optind];
412 drv->a.format = NULL;
415 } else { /* simulate -d option */
416 drv = malloc (sizeof (struct drv));
422 drv->d.guest = argv[optind];
431 /* If we've got drives to add, add them now. */
432 add_drives (drvs, 'a');
434 /* If we've got mountpoints or prepared drives or -i option, we must
435 * launch the guest and mount them.
437 if (next_prepared_drive > 1 || mps != NULL || inspector) {
438 /* RHBZ#612178: If --listen flag is given, then we will fork into
439 * the background in rc_listen(). However you can't do this while
440 * holding a libguestfs handle open because the recovery process
441 * will think the main program has died and kill qemu. Therefore
442 * don't use the recovery process for this case. (A better
443 * solution would be to call launch () etc after the fork, but
444 * that greatly complicates the code here).
446 if (remote_control_listen)
447 guestfs_set_recovery_proc (g, 0);
449 if (launch () == -1) exit (EXIT_FAILURE);
454 prepare_drives (drvs);
458 /* Free up data structures, no longer needed after this point. */
462 /* Remote control? */
463 if (remote_control_listen && remote_control) {
465 _("%s: cannot use --listen and --remote options at the same time\n"),
470 if (remote_control_listen) {
473 _("%s: extra parameters on the command line with --listen flag\n"),
479 _("%s: cannot use --listen and --file options at the same time\n"),
486 /* -f (file) parameter? */
489 if (open (file, O_RDONLY) == -1) {
495 /* Decide if we display progress bars. */
497 override_progress_bars >= 0
498 ? override_progress_bars
499 : (optind >= argc && isatty (0));
502 guestfs_set_event_callback (g, progress_callback,
503 GUESTFS_EVENT_PROGRESS, 0, NULL);
505 /* Interactive, shell script, or command(s) on the command line? */
506 if (optind >= argc) {
513 cmdline (argv, optind, argc);
520 /* The <term.h> header file which defines this has "issues". */
521 extern int tgetent (char *, const char *);
524 set_up_terminal (void)
526 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
527 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
529 char *term = getenv ("TERM");
531 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
535 int r = tgetent (NULL, term);
537 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
541 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
550 prepare_drives (struct drv *drv)
553 prepare_drives (drv->next);
554 if (drv->type == drv_N)
555 prepare_drive (drv->N.filename, drv->N.data, drv->device);
562 if (guestfs_is_config (g)) {
563 if (guestfs_launch (g) == -1)
581 #define FISH "><fs> "
583 static char *line_read = NULL;
588 #ifdef HAVE_LIBREADLINE
596 line_read = readline (prompt ? FISH : "");
598 if (line_read && *line_read)
599 add_history_line (line_read);
604 #endif /* HAVE_LIBREADLINE */
606 static char buf[8192];
609 if (prompt) printf (FISH);
610 line_read = fgets (buf, sizeof buf, stdin);
613 len = strlen (line_read);
614 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
624 int global_exit_on_error = !prompt;
626 struct parsed_command pcmd;
630 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
631 "editing virtual machine filesystems.\n"
633 "Type: 'help' for help on commands\n"
634 " 'man' to read the manual\n"
635 " 'quit' to quit the shell\n"
639 print_inspect_prompt ();
645 exit_on_error = global_exit_on_error;
647 buf = rl_gets (prompt);
653 pcmd = parse_command_line (buf, &exit_on_error);
654 if (pcmd.status == -1 && exit_on_error)
656 if (pcmd.status == 1) {
657 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
658 if (exit_on_error) exit (EXIT_FAILURE);
662 if (prompt) printf ("\n");
665 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
666 * This destructively updates 'buf'.
668 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
669 * setting and to return the local setting (eg. if the command begins
672 * Returns in parsed_command.status:
673 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
674 * 0 = no guestfish command, but otherwise OK
677 static struct parsed_command
678 parse_command_line (char *buf, int *exit_on_error_rtn)
680 struct parsed_command pcmd;
685 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
687 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
688 * fields do not need to be, but this silences a gcc warning.
690 memset (&pcmd, 0, sizeof pcmd);
693 /* Skip any initial whitespace before the command. */
694 while (*buf && c_isspace (*buf))
702 /* If the next character is '#' then this is a comment. */
708 /* If the next character is '!' then pass the whole lot to system(3). */
713 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
714 WEXITSTATUS (r) != 0)
721 /* If the next two characters are "<!" then pass the command to
722 * popen(3), read the result and execute it as guestfish commands.
724 if (buf[0] == '<' && buf[1] == '!') {
725 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
733 /* If the next character is '-' allow the command to fail without
734 * exiting on error (just for this one command though).
737 *exit_on_error_rtn = 0;
742 /* Get the command (cannot be quoted). */
743 len = strcspn (buf, " \t");
752 if (buf[len] == '\0') {
760 p += strspn (p, " \t");
762 /* Get the parameters. */
763 while (*p && i < argv_len) {
766 /* Parameters which start with quotes or pipes are treated
767 * specially. Bare parameters are delimited by whitespace.
771 len = strcspn (p, "\"");
772 if (p[len] == '\0') {
773 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
777 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
779 _("%s: command arguments not separated by whitespace\n"),
785 pend = p[len+1] ? &p[len+2] : &p[len+1];
786 } else if (*p == '\'') {
788 len = strcspn (p, "'");
789 if (p[len] == '\0') {
790 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
794 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
796 _("%s: command arguments not separated by whitespace\n"),
802 pend = p[len+1] ? &p[len+2] : &p[len+1];
803 } else if (*p == '|') {
807 } else if (*p != ' ' && *p != '\t') {
808 /* If the first character is a ~ then note that this parameter
809 * is a candidate for ~username expansion. NB this does not
810 * apply to quoted parameters.
812 tilde_candidate = *p == '~';
813 len = strcspn (p, " \t");
820 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
825 if (!tilde_candidate)
828 pcmd.argv[i] = try_tilde_expansion (p);
833 p += strspn (p, " \t");
837 fprintf (stderr, _("%s: too many arguments\n"), program_name);
848 /* Used to handle "<!" (execute command and inline result). */
850 execute_and_inline (const char *cmd, int global_exit_on_error)
857 struct parsed_command pcmd;
859 pp = popen (cmd, "r");
865 while ((n = getline (&line, &len, pp)) != -1) {
866 exit_on_error = global_exit_on_error;
868 /* Chomp final line ending which parse_command_line would not expect. */
869 if (n > 0 && line[n-1] == '\n')
872 pcmd = parse_command_line (line, &exit_on_error);
873 if (pcmd.status == -1 && exit_on_error)
875 if (pcmd.status == 1) {
876 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
877 if (exit_on_error) exit (EXIT_FAILURE);
884 if (pclose (pp) == -1) {
893 cmdline (char *argv[], int optind, int argc)
901 if (optind >= argc) return;
903 cmd = argv[optind++];
904 if (STREQ (cmd, ":")) {
905 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
909 /* Allow -cmd on the command line to mean (temporarily) override
910 * the normal exit on error (RHBZ#578407).
917 params = &argv[optind];
919 /* Search for end of command list or ":" ... */
920 while (optind < argc && STRNEQ (argv[optind], ":"))
923 if (optind == argc) {
924 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
928 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
930 cmdline (argv, optind+1, argc);
934 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
935 * pass to the remote server (when issuing --remote commands). It
936 * does not cause issue_command itself to exit on error.
939 issue_command (const char *cmd, char *argv[], const char *pipecmd,
940 int rc_exit_on_error_flag)
943 int stdout_saved_fd = -1;
947 reset_progress_bar ();
949 /* This counts the commands issued, starting at 1. */
952 /* For | ... commands. Annoyingly we can't use popen(3) here. */
956 if (fflush (stdout) == EOF) {
957 perror ("failed to flush standard output");
961 perror ("pipe failed");
970 if (pid == 0) { /* Child process. */
972 if (dup2 (fd[0], 0) < 0) {
973 perror ("dup2 of stdin failed");
977 r = system (pipecmd);
982 _exit (WEXITSTATUS (r));
985 if ((stdout_saved_fd = dup (1)) < 0) {
986 perror ("failed to dup stdout");
990 if (dup2 (fd[1], 1) < 0) {
991 perror ("failed to dup stdout");
992 close (stdout_saved_fd);
998 for (argc = 0; argv[argc] != NULL; ++argc)
1001 /* If --remote was set, then send this command to a remote process. */
1003 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1005 /* Otherwise execute it locally. */
1006 else if (STRCASEEQ (cmd, "help")) {
1011 r = display_command (argv[0]);
1013 else if (STRCASEEQ (cmd, "quit") ||
1014 STRCASEEQ (cmd, "exit") ||
1015 STRCASEEQ (cmd, "q")) {
1020 r = run_action (cmd, argc, argv);
1022 /* Always flush stdout after every command, so that messages, results
1023 * etc appear immediately.
1025 if (fflush (stdout) == EOF) {
1026 perror ("failed to flush standard output");
1032 if (dup2 (stdout_saved_fd, 1) < 0) {
1033 perror ("failed to dup2 standard output");
1036 close (stdout_saved_fd);
1037 if (waitpid (pid, NULL, 0) < 0) {
1038 perror ("waiting for command to complete");
1047 list_builtin_commands (void)
1049 /* help and quit should appear at the top */
1050 printf ("%-20s %s\n",
1051 "help", _("display a list of commands or help on a command"));
1052 printf ("%-20s %s\n",
1053 "quit", _("quit guestfish"));
1055 /* actions are printed after this (see list_commands) */
1059 display_builtin_command (const char *cmd)
1061 /* help for actions is auto-generated, see display_command */
1063 if (STRCASEEQ (cmd, "help")) {
1064 printf (_("help - display a list of commands or help on a command\n"
1069 else if (STRCASEEQ (cmd, "quit") ||
1070 STRCASEEQ (cmd, "exit") ||
1071 STRCASEEQ (cmd, "q")) {
1072 printf (_("quit - quit guestfish\n"
1077 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1083 /* This is printed when the user types in an unknown command for the
1084 * first command issued. A common case is the user doing:
1085 * guestfish disk.img
1086 * expecting guestfish to open 'disk.img' (in fact, this tried to
1087 * run a command 'disk.img').
1090 extended_help_message (void)
1093 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1094 "For a list of commands: guestfish -h\n"
1095 "For complete documentation: man guestfish\n"));
1099 free_strings (char **argv)
1103 for (argc = 0; argv[argc] != NULL; ++argc)
1109 count_strings (char *const *argv)
1113 for (c = 0; argv[c]; ++c)
1119 print_strings (char *const *argv)
1123 for (argc = 0; argv[argc] != NULL; ++argc)
1124 printf ("%s\n", argv[argc]);
1128 print_table (char *const *argv)
1132 for (i = 0; argv[i] != NULL; i += 2)
1133 printf ("%s: %s\n", argv[i], argv[i+1]);
1137 is_true (const char *str)
1140 STRCASENEQ (str, "0") &&
1141 STRCASENEQ (str, "f") &&
1142 STRCASENEQ (str, "false") &&
1143 STRCASENEQ (str, "n") &&
1144 STRCASENEQ (str, "no");
1147 /* Free strings from a non-NULL terminated char** */
1149 free_n_strings (char **str, size_t len)
1153 for (i = 0; i < len; i++) {
1160 parse_string_list (const char *str)
1163 size_t argv_len = 0;
1165 /* Current position pointer */
1166 const char *p = str;
1168 /* Token might be simple:
1171 * 'This is a single token'
1172 * or contain embedded single-quoted sections:
1173 * This' is a sing'l'e to'ken
1175 * The latter may seem over-complicated, but it's what a normal shell does.
1176 * Not doing it risks surprising somebody.
1178 * This outer loop is over complete tokens.
1184 /* Skip leading whitespace */
1185 p += strspn (p, " \t");
1189 /* This loop is over token 'fragments'. A token can be in multiple bits if
1190 * it contains single quotes. We also treat both sides of an escaped quote
1191 * as separate fragments because we can't just copy it: we have to remove
1194 while (*p && (!c_isblank (*p) || in_quote)) {
1195 const char *end = p;
1197 /* Check if the fragment starts with a quote */
1199 /* Toggle in_quote */
1200 in_quote = !in_quote;
1202 /* Skip the quote */
1206 /* If we're in a quote, look for an end quote */
1208 end += strcspn (end, "'");
1211 /* Otherwise, look for whitespace or a quote */
1213 end += strcspn (end, " \t'");
1216 /* Grow the token to accommodate the fragment */
1217 size_t tok_end = tok_len;
1219 char *tok_new = realloc (tok, tok_len + 1);
1220 if (NULL == tok_new) {
1222 free_n_strings (argv, argv_len);
1224 exit (EXIT_FAILURE);
1228 /* Check if we stopped on an escaped quote */
1229 if ('\'' == *end && end != p && *(end-1) == '\\') {
1230 /* Add everything before \' to the token */
1231 memcpy (&tok[tok_end], p, end - p - 1);
1234 tok[tok_len-1] = '\'';
1236 /* Already processed the quote */
1241 /* Add the whole fragment */
1242 memcpy (&tok[tok_end], p, end - p);
1248 /* We've reached the end of a token. We shouldn't still be in quotes. */
1250 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1252 free_n_strings (argv, argv_len);
1257 /* Add this token if there is one. There might not be if there was
1258 * whitespace at the end of the input string */
1260 /* Add the NULL terminator */
1261 tok[tok_len] = '\0';
1263 /* Add the argument to the argument list */
1265 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1266 if (NULL == argv_new) {
1268 free_n_strings (argv, argv_len-1);
1270 exit (EXIT_FAILURE);
1274 argv[argv_len-1] = tok;
1278 /* NULL terminate the argument list */
1280 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1281 if (NULL == argv_new) {
1283 free_n_strings (argv, argv_len-1);
1284 exit (EXIT_FAILURE);
1288 argv[argv_len-1] = NULL;
1293 #ifdef HAVE_LIBREADLINE
1294 static char histfile[1024];
1295 static int nr_history_lines = 0;
1299 initialize_readline (void)
1301 #ifdef HAVE_LIBREADLINE
1304 home = getenv ("HOME");
1306 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1308 (void) read_history (histfile);
1311 rl_readline_name = "guestfish";
1312 rl_attempted_completion_function = do_completion;
1314 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1315 * call the readline(), which happens later. Therefore, these
1316 * provide default values which can be overridden by the user if
1319 (void) rl_variable_bind ("completion-ignore-case", "on");
1324 cleanup_readline (void)
1326 #ifdef HAVE_LIBREADLINE
1329 if (histfile[0] != '\0') {
1330 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1337 #ifdef HAVE_APPEND_HISTORY
1338 (void) append_history (nr_history_lines, histfile);
1340 (void) write_history (histfile);
1347 #ifdef HAVE_LIBREADLINE
1349 add_history_line (const char *line)
1357 xwrite (int fd, const void *v_buf, size_t len)
1360 const char *buf = v_buf;
1363 r = write (fd, buf, len);
1375 /* Resolve the special "win:..." form for Windows-specific paths.
1376 * This always returns a newly allocated string which is freed by the
1377 * caller function in "cmds.c".
1380 resolve_win_path (const char *path)
1385 if (STRCASENEQLEN (path, "win:", 4)) {
1386 ret = strdup (path);
1394 /* Drop drive letter, if it's "C:". */
1395 if (STRCASEEQLEN (path, "c:", 2))
1405 ret = strdup (path);
1411 /* Blindly convert any backslashes into forward slashes. Is this good? */
1412 for (i = 0; i < strlen (ret); ++i)
1416 char *t = guestfs_case_sensitive_path (g, ret);
1423 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1424 * The caller (cmds.c) will call free_file_in after the command has
1425 * run which should clean up resources.
1427 static char *file_in_heredoc (const char *endmarker);
1428 static char *file_in_tmpfile = NULL;
1431 file_in (const char *arg)
1435 if (STREQ (arg, "-")) {
1436 ret = strdup ("/dev/stdin");
1442 else if (STRPREFIX (arg, "-<<")) {
1443 const char *endmarker = &arg[3];
1444 if (*endmarker == '\0') {
1445 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1449 ret = file_in_heredoc (endmarker);
1465 file_in_heredoc (const char *endmarker)
1467 TMP_TEMPLATE_ON_STACK (template);
1468 file_in_tmpfile = strdup (template);
1469 if (file_in_tmpfile == NULL) {
1474 int fd = mkstemp (file_in_tmpfile);
1480 size_t markerlen = strlen (endmarker);
1482 char buffer[BUFSIZ];
1483 int write_error = 0;
1484 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1485 /* Look for "END"<EOF> or "END\n" in input. */
1486 size_t blen = strlen (buffer);
1487 if (STREQLEN (buffer, endmarker, markerlen) &&
1488 (blen == markerlen ||
1489 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1492 if (xwrite (fd, buffer, blen) == -1) {
1493 if (!write_error) perror ("write");
1495 /* continue reading up to the end marker */
1499 /* Reached EOF of stdin without finding the end marker, which
1500 * is likely to be an error.
1502 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1503 program_name, endmarker);
1512 if (close (fd) == -1) {
1517 return file_in_tmpfile;
1520 unlink (file_in_tmpfile);
1523 free (file_in_tmpfile);
1524 file_in_tmpfile = NULL;
1529 free_file_in (char *s)
1531 if (file_in_tmpfile) {
1532 if (unlink (file_in_tmpfile) == -1)
1533 perror (file_in_tmpfile);
1534 file_in_tmpfile = NULL;
1537 /* Free the device or file name which was strdup'd in file_in().
1538 * Note it's not immediately clear, but for -<< heredocs,
1539 * s == file_in_tmpfile, so this frees up that buffer.
1544 /* Resolve the special FileOut paths ("-" or filename).
1545 * The caller (cmds.c) will call free (str) after the command has run.
1548 file_out (const char *arg)
1552 if (STREQ (arg, "-"))
1553 ret = strdup ("/dev/stdout");