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>
35 #ifdef HAVE_LIBREADLINE
36 #include <readline/readline.h>
37 #include <readline/history.h>
47 /* List of drives added via -a, -d or -N options. */
50 enum { drv_a, drv_d, drv_N } type;
53 char *filename; /* disk filename */
56 char *guest; /* guest name */
59 char *filename; /* disk filename (testX.img) */
60 prep_data *data; /* prepared type */
61 char *device; /* device inside the appliance */
72 static void set_up_terminal (void);
73 static char add_drives (struct drv *drv, char next_drive);
74 static void prepare_drives (struct drv *drv);
75 static void mount_mps (struct mp *mp);
76 static int launch (void);
77 static void interactive (void);
78 static void shell_script (void);
79 static void script (int prompt);
80 static void cmdline (char *argv[], int optind, int argc);
81 static void initialize_readline (void);
82 static void cleanup_readline (void);
83 #ifdef HAVE_LIBREADLINE
84 static void add_history_line (const char *);
87 static int override_progress_bars = -1;
89 /* Currently open libguestfs handle. */
95 int remote_control_listen = 0;
96 int remote_control = 0;
97 int exit_on_error = 1;
99 int keys_from_stdin = 0;
101 const char *libvirt_uri = NULL;
104 int have_terminfo = 0;
105 int progress_bars = 0;
107 static void __attribute__((noreturn))
110 if (status != EXIT_SUCCESS)
111 fprintf (stderr, _("Try `%s --help' for more information.\n"),
115 _("%s: guest filesystem shell\n"
116 "%s lets you edit virtual machine filesystems\n"
117 "Copyright (C) 2009-2010 Red Hat Inc.\n"
119 " %s [--options] cmd [: cmd : cmd ...]\n"
120 " %s [--ro] -i -a disk-image\n"
121 " %s [--ro] -i -d libvirt-domain\n"
122 "or for interactive use:\n"
124 "or from a shell script:\n"
130 " -h|--cmd-help List available commands\n"
131 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
132 " -a|--add image Add image\n"
133 " -c|--connect uri Specify libvirt URI for -d option\n"
134 " -d|--domain guest Add disks from libvirt guest\n"
135 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
136 " --echo-keys Don't turn off echo for passphrases\n"
137 " -f|--file file Read commands from file\n"
138 " -i|--inspector Automatically mount filesystems\n"
139 " --keys-from-stdin Read passphrases from stdin\n"
140 " --listen Listen for remote commands\n"
141 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
142 " -n|--no-sync Don't autosync\n"
143 " -N|--new type Create prepared disk (test1.img, ...)\n"
144 " --progress-bars Enable progress bars even when not interactive\n"
145 " --no-progress-bars Disable progress bars\n"
146 " --remote[=pid] Send commands to remote %s\n"
147 " -r|--ro Mount read-only\n"
148 " --selinux Enable SELinux support\n"
149 " -v|--verbose Verbose messages\n"
150 " -x Echo each command before executing it\n"
151 " -V|--version Display version and exit\n"
152 "For more information, see the manpage %s(1).\n"),
153 program_name, program_name, program_name,
154 program_name, program_name, program_name,
155 program_name, program_name, program_name);
161 main (int argc, char *argv[])
163 /* Set global program name that is not polluted with libtool artifacts. */
164 set_program_name (argv[0]);
166 atexit (close_stdout);
168 setlocale (LC_ALL, "");
169 bindtextdomain (PACKAGE, LOCALEBASEDIR);
170 textdomain (PACKAGE);
174 enum { HELP_OPTION = CHAR_MAX + 1 };
176 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
177 static const struct option long_options[] = {
178 { "add", 1, 0, 'a' },
179 { "cmd-help", 2, 0, 'h' },
180 { "connect", 1, 0, 'c' },
181 { "domain", 1, 0, 'd' },
182 { "echo-keys", 0, 0, 0 },
183 { "file", 1, 0, 'f' },
184 { "help", 0, 0, HELP_OPTION },
185 { "inspector", 0, 0, 'i' },
186 { "keys-from-stdin", 0, 0, 0 },
187 { "listen", 0, 0, 0 },
188 { "mount", 1, 0, 'm' },
189 { "new", 1, 0, 'N' },
190 { "no-dest-paths", 0, 0, 'D' },
191 { "no-sync", 0, 0, 'n' },
192 { "progress-bars", 0, 0, 0 },
193 { "no-progress-bars", 0, 0, 0 },
194 { "remote", 2, 0, 0 },
196 { "selinux", 0, 0, 0 },
197 { "verbose", 0, 0, 'v' },
198 { "version", 0, 0, 'V' },
201 struct drv *drvs = NULL;
203 struct mp *mps = NULL;
205 char *p, *file = NULL;
209 int next_prepared_drive = 1;
211 initialize_readline ();
213 memset (&sa, 0, sizeof sa);
214 sa.sa_handler = SIG_IGN;
215 sa.sa_flags = SA_RESTART;
216 sigaction (SIGPIPE, &sa, NULL);
218 /* guestfs_create is meant to be a lightweight operation, so
219 * it's OK to do it early here.
221 g = guestfs_create ();
223 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
227 guestfs_set_autosync (g, 1);
229 /* If developing, add ./appliance to the path. Note that libtools
230 * interferes with this because uninstalled guestfish is a shell
231 * script that runs the real program with an absolute path. Detect
234 * BUT if LIBGUESTFS_PATH environment variable is already set by
235 * the user, then don't override it.
237 if (getenv ("LIBGUESTFS_PATH") == NULL &&
239 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
240 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
242 /* CAUTION: we are careful to modify argv[0] here, only after
243 * using it just above.
245 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
246 * of the original, in case it's needed below.
248 char *real_argv0 = argv[0];
249 argv[0] = bad_cast (program_name);
252 c = getopt_long (argc, argv, options, long_options, &option_index);
256 case 0: /* options which are long only */
257 if (STREQ (long_options[option_index].name, "listen"))
258 remote_control_listen = 1;
259 else if (STREQ (long_options[option_index].name, "remote")) {
261 if (sscanf (optarg, "%d", &remote_control) != 1) {
262 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
263 program_name, optarg);
267 p = getenv ("GUESTFISH_PID");
268 if (!p || sscanf (p, "%d", &remote_control) != 1) {
269 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
270 " to the PID of the remote process\n"),
275 } else if (STREQ (long_options[option_index].name, "selinux")) {
276 guestfs_set_selinux (g, 1);
277 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
279 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
280 override_progress_bars = 1;
281 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
282 override_progress_bars = 0;
283 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
286 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
287 program_name, long_options[option_index].name, option_index);
293 if (access (optarg, R_OK) != 0) {
297 drv = malloc (sizeof (struct drv));
303 drv->a.filename = optarg;
309 libvirt_uri = optarg;
313 drv = malloc (sizeof (struct drv));
319 drv->d.guest = optarg;
325 if (STRCASEEQ (optarg, "list") ||
326 STRCASEEQ (optarg, "help") ||
327 STRCASEEQ (optarg, "h") ||
328 STRCASEEQ (optarg, "?")) {
329 list_prepared_drives ();
332 drv = malloc (sizeof (struct drv));
338 if (asprintf (&drv->N.filename, "test%d.img",
339 next_prepared_drive++) == -1) {
343 drv->N.data = create_prepared_file (optarg, drv->N.filename);
344 drv->N.device = NULL; /* filled in by add_drives */
350 complete_dest_paths = 0;
355 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
366 r = display_command (optarg);
367 else if (argv[optind] && argv[optind][0] != '-')
368 r = display_command (argv[optind++]);
372 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
380 mp = malloc (sizeof (struct mp));
385 p = strchr (optarg, ':');
388 mp->mountpoint = p+1;
390 mp->mountpoint = bad_cast ("/");
397 guestfs_set_autosync (g, 0);
406 guestfs_set_verbose (g, verbose);
410 struct guestfs_version *v = guestfs_version (g);
411 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
412 v->major, v->minor, v->release, v->extra);
417 guestfs_set_trace (g, 1);
421 usage (EXIT_SUCCESS);
424 usage (EXIT_FAILURE);
428 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
429 * previously, if we have -i without any drives but with something
430 * on the command line, it must be old-style syntax.
432 if (inspector && drvs == NULL && optind < argc) {
433 while (optind < argc) {
434 if (strchr (argv[optind], '/') ||
435 access (argv[optind], F_OK) == 0) { /* simulate -a option */
436 drv = malloc (sizeof (struct drv));
442 drv->a.filename = argv[optind];
445 } else { /* simulate -d option */
446 drv = malloc (sizeof (struct drv));
452 drv->d.guest = argv[optind];
461 /* If we've got drives to add, add them now. */
462 add_drives (drvs, 'a');
464 /* If we've got mountpoints or prepared drives or -i option, we must
465 * launch the guest and mount them.
467 if (next_prepared_drive > 1 || mps != NULL || inspector) {
468 /* RHBZ#612178: If --listen flag is given, then we will fork into
469 * the background in rc_listen(). However you can't do this while
470 * holding a libguestfs handle open because the recovery process
471 * will think the main program has died and kill qemu. Therefore
472 * don't use the recovery process for this case. (A better
473 * solution would be to call launch () etc after the fork, but
474 * that greatly complicates the code here).
476 if (remote_control_listen)
477 guestfs_set_recovery_proc (g, 0);
479 if (launch () == -1) exit (EXIT_FAILURE);
484 prepare_drives (drvs);
488 /* Remote control? */
489 if (remote_control_listen && remote_control) {
491 _("%s: cannot use --listen and --remote options at the same time\n"),
496 if (remote_control_listen) {
499 _("%s: extra parameters on the command line with --listen flag\n"),
505 _("%s: cannot use --listen and --file options at the same time\n"),
512 /* -f (file) parameter? */
515 if (open (file, O_RDONLY) == -1) {
521 /* Decide if we display progress bars. */
523 override_progress_bars >= 0
524 ? override_progress_bars
525 : (optind >= argc && isatty (0));
528 guestfs_set_progress_callback (g, progress_callback, NULL);
530 /* Interactive, shell script, or command(s) on the command line? */
531 if (optind >= argc) {
538 cmdline (argv, optind, argc);
545 /* The <term.h> header file which defines this has "issues". */
546 extern int tgetent (char *, const char *);
549 set_up_terminal (void)
551 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
552 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
554 char *term = getenv ("TERM");
556 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
560 int r = tgetent (NULL, term);
562 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
566 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
575 pod2text (const char *name, const char *shortdesc, const char *str)
579 fp = popen ("pod2text", "w");
581 /* pod2text failed, maybe not found, so let's just print the
582 * source instead, since that's better than doing nothing.
584 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
587 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
592 /* List is built in reverse order, so mount them in reverse order. */
594 mount_mps (struct mp *mp)
599 mount_mps (mp->next);
601 /* Don't use guestfs_mount here because that will default to mount
602 * options -o sync,noatime. For more information, see guestfs(3)
603 * section "LIBGUESTFS GOTCHAS".
605 const char *options = read_only ? "ro" : "";
606 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
608 /* Display possible mountpoints before exiting. */
609 char **fses = guestfs_list_filesystems (g);
610 if (fses == NULL || fses[0] == NULL)
613 _("guestfish: '%s' could not be mounted. Did you mean one of these?\n"),
616 for (i = 0; fses[i] != NULL; i += 2)
617 fprintf (stderr, "\t%s (%s)\n", fses[i], fses[i+1]);
626 add_drives (struct drv *drv, char next_drive)
630 if (next_drive > 'z') {
632 _("guestfish: too many drives added on the command line\n"));
637 next_drive = add_drives (drv->next, next_drive);
642 r = guestfs_add_drive (g, drv->a.filename);
644 r = guestfs_add_drive_ro (g, drv->a.filename);
652 r = add_libvirt_drives (drv->d.guest);
660 /* -N option is not affected by --ro */
661 r = guestfs_add_drive (g, drv->N.filename);
665 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
673 default: /* keep GCC happy */
682 prepare_drives (struct drv *drv)
685 prepare_drives (drv->next);
686 if (drv->type == drv_N)
687 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
694 if (guestfs_is_config (g)) {
695 if (guestfs_launch (g) == -1)
713 #define FISH "><fs> "
715 static char *line_read = NULL;
720 #ifdef HAVE_LIBREADLINE
728 line_read = readline (prompt ? FISH : "");
730 if (line_read && *line_read)
731 add_history_line (line_read);
736 #endif /* HAVE_LIBREADLINE */
738 static char buf[8192];
741 if (prompt) printf (FISH);
742 line_read = fgets (buf, sizeof buf, stdin);
745 len = strlen (line_read);
746 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
760 int global_exit_on_error = !prompt;
765 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
766 "editing virtual machine filesystems.\n"
768 "Type: 'help' for a list of commands\n"
769 " 'man' to read the manual\n"
770 " 'quit' to quit the shell\n"
774 print_inspect_prompt ();
782 exit_on_error = global_exit_on_error;
784 buf = rl_gets (prompt);
790 /* Skip any initial whitespace before the command. */
792 while (*buf && c_isspace (*buf))
797 /* If the next character is '#' then this is a comment. */
798 if (*buf == '#') continue;
800 /* If the next character is '!' then pass the whole lot to system(3). */
808 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
809 WEXITSTATUS (r) != 0)
815 /* If the next character is '-' allow the command to fail without
816 * exiting on error (just for this one command though).
824 /* Get the command (cannot be quoted). */
825 len = strcspn (buf, " \t");
827 if (len == 0) continue;
831 if (buf[len] == '\0') {
838 p += strspn (p, " \t");
840 /* Get the parameters. */
841 while (*p && i < sizeof argv / sizeof argv[0]) {
844 /* Parameters which start with quotes or pipes are treated
845 * specially. Bare parameters are delimited by whitespace.
849 len = strcspn (p, "\"");
850 if (p[len] == '\0') {
851 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
852 if (exit_on_error) exit (EXIT_FAILURE);
855 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
857 _("%s: command arguments not separated by whitespace\n"),
859 if (exit_on_error) exit (EXIT_FAILURE);
863 pend = p[len+1] ? &p[len+2] : &p[len+1];
864 } else if (*p == '\'') {
866 len = strcspn (p, "'");
867 if (p[len] == '\0') {
868 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
869 if (exit_on_error) exit (EXIT_FAILURE);
872 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
874 _("%s: command arguments not separated by whitespace\n"),
876 if (exit_on_error) exit (EXIT_FAILURE);
880 pend = p[len+1] ? &p[len+2] : &p[len+1];
881 } else if (*p == '|') {
886 } else if (*p == '[') {
890 while (*pend && c != 0) {
891 if (*pend == '[') c++;
892 else if (*pend == ']') c--;
897 _("%s: unterminated \"[...]\" sequence\n"), program_name);
898 if (exit_on_error) exit (EXIT_FAILURE);
901 if (*pend && (*pend != ' ' && *pend != '\t')) {
903 _("%s: command arguments not separated by whitespace\n"),
905 if (exit_on_error) exit (EXIT_FAILURE);
910 } else if (*p != ' ' && *p != '\t') {
911 /* If the first character is a ~ then note that this parameter
912 * is a candidate for ~username expansion. NB this does not
913 * apply to quoted parameters.
915 tilde_candidate = *p == '~';
916 len = strcspn (p, " \t");
923 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
928 if (!tilde_candidate)
931 argv[i] = try_tilde_expansion (p);
936 p += strspn (p, " \t");
939 if (i == sizeof argv / sizeof argv[0]) {
940 fprintf (stderr, _("%s: too many arguments\n"), program_name);
941 if (exit_on_error) exit (EXIT_FAILURE);
948 if (issue_command (cmd, argv, pipe) == -1) {
949 if (exit_on_error) exit (EXIT_FAILURE);
954 if (prompt) printf ("\n");
958 cmdline (char *argv[], int optind, int argc)
965 if (optind >= argc) return;
967 cmd = argv[optind++];
968 if (STREQ (cmd, ":")) {
969 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
973 /* Allow -cmd on the command line to mean (temporarily) override
974 * the normal exit on error (RHBZ#578407).
981 params = &argv[optind];
983 /* Search for end of command list or ":" ... */
984 while (optind < argc && STRNEQ (argv[optind], ":"))
987 if (optind == argc) {
988 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
992 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
994 cmdline (argv, optind+1, argc);
999 issue_command (const char *cmd, char *argv[], const char *pipecmd)
1002 int stdout_saved_fd = -1;
1006 reset_progress_bar ();
1008 /* This counts the commands issued, starting at 1. */
1011 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1015 if (fflush (stdout) == EOF) {
1016 perror ("failed to flush standard output");
1019 if (pipe (fd) < 0) {
1020 perror ("pipe failed");
1029 if (pid == 0) { /* Child process. */
1031 if (dup2 (fd[0], 0) < 0) {
1032 perror ("dup2 of stdin failed");
1036 r = system (pipecmd);
1041 _exit (WEXITSTATUS (r));
1044 if ((stdout_saved_fd = dup (1)) < 0) {
1045 perror ("failed to dup stdout");
1049 if (dup2 (fd[1], 1) < 0) {
1050 perror ("failed to dup stdout");
1051 close (stdout_saved_fd);
1057 for (argc = 0; argv[argc] != NULL; ++argc)
1060 /* If --remote was set, then send this command to a remote process. */
1062 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1064 /* Otherwise execute it locally. */
1065 else if (STRCASEEQ (cmd, "help")) {
1070 r = display_command (argv[0]);
1072 else if (STRCASEEQ (cmd, "quit") ||
1073 STRCASEEQ (cmd, "exit") ||
1074 STRCASEEQ (cmd, "q")) {
1079 r = run_action (cmd, argc, argv);
1081 /* Always flush stdout after every command, so that messages, results
1082 * etc appear immediately.
1084 if (fflush (stdout) == EOF) {
1085 perror ("failed to flush standard output");
1091 if (dup2 (stdout_saved_fd, 1) < 0) {
1092 perror ("failed to dup2 standard output");
1095 close (stdout_saved_fd);
1096 if (waitpid (pid, NULL, 0) < 0) {
1097 perror ("waiting for command to complete");
1106 list_builtin_commands (void)
1108 /* help and quit should appear at the top */
1109 printf ("%-20s %s\n",
1110 "help", _("display a list of commands or help on a command"));
1111 printf ("%-20s %s\n",
1112 "quit", _("quit guestfish"));
1114 /* actions are printed after this (see list_commands) */
1118 display_builtin_command (const char *cmd)
1120 /* help for actions is auto-generated, see display_command */
1122 if (STRCASEEQ (cmd, "help")) {
1123 printf (_("help - display a list of commands or help on a command\n"
1128 else if (STRCASEEQ (cmd, "quit") ||
1129 STRCASEEQ (cmd, "exit") ||
1130 STRCASEEQ (cmd, "q")) {
1131 printf (_("quit - quit guestfish\n"
1136 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1142 /* This is printed when the user types in an unknown command for the
1143 * first command issued. A common case is the user doing:
1144 * guestfish disk.img
1145 * expecting guestfish to open 'disk.img' (in fact, this tried to
1146 * run a command 'disk.img').
1149 extended_help_message (void)
1152 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1153 "For a list of commands: guestfish -h\n"
1154 "For complete documentation: man guestfish\n"));
1158 free_strings (char **argv)
1162 for (argc = 0; argv[argc] != NULL; ++argc)
1168 count_strings (char *const *argv)
1172 for (c = 0; argv[c]; ++c)
1178 print_strings (char *const *argv)
1182 for (argc = 0; argv[argc] != NULL; ++argc)
1183 printf ("%s\n", argv[argc]);
1187 print_table (char *const *argv)
1191 for (i = 0; argv[i] != NULL; i += 2)
1192 printf ("%s: %s\n", argv[i], argv[i+1]);
1196 is_true (const char *str)
1199 STRCASENEQ (str, "0") &&
1200 STRCASENEQ (str, "f") &&
1201 STRCASENEQ (str, "false") &&
1202 STRCASENEQ (str, "n") &&
1203 STRCASENEQ (str, "no");
1206 /* Free strings from a non-NULL terminated char** */
1208 free_n_strings (char **str, size_t len)
1212 for (i = 0; i < len; i++) {
1219 parse_string_list (const char *str)
1222 size_t argv_len = 0;
1224 /* Current position pointer */
1225 const char *p = str;
1227 /* Token might be simple:
1230 * 'This is a single token'
1231 * or contain embedded single-quoted sections:
1232 * This' is a sing'l'e to'ken
1234 * The latter may seem over-complicated, but it's what a normal shell does.
1235 * Not doing it risks surprising somebody.
1237 * This outer loop is over complete tokens.
1243 /* Skip leading whitespace */
1244 p += strspn (p, " \t");
1248 /* This loop is over token 'fragments'. A token can be in multiple bits if
1249 * it contains single quotes. We also treat both sides of an escaped quote
1250 * as separate fragments because we can't just copy it: we have to remove
1253 while (*p && (!c_isblank (*p) || in_quote)) {
1254 const char *end = p;
1256 /* Check if the fragment starts with a quote */
1258 /* Toggle in_quote */
1259 in_quote = !in_quote;
1261 /* Skip the quote */
1265 /* If we're in a quote, look for an end quote */
1267 end += strcspn (end, "'");
1270 /* Otherwise, look for whitespace or a quote */
1272 end += strcspn (end, " \t'");
1275 /* Grow the token to accommodate the fragment */
1276 size_t tok_end = tok_len;
1278 char *tok_new = realloc (tok, tok_len + 1);
1279 if (NULL == tok_new) {
1281 free_n_strings (argv, argv_len);
1283 exit (EXIT_FAILURE);
1287 /* Check if we stopped on an escaped quote */
1288 if ('\'' == *end && end != p && *(end-1) == '\\') {
1289 /* Add everything before \' to the token */
1290 memcpy (&tok[tok_end], p, end - p - 1);
1293 tok[tok_len-1] = '\'';
1295 /* Already processed the quote */
1300 /* Add the whole fragment */
1301 memcpy (&tok[tok_end], p, end - p);
1307 /* We've reached the end of a token. We shouldn't still be in quotes. */
1309 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1311 free_n_strings (argv, argv_len);
1316 /* Add this token if there is one. There might not be if there was
1317 * whitespace at the end of the input string */
1319 /* Add the NULL terminator */
1320 tok[tok_len] = '\0';
1322 /* Add the argument to the argument list */
1324 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1325 if (NULL == argv_new) {
1327 free_n_strings (argv, argv_len-1);
1329 exit (EXIT_FAILURE);
1333 argv[argv_len-1] = tok;
1337 /* NULL terminate the argument list */
1339 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1340 if (NULL == argv_new) {
1342 free_n_strings (argv, argv_len-1);
1343 exit (EXIT_FAILURE);
1347 argv[argv_len-1] = NULL;
1352 #ifdef HAVE_LIBREADLINE
1353 static char histfile[1024];
1354 static int nr_history_lines = 0;
1358 initialize_readline (void)
1360 #ifdef HAVE_LIBREADLINE
1363 home = getenv ("HOME");
1365 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1367 (void) read_history (histfile);
1370 rl_readline_name = "guestfish";
1371 rl_attempted_completion_function = do_completion;
1373 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1374 * call the readline(), which happens later. Therefore, these
1375 * provide default values which can be overridden by the user if
1378 (void) rl_variable_bind ("completion-ignore-case", "on");
1383 cleanup_readline (void)
1385 #ifdef HAVE_LIBREADLINE
1388 if (histfile[0] != '\0') {
1389 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1396 #ifdef HAVE_APPEND_HISTORY
1397 (void) append_history (nr_history_lines, histfile);
1399 (void) write_history (histfile);
1405 #ifdef HAVE_LIBREADLINE
1407 add_history_line (const char *line)
1415 xwrite (int fd, const void *v_buf, size_t len)
1418 const char *buf = v_buf;
1421 r = write (fd, buf, len);
1433 /* Resolve the special "win:..." form for Windows-specific paths.
1434 * This always returns a newly allocated string which is freed by the
1435 * caller function in "cmds.c".
1438 resolve_win_path (const char *path)
1443 if (STRCASENEQLEN (path, "win:", 4)) {
1444 ret = strdup (path);
1452 /* Drop drive letter, if it's "C:". */
1453 if (STRCASEEQLEN (path, "c:", 2))
1463 ret = strdup (path);
1469 /* Blindly convert any backslashes into forward slashes. Is this good? */
1470 for (i = 0; i < strlen (ret); ++i)
1474 char *t = guestfs_case_sensitive_path (g, ret);
1481 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1482 * The caller (cmds.c) will call free_file_in after the command has
1483 * run which should clean up resources.
1485 static char *file_in_heredoc (const char *endmarker);
1486 static char *file_in_tmpfile = NULL;
1489 file_in (const char *arg)
1493 if (STREQ (arg, "-")) {
1494 ret = strdup ("/dev/stdin");
1500 else if (STRPREFIX (arg, "-<<")) {
1501 const char *endmarker = &arg[3];
1502 if (*endmarker == '\0') {
1503 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1507 ret = file_in_heredoc (endmarker);
1523 file_in_heredoc (const char *endmarker)
1525 static const char template[] = "/tmp/heredocXXXXXX";
1526 file_in_tmpfile = strdup (template);
1527 if (file_in_tmpfile == NULL) {
1532 int fd = mkstemp (file_in_tmpfile);
1538 size_t markerlen = strlen (endmarker);
1540 char buffer[BUFSIZ];
1541 int write_error = 0;
1542 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1543 /* Look for "END"<EOF> or "END\n" in input. */
1544 size_t blen = strlen (buffer);
1545 if (STREQLEN (buffer, endmarker, markerlen) &&
1546 (blen == markerlen ||
1547 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1550 if (xwrite (fd, buffer, blen) == -1) {
1551 if (!write_error) perror ("write");
1553 /* continue reading up to the end marker */
1557 /* Reached EOF of stdin without finding the end marker, which
1558 * is likely to be an error.
1560 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1561 program_name, endmarker);
1570 if (close (fd) == -1) {
1575 return file_in_tmpfile;
1578 unlink (file_in_tmpfile);
1581 free (file_in_tmpfile);
1582 file_in_tmpfile = NULL;
1587 free_file_in (char *s)
1589 if (file_in_tmpfile) {
1590 if (unlink (file_in_tmpfile) == -1)
1591 perror (file_in_tmpfile);
1592 file_in_tmpfile = NULL;
1595 /* Free the device or file name which was strdup'd in file_in().
1596 * Note it's not immediately clear, but for -<< heredocs,
1597 * s == file_in_tmpfile, so this frees up that buffer.
1602 /* Resolve the special FileOut paths ("-" or filename).
1603 * The caller (cmds.c) will call free (str) after the command has run.
1606 file_out (const char *arg)
1610 if (STREQ (arg, "-"))
1611 ret = strdup ("/dev/stdout");
1622 /* Read a passphrase ('Key') from /dev/tty with echo off.
1623 * The caller (cmds.c) will call free on the string afterwards.
1624 * Based on the code in cryptsetup file lib/utils.c.
1627 read_key (const char *param)
1630 struct termios orig, temp;
1633 /* Read and write to /dev/tty if available. */
1634 if (keys_from_stdin ||
1635 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1640 /* Print the prompt and set no echo. */
1641 int tty = isatty (fileno (infp));
1644 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1647 if (tcgetattr (fileno (infp), &orig) == -1) {
1648 perror ("tcgetattr");
1651 memcpy (&temp, &orig, sizeof temp);
1652 temp.c_lflag &= ~ECHO;
1654 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1661 len = getline (&ret, &n, infp);
1668 /* Remove the terminating \n if there is one. */
1669 if (len > 0 && ret[len-1] == '\n')
1673 /* Restore echo, close file descriptor. */
1676 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1680 fclose (infp); /* outfp == infp, so this is closed also */