1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2010 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. */
79 int remote_control_listen = 0;
80 int remote_control_csh = 0;
81 int remote_control = 0;
83 int keys_from_stdin = 0;
85 const char *libvirt_uri = NULL;
88 int have_terminfo = 0;
89 int progress_bars = 0;
91 static void __attribute__((noreturn))
94 if (status != EXIT_SUCCESS)
95 fprintf (stderr, _("Try `%s --help' for more information.\n"),
99 _("%s: guest filesystem shell\n"
100 "%s lets you edit virtual machine filesystems\n"
101 "Copyright (C) 2009-2010 Red Hat Inc.\n"
103 " %s [--options] cmd [: cmd : cmd ...]\n"
104 " %s [--ro] -i -a disk-image\n"
105 " %s [--ro] -i -d libvirt-domain\n"
106 "or for interactive use:\n"
108 "or from a shell script:\n"
114 " -h|--cmd-help List available commands\n"
115 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
116 " -a|--add image Add image\n"
117 " -c|--connect uri Specify libvirt URI for -d option\n"
118 " --csh Make --listen csh-compatible\n"
119 " -d|--domain guest Add disks from libvirt guest\n"
120 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
121 " --echo-keys Don't turn off echo for passphrases\n"
122 " -f|--file file Read commands from file\n"
123 " --format[=raw|..] Force disk format for -a option\n"
124 " -i|--inspector Automatically mount filesystems\n"
125 " --keys-from-stdin Read passphrases from stdin\n"
126 " --listen Listen for remote commands\n"
127 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
128 " -n|--no-sync Don't autosync\n"
129 " -N|--new type Create prepared disk (test1.img, ...)\n"
130 " --progress-bars Enable progress bars even when not interactive\n"
131 " --no-progress-bars Disable progress bars\n"
132 " --remote[=pid] Send commands to remote %s\n"
133 " -r|--ro Mount read-only\n"
134 " --selinux Enable SELinux support\n"
135 " -v|--verbose Verbose messages\n"
136 " -V|--version Display version and exit\n"
137 " -x Echo each command before executing it\n"
138 "For more information, see the manpage %s(1).\n"),
139 program_name, program_name, program_name,
140 program_name, program_name, program_name,
141 program_name, program_name, program_name);
147 main (int argc, char *argv[])
149 /* Set global program name that is not polluted with libtool artifacts. */
150 set_program_name (argv[0]);
152 atexit (close_stdout);
154 setlocale (LC_ALL, "");
155 bindtextdomain (PACKAGE, LOCALEBASEDIR);
156 textdomain (PACKAGE);
160 enum { HELP_OPTION = CHAR_MAX + 1 };
162 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
163 static const struct option long_options[] = {
164 { "add", 1, 0, 'a' },
165 { "cmd-help", 2, 0, 'h' },
166 { "connect", 1, 0, 'c' },
168 { "domain", 1, 0, 'd' },
169 { "echo-keys", 0, 0, 0 },
170 { "file", 1, 0, 'f' },
171 { "format", 2, 0, 0 },
172 { "help", 0, 0, HELP_OPTION },
173 { "inspector", 0, 0, 'i' },
174 { "keys-from-stdin", 0, 0, 0 },
175 { "listen", 0, 0, 0 },
176 { "mount", 1, 0, 'm' },
177 { "new", 1, 0, 'N' },
178 { "no-dest-paths", 0, 0, 'D' },
179 { "no-sync", 0, 0, 'n' },
180 { "progress-bars", 0, 0, 0 },
181 { "no-progress-bars", 0, 0, 0 },
182 { "remote", 2, 0, 0 },
185 { "selinux", 0, 0, 0 },
186 { "verbose", 0, 0, 'v' },
187 { "version", 0, 0, 'V' },
190 struct drv *drvs = NULL;
192 struct mp *mps = NULL;
194 char *p, *file = NULL;
195 const char *format = NULL;
199 int next_prepared_drive = 1;
201 initialize_readline ();
203 memset (&sa, 0, sizeof sa);
204 sa.sa_handler = SIG_IGN;
205 sa.sa_flags = SA_RESTART;
206 sigaction (SIGPIPE, &sa, NULL);
208 /* guestfs_create is meant to be a lightweight operation, so
209 * it's OK to do it early here.
211 g = guestfs_create ();
213 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
217 /* If developing, add ./appliance to the path. Note that libtools
218 * interferes with this because uninstalled guestfish is a shell
219 * script that runs the real program with an absolute path. Detect
222 * BUT if LIBGUESTFS_PATH environment variable is already set by
223 * the user, then don't override it.
225 if (getenv ("LIBGUESTFS_PATH") == NULL &&
227 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
228 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
230 /* CAUTION: we are careful to modify argv[0] here, only after
231 * using it just above.
233 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
234 * of the original, in case it's needed below.
236 //char *real_argv0 = argv[0];
237 argv[0] = bad_cast (program_name);
240 c = getopt_long (argc, argv, options, long_options, &option_index);
244 case 0: /* options which are long only */
245 if (STREQ (long_options[option_index].name, "listen"))
246 remote_control_listen = 1;
247 else if (STREQ (long_options[option_index].name, "remote")) {
249 if (sscanf (optarg, "%d", &remote_control) != 1) {
250 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
251 program_name, optarg);
255 p = getenv ("GUESTFISH_PID");
256 if (!p || sscanf (p, "%d", &remote_control) != 1) {
257 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
258 " to the PID of the remote process\n"),
263 } else if (STREQ (long_options[option_index].name, "selinux")) {
264 guestfs_set_selinux (g, 1);
265 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
267 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
268 override_progress_bars = 1;
269 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
270 override_progress_bars = 0;
271 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
273 } else if (STREQ (long_options[option_index].name, "format")) {
274 if (!optarg || STREQ (optarg, ""))
278 } else if (STREQ (long_options[option_index].name, "csh")) {
279 remote_control_csh = 1;
281 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
282 program_name, long_options[option_index].name, option_index);
300 complete_dest_paths = 0;
305 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
316 r = display_command (optarg);
317 else if (argv[optind] && argv[optind][0] != '-')
318 r = display_command (argv[optind++]);
322 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
338 if (STRCASEEQ (optarg, "list") ||
339 STRCASEEQ (optarg, "help") ||
340 STRCASEEQ (optarg, "h") ||
341 STRCASEEQ (optarg, "?")) {
342 list_prepared_drives ();
345 drv = malloc (sizeof (struct drv));
353 if (asprintf (&drv->N.filename, "test%d.img",
354 next_prepared_drive++) == -1) {
358 drv->N.data = create_prepared_file (optarg, drv->N.filename);
359 drv->N.data_free = free_prep_data;
385 usage (EXIT_SUCCESS);
388 usage (EXIT_FAILURE);
392 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
393 * previously, if we have -i without any drives but with something
394 * on the command line, it must be old-style syntax.
396 if (inspector && drvs == NULL && optind < argc) {
397 while (optind < argc) {
398 if (strchr (argv[optind], '/') ||
399 access (argv[optind], F_OK) == 0) { /* simulate -a option */
400 drv = malloc (sizeof (struct drv));
406 drv->a.filename = argv[optind];
407 drv->a.format = NULL;
410 } else { /* simulate -d option */
411 drv = malloc (sizeof (struct drv));
417 drv->d.guest = argv[optind];
426 /* If we've got drives to add, add them now. */
427 add_drives (drvs, 'a');
429 /* If we've got mountpoints or prepared drives or -i option, we must
430 * launch the guest and mount them.
432 if (next_prepared_drive > 1 || mps != NULL || inspector) {
433 /* RHBZ#612178: If --listen flag is given, then we will fork into
434 * the background in rc_listen(). However you can't do this while
435 * holding a libguestfs handle open because the recovery process
436 * will think the main program has died and kill qemu. Therefore
437 * don't use the recovery process for this case. (A better
438 * solution would be to call launch () etc after the fork, but
439 * that greatly complicates the code here).
441 if (remote_control_listen)
442 guestfs_set_recovery_proc (g, 0);
444 if (launch () == -1) exit (EXIT_FAILURE);
449 prepare_drives (drvs);
453 /* Free up data structures, no longer needed after this point. */
457 /* Remote control? */
458 if (remote_control_listen && remote_control) {
460 _("%s: cannot use --listen and --remote options at the same time\n"),
465 if (remote_control_listen) {
468 _("%s: extra parameters on the command line with --listen flag\n"),
474 _("%s: cannot use --listen and --file options at the same time\n"),
481 /* -f (file) parameter? */
484 if (open (file, O_RDONLY) == -1) {
490 /* Decide if we display progress bars. */
492 override_progress_bars >= 0
493 ? override_progress_bars
494 : (optind >= argc && isatty (0));
497 guestfs_set_progress_callback (g, progress_callback, NULL);
499 /* Interactive, shell script, or command(s) on the command line? */
500 if (optind >= argc) {
507 cmdline (argv, optind, argc);
514 /* The <term.h> header file which defines this has "issues". */
515 extern int tgetent (char *, const char *);
518 set_up_terminal (void)
520 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
521 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
523 char *term = getenv ("TERM");
525 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
529 int r = tgetent (NULL, term);
531 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
535 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
544 prepare_drives (struct drv *drv)
547 prepare_drives (drv->next);
548 if (drv->type == drv_N)
549 prepare_drive (drv->N.filename, drv->N.data, drv->device);
556 if (guestfs_is_config (g)) {
557 if (guestfs_launch (g) == -1)
575 #define FISH "><fs> "
577 static char *line_read = NULL;
582 #ifdef HAVE_LIBREADLINE
590 line_read = readline (prompt ? FISH : "");
592 if (line_read && *line_read)
593 add_history_line (line_read);
598 #endif /* HAVE_LIBREADLINE */
600 static char buf[8192];
603 if (prompt) printf (FISH);
604 line_read = fgets (buf, sizeof buf, stdin);
607 len = strlen (line_read);
608 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
618 int global_exit_on_error = !prompt;
620 struct parsed_command pcmd;
624 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
625 "editing virtual machine filesystems.\n"
627 "Type: 'help' for help on commands\n"
628 " 'man' to read the manual\n"
629 " 'quit' to quit the shell\n"
633 print_inspect_prompt ();
639 exit_on_error = global_exit_on_error;
641 buf = rl_gets (prompt);
647 pcmd = parse_command_line (buf, &exit_on_error);
648 if (pcmd.status == -1 && exit_on_error)
650 if (pcmd.status == 1) {
651 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
652 if (exit_on_error) exit (EXIT_FAILURE);
656 if (prompt) printf ("\n");
659 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
660 * This destructively updates 'buf'.
662 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
663 * setting and to return the local setting (eg. if the command begins
666 * Returns in parsed_command.status:
667 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
668 * 0 = no guestfish command, but otherwise OK
671 static struct parsed_command
672 parse_command_line (char *buf, int *exit_on_error_rtn)
674 struct parsed_command pcmd;
679 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
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 = strcspn (p, "\"");
763 if (p[len] == '\0') {
764 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
768 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
770 _("%s: command arguments not separated by whitespace\n"),
776 pend = p[len+1] ? &p[len+2] : &p[len+1];
777 } else if (*p == '\'') {
779 len = strcspn (p, "'");
780 if (p[len] == '\0') {
781 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
785 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
787 _("%s: command arguments not separated by whitespace\n"),
793 pend = p[len+1] ? &p[len+2] : &p[len+1];
794 } else if (*p == '|') {
798 } else if (*p != ' ' && *p != '\t') {
799 /* If the first character is a ~ then note that this parameter
800 * is a candidate for ~username expansion. NB this does not
801 * apply to quoted parameters.
803 tilde_candidate = *p == '~';
804 len = strcspn (p, " \t");
811 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
816 if (!tilde_candidate)
819 pcmd.argv[i] = try_tilde_expansion (p);
824 p += strspn (p, " \t");
828 fprintf (stderr, _("%s: too many arguments\n"), program_name);
839 /* Used to handle "<!" (execute command and inline result). */
841 execute_and_inline (const char *cmd, int global_exit_on_error)
848 struct parsed_command pcmd;
850 pp = popen (cmd, "r");
856 while ((n = getline (&line, &len, pp)) != -1) {
857 exit_on_error = global_exit_on_error;
859 /* Chomp final line ending which parse_command_line would not expect. */
860 if (n > 0 && line[n-1] == '\n')
863 pcmd = parse_command_line (line, &exit_on_error);
864 if (pcmd.status == -1 && exit_on_error)
866 if (pcmd.status == 1) {
867 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
868 if (exit_on_error) exit (EXIT_FAILURE);
875 if (pclose (pp) == -1) {
884 cmdline (char *argv[], int optind, int argc)
892 if (optind >= argc) return;
894 cmd = argv[optind++];
895 if (STREQ (cmd, ":")) {
896 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
900 /* Allow -cmd on the command line to mean (temporarily) override
901 * the normal exit on error (RHBZ#578407).
908 params = &argv[optind];
910 /* Search for end of command list or ":" ... */
911 while (optind < argc && STRNEQ (argv[optind], ":"))
914 if (optind == argc) {
915 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
919 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
921 cmdline (argv, optind+1, argc);
925 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
926 * pass to the remote server (when issuing --remote commands). It
927 * does not cause issue_command itself to exit on error.
930 issue_command (const char *cmd, char *argv[], const char *pipecmd,
931 int rc_exit_on_error_flag)
934 int stdout_saved_fd = -1;
938 reset_progress_bar ();
940 /* This counts the commands issued, starting at 1. */
943 /* For | ... commands. Annoyingly we can't use popen(3) here. */
947 if (fflush (stdout) == EOF) {
948 perror ("failed to flush standard output");
952 perror ("pipe failed");
961 if (pid == 0) { /* Child process. */
963 if (dup2 (fd[0], 0) < 0) {
964 perror ("dup2 of stdin failed");
968 r = system (pipecmd);
973 _exit (WEXITSTATUS (r));
976 if ((stdout_saved_fd = dup (1)) < 0) {
977 perror ("failed to dup stdout");
981 if (dup2 (fd[1], 1) < 0) {
982 perror ("failed to dup stdout");
983 close (stdout_saved_fd);
989 for (argc = 0; argv[argc] != NULL; ++argc)
992 /* If --remote was set, then send this command to a remote process. */
994 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
996 /* Otherwise execute it locally. */
997 else if (STRCASEEQ (cmd, "help")) {
1002 r = display_command (argv[0]);
1004 else if (STRCASEEQ (cmd, "quit") ||
1005 STRCASEEQ (cmd, "exit") ||
1006 STRCASEEQ (cmd, "q")) {
1011 r = run_action (cmd, argc, argv);
1013 /* Always flush stdout after every command, so that messages, results
1014 * etc appear immediately.
1016 if (fflush (stdout) == EOF) {
1017 perror ("failed to flush standard output");
1023 if (dup2 (stdout_saved_fd, 1) < 0) {
1024 perror ("failed to dup2 standard output");
1027 close (stdout_saved_fd);
1028 if (waitpid (pid, NULL, 0) < 0) {
1029 perror ("waiting for command to complete");
1038 list_builtin_commands (void)
1040 /* help and quit should appear at the top */
1041 printf ("%-20s %s\n",
1042 "help", _("display a list of commands or help on a command"));
1043 printf ("%-20s %s\n",
1044 "quit", _("quit guestfish"));
1046 /* actions are printed after this (see list_commands) */
1050 display_builtin_command (const char *cmd)
1052 /* help for actions is auto-generated, see display_command */
1054 if (STRCASEEQ (cmd, "help")) {
1055 printf (_("help - display a list of commands or help on a command\n"
1060 else if (STRCASEEQ (cmd, "quit") ||
1061 STRCASEEQ (cmd, "exit") ||
1062 STRCASEEQ (cmd, "q")) {
1063 printf (_("quit - quit guestfish\n"
1068 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1074 /* This is printed when the user types in an unknown command for the
1075 * first command issued. A common case is the user doing:
1076 * guestfish disk.img
1077 * expecting guestfish to open 'disk.img' (in fact, this tried to
1078 * run a command 'disk.img').
1081 extended_help_message (void)
1084 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1085 "For a list of commands: guestfish -h\n"
1086 "For complete documentation: man guestfish\n"));
1090 free_strings (char **argv)
1094 for (argc = 0; argv[argc] != NULL; ++argc)
1100 count_strings (char *const *argv)
1104 for (c = 0; argv[c]; ++c)
1110 print_strings (char *const *argv)
1114 for (argc = 0; argv[argc] != NULL; ++argc)
1115 printf ("%s\n", argv[argc]);
1119 print_table (char *const *argv)
1123 for (i = 0; argv[i] != NULL; i += 2)
1124 printf ("%s: %s\n", argv[i], argv[i+1]);
1128 is_true (const char *str)
1131 STRCASENEQ (str, "0") &&
1132 STRCASENEQ (str, "f") &&
1133 STRCASENEQ (str, "false") &&
1134 STRCASENEQ (str, "n") &&
1135 STRCASENEQ (str, "no");
1138 /* Free strings from a non-NULL terminated char** */
1140 free_n_strings (char **str, size_t len)
1144 for (i = 0; i < len; i++) {
1151 parse_string_list (const char *str)
1154 size_t argv_len = 0;
1156 /* Current position pointer */
1157 const char *p = str;
1159 /* Token might be simple:
1162 * 'This is a single token'
1163 * or contain embedded single-quoted sections:
1164 * This' is a sing'l'e to'ken
1166 * The latter may seem over-complicated, but it's what a normal shell does.
1167 * Not doing it risks surprising somebody.
1169 * This outer loop is over complete tokens.
1175 /* Skip leading whitespace */
1176 p += strspn (p, " \t");
1180 /* This loop is over token 'fragments'. A token can be in multiple bits if
1181 * it contains single quotes. We also treat both sides of an escaped quote
1182 * as separate fragments because we can't just copy it: we have to remove
1185 while (*p && (!c_isblank (*p) || in_quote)) {
1186 const char *end = p;
1188 /* Check if the fragment starts with a quote */
1190 /* Toggle in_quote */
1191 in_quote = !in_quote;
1193 /* Skip the quote */
1197 /* If we're in a quote, look for an end quote */
1199 end += strcspn (end, "'");
1202 /* Otherwise, look for whitespace or a quote */
1204 end += strcspn (end, " \t'");
1207 /* Grow the token to accommodate the fragment */
1208 size_t tok_end = tok_len;
1210 char *tok_new = realloc (tok, tok_len + 1);
1211 if (NULL == tok_new) {
1213 free_n_strings (argv, argv_len);
1215 exit (EXIT_FAILURE);
1219 /* Check if we stopped on an escaped quote */
1220 if ('\'' == *end && end != p && *(end-1) == '\\') {
1221 /* Add everything before \' to the token */
1222 memcpy (&tok[tok_end], p, end - p - 1);
1225 tok[tok_len-1] = '\'';
1227 /* Already processed the quote */
1232 /* Add the whole fragment */
1233 memcpy (&tok[tok_end], p, end - p);
1239 /* We've reached the end of a token. We shouldn't still be in quotes. */
1241 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1243 free_n_strings (argv, argv_len);
1248 /* Add this token if there is one. There might not be if there was
1249 * whitespace at the end of the input string */
1251 /* Add the NULL terminator */
1252 tok[tok_len] = '\0';
1254 /* Add the argument to the argument list */
1256 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1257 if (NULL == argv_new) {
1259 free_n_strings (argv, argv_len-1);
1261 exit (EXIT_FAILURE);
1265 argv[argv_len-1] = tok;
1269 /* NULL terminate the argument list */
1271 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1272 if (NULL == argv_new) {
1274 free_n_strings (argv, argv_len-1);
1275 exit (EXIT_FAILURE);
1279 argv[argv_len-1] = NULL;
1284 #ifdef HAVE_LIBREADLINE
1285 static char histfile[1024];
1286 static int nr_history_lines = 0;
1290 initialize_readline (void)
1292 #ifdef HAVE_LIBREADLINE
1295 home = getenv ("HOME");
1297 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1299 (void) read_history (histfile);
1302 rl_readline_name = "guestfish";
1303 rl_attempted_completion_function = do_completion;
1305 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1306 * call the readline(), which happens later. Therefore, these
1307 * provide default values which can be overridden by the user if
1310 (void) rl_variable_bind ("completion-ignore-case", "on");
1315 cleanup_readline (void)
1317 #ifdef HAVE_LIBREADLINE
1320 if (histfile[0] != '\0') {
1321 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1328 #ifdef HAVE_APPEND_HISTORY
1329 (void) append_history (nr_history_lines, histfile);
1331 (void) write_history (histfile);
1338 #ifdef HAVE_LIBREADLINE
1340 add_history_line (const char *line)
1348 xwrite (int fd, const void *v_buf, size_t len)
1351 const char *buf = v_buf;
1354 r = write (fd, buf, len);
1366 /* Resolve the special "win:..." form for Windows-specific paths.
1367 * This always returns a newly allocated string which is freed by the
1368 * caller function in "cmds.c".
1371 resolve_win_path (const char *path)
1376 if (STRCASENEQLEN (path, "win:", 4)) {
1377 ret = strdup (path);
1385 /* Drop drive letter, if it's "C:". */
1386 if (STRCASEEQLEN (path, "c:", 2))
1396 ret = strdup (path);
1402 /* Blindly convert any backslashes into forward slashes. Is this good? */
1403 for (i = 0; i < strlen (ret); ++i)
1407 char *t = guestfs_case_sensitive_path (g, ret);
1414 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1415 * The caller (cmds.c) will call free_file_in after the command has
1416 * run which should clean up resources.
1418 static char *file_in_heredoc (const char *endmarker);
1419 static char *file_in_tmpfile = NULL;
1422 file_in (const char *arg)
1426 if (STREQ (arg, "-")) {
1427 ret = strdup ("/dev/stdin");
1433 else if (STRPREFIX (arg, "-<<")) {
1434 const char *endmarker = &arg[3];
1435 if (*endmarker == '\0') {
1436 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1440 ret = file_in_heredoc (endmarker);
1456 file_in_heredoc (const char *endmarker)
1458 TMP_TEMPLATE_ON_STACK (template);
1459 file_in_tmpfile = strdup (template);
1460 if (file_in_tmpfile == NULL) {
1465 int fd = mkstemp (file_in_tmpfile);
1471 size_t markerlen = strlen (endmarker);
1473 char buffer[BUFSIZ];
1474 int write_error = 0;
1475 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1476 /* Look for "END"<EOF> or "END\n" in input. */
1477 size_t blen = strlen (buffer);
1478 if (STREQLEN (buffer, endmarker, markerlen) &&
1479 (blen == markerlen ||
1480 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1483 if (xwrite (fd, buffer, blen) == -1) {
1484 if (!write_error) perror ("write");
1486 /* continue reading up to the end marker */
1490 /* Reached EOF of stdin without finding the end marker, which
1491 * is likely to be an error.
1493 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1494 program_name, endmarker);
1503 if (close (fd) == -1) {
1508 return file_in_tmpfile;
1511 unlink (file_in_tmpfile);
1514 free (file_in_tmpfile);
1515 file_in_tmpfile = NULL;
1520 free_file_in (char *s)
1522 if (file_in_tmpfile) {
1523 if (unlink (file_in_tmpfile) == -1)
1524 perror (file_in_tmpfile);
1525 file_in_tmpfile = NULL;
1528 /* Free the device or file name which was strdup'd in file_in().
1529 * Note it's not immediately clear, but for -<< heredocs,
1530 * s == file_in_tmpfile, so this frees up that buffer.
1535 /* Resolve the special FileOut paths ("-" or filename).
1536 * The caller (cmds.c) will call free (str) after the command has run.
1539 file_out (const char *arg)
1543 if (STREQ (arg, "-"))
1544 ret = strdup ("/dev/stdout");