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 void free_drives (struct drv *drv);
77 static void free_mps (struct mp *mp);
78 static int launch (void);
79 static void interactive (void);
80 static void shell_script (void);
81 static void script (int prompt);
82 static void cmdline (char *argv[], int optind, int argc);
83 static void initialize_readline (void);
84 static void cleanup_readline (void);
85 #ifdef HAVE_LIBREADLINE
86 static void add_history_line (const char *);
89 static int override_progress_bars = -1;
91 /* Currently open libguestfs handle. */
97 int remote_control_listen = 0;
98 int remote_control = 0;
99 int exit_on_error = 1;
101 int keys_from_stdin = 0;
103 const char *libvirt_uri = NULL;
106 int have_terminfo = 0;
107 int progress_bars = 0;
109 static void __attribute__((noreturn))
112 if (status != EXIT_SUCCESS)
113 fprintf (stderr, _("Try `%s --help' for more information.\n"),
117 _("%s: guest filesystem shell\n"
118 "%s lets you edit virtual machine filesystems\n"
119 "Copyright (C) 2009-2010 Red Hat Inc.\n"
121 " %s [--options] cmd [: cmd : cmd ...]\n"
122 " %s [--ro] -i -a disk-image\n"
123 " %s [--ro] -i -d libvirt-domain\n"
124 "or for interactive use:\n"
126 "or from a shell script:\n"
132 " -h|--cmd-help List available commands\n"
133 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
134 " -a|--add image Add image\n"
135 " -c|--connect uri Specify libvirt URI for -d option\n"
136 " -d|--domain guest Add disks from libvirt guest\n"
137 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
138 " --echo-keys Don't turn off echo for passphrases\n"
139 " -f|--file file Read commands from file\n"
140 " -i|--inspector Automatically mount filesystems\n"
141 " --keys-from-stdin Read passphrases from stdin\n"
142 " --listen Listen for remote commands\n"
143 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
144 " -n|--no-sync Don't autosync\n"
145 " -N|--new type Create prepared disk (test1.img, ...)\n"
146 " --progress-bars Enable progress bars even when not interactive\n"
147 " --no-progress-bars Disable progress bars\n"
148 " --remote[=pid] Send commands to remote %s\n"
149 " -r|--ro Mount read-only\n"
150 " --selinux Enable SELinux support\n"
151 " -v|--verbose Verbose messages\n"
152 " -x Echo each command before executing it\n"
153 " -V|--version Display version and exit\n"
154 "For more information, see the manpage %s(1).\n"),
155 program_name, program_name, program_name,
156 program_name, program_name, program_name,
157 program_name, program_name, program_name);
163 main (int argc, char *argv[])
165 /* Set global program name that is not polluted with libtool artifacts. */
166 set_program_name (argv[0]);
168 atexit (close_stdout);
170 setlocale (LC_ALL, "");
171 bindtextdomain (PACKAGE, LOCALEBASEDIR);
172 textdomain (PACKAGE);
176 enum { HELP_OPTION = CHAR_MAX + 1 };
178 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
179 static const struct option long_options[] = {
180 { "add", 1, 0, 'a' },
181 { "cmd-help", 2, 0, 'h' },
182 { "connect", 1, 0, 'c' },
183 { "domain", 1, 0, 'd' },
184 { "echo-keys", 0, 0, 0 },
185 { "file", 1, 0, 'f' },
186 { "help", 0, 0, HELP_OPTION },
187 { "inspector", 0, 0, 'i' },
188 { "keys-from-stdin", 0, 0, 0 },
189 { "listen", 0, 0, 0 },
190 { "mount", 1, 0, 'm' },
191 { "new", 1, 0, 'N' },
192 { "no-dest-paths", 0, 0, 'D' },
193 { "no-sync", 0, 0, 'n' },
194 { "progress-bars", 0, 0, 0 },
195 { "no-progress-bars", 0, 0, 0 },
196 { "remote", 2, 0, 0 },
198 { "selinux", 0, 0, 0 },
199 { "verbose", 0, 0, 'v' },
200 { "version", 0, 0, 'V' },
203 struct drv *drvs = NULL;
205 struct mp *mps = NULL;
207 char *p, *file = NULL;
211 int next_prepared_drive = 1;
213 initialize_readline ();
215 memset (&sa, 0, sizeof sa);
216 sa.sa_handler = SIG_IGN;
217 sa.sa_flags = SA_RESTART;
218 sigaction (SIGPIPE, &sa, NULL);
220 /* guestfs_create is meant to be a lightweight operation, so
221 * it's OK to do it early here.
223 g = guestfs_create ();
225 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
229 guestfs_set_autosync (g, 1);
231 /* If developing, add ./appliance to the path. Note that libtools
232 * interferes with this because uninstalled guestfish is a shell
233 * script that runs the real program with an absolute path. Detect
236 * BUT if LIBGUESTFS_PATH environment variable is already set by
237 * the user, then don't override it.
239 if (getenv ("LIBGUESTFS_PATH") == NULL &&
241 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
242 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
244 /* CAUTION: we are careful to modify argv[0] here, only after
245 * using it just above.
247 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
248 * of the original, in case it's needed below.
250 char *real_argv0 = argv[0];
251 argv[0] = bad_cast (program_name);
254 c = getopt_long (argc, argv, options, long_options, &option_index);
258 case 0: /* options which are long only */
259 if (STREQ (long_options[option_index].name, "listen"))
260 remote_control_listen = 1;
261 else if (STREQ (long_options[option_index].name, "remote")) {
263 if (sscanf (optarg, "%d", &remote_control) != 1) {
264 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
265 program_name, optarg);
269 p = getenv ("GUESTFISH_PID");
270 if (!p || sscanf (p, "%d", &remote_control) != 1) {
271 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
272 " to the PID of the remote process\n"),
277 } else if (STREQ (long_options[option_index].name, "selinux")) {
278 guestfs_set_selinux (g, 1);
279 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
281 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
282 override_progress_bars = 1;
283 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
284 override_progress_bars = 0;
285 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
288 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
289 program_name, long_options[option_index].name, option_index);
295 if (access (optarg, R_OK) != 0) {
299 drv = malloc (sizeof (struct drv));
305 drv->a.filename = optarg;
311 libvirt_uri = optarg;
315 drv = malloc (sizeof (struct drv));
321 drv->d.guest = optarg;
327 if (STRCASEEQ (optarg, "list") ||
328 STRCASEEQ (optarg, "help") ||
329 STRCASEEQ (optarg, "h") ||
330 STRCASEEQ (optarg, "?")) {
331 list_prepared_drives ();
334 drv = malloc (sizeof (struct drv));
340 if (asprintf (&drv->N.filename, "test%d.img",
341 next_prepared_drive++) == -1) {
345 drv->N.data = create_prepared_file (optarg, drv->N.filename);
346 drv->N.device = NULL; /* filled in by add_drives */
352 complete_dest_paths = 0;
357 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
368 r = display_command (optarg);
369 else if (argv[optind] && argv[optind][0] != '-')
370 r = display_command (argv[optind++]);
374 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
382 mp = malloc (sizeof (struct mp));
387 p = strchr (optarg, ':');
390 mp->mountpoint = p+1;
392 mp->mountpoint = bad_cast ("/");
399 guestfs_set_autosync (g, 0);
408 guestfs_set_verbose (g, verbose);
412 struct guestfs_version *v = guestfs_version (g);
413 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
414 v->major, v->minor, v->release, v->extra);
419 guestfs_set_trace (g, 1);
423 usage (EXIT_SUCCESS);
426 usage (EXIT_FAILURE);
430 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
431 * previously, if we have -i without any drives but with something
432 * on the command line, it must be old-style syntax.
434 if (inspector && drvs == NULL && optind < argc) {
435 while (optind < argc) {
436 if (strchr (argv[optind], '/') ||
437 access (argv[optind], F_OK) == 0) { /* simulate -a option */
438 drv = malloc (sizeof (struct drv));
444 drv->a.filename = argv[optind];
447 } else { /* simulate -d option */
448 drv = malloc (sizeof (struct drv));
454 drv->d.guest = argv[optind];
463 /* If we've got drives to add, add them now. */
464 add_drives (drvs, 'a');
466 /* If we've got mountpoints or prepared drives or -i option, we must
467 * launch the guest and mount them.
469 if (next_prepared_drive > 1 || mps != NULL || inspector) {
470 /* RHBZ#612178: If --listen flag is given, then we will fork into
471 * the background in rc_listen(). However you can't do this while
472 * holding a libguestfs handle open because the recovery process
473 * will think the main program has died and kill qemu. Therefore
474 * don't use the recovery process for this case. (A better
475 * solution would be to call launch () etc after the fork, but
476 * that greatly complicates the code here).
478 if (remote_control_listen)
479 guestfs_set_recovery_proc (g, 0);
481 if (launch () == -1) exit (EXIT_FAILURE);
486 prepare_drives (drvs);
490 /* Free up data structures, no longer needed after this point. */
494 /* Remote control? */
495 if (remote_control_listen && remote_control) {
497 _("%s: cannot use --listen and --remote options at the same time\n"),
502 if (remote_control_listen) {
505 _("%s: extra parameters on the command line with --listen flag\n"),
511 _("%s: cannot use --listen and --file options at the same time\n"),
518 /* -f (file) parameter? */
521 if (open (file, O_RDONLY) == -1) {
527 /* Decide if we display progress bars. */
529 override_progress_bars >= 0
530 ? override_progress_bars
531 : (optind >= argc && isatty (0));
534 guestfs_set_progress_callback (g, progress_callback, NULL);
536 /* Interactive, shell script, or command(s) on the command line? */
537 if (optind >= argc) {
544 cmdline (argv, optind, argc);
551 /* The <term.h> header file which defines this has "issues". */
552 extern int tgetent (char *, const char *);
555 set_up_terminal (void)
557 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
558 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
560 char *term = getenv ("TERM");
562 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
566 int r = tgetent (NULL, term);
568 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
572 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
581 pod2text (const char *name, const char *shortdesc, const char *str)
585 fp = popen ("pod2text", "w");
587 /* pod2text failed, maybe not found, so let's just print the
588 * source instead, since that's better than doing nothing.
590 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
593 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
598 /* List is built in reverse order, so mount them in reverse order. */
600 mount_mps (struct mp *mp)
605 mount_mps (mp->next);
607 /* Don't use guestfs_mount here because that will default to mount
608 * options -o sync,noatime. For more information, see guestfs(3)
609 * section "LIBGUESTFS GOTCHAS".
611 const char *options = read_only ? "ro" : "";
612 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
614 /* Display possible mountpoints before exiting. */
615 char **fses = guestfs_list_filesystems (g);
616 if (fses == NULL || fses[0] == NULL)
619 _("guestfish: '%s' could not be mounted. Did you mean one of these?\n"),
622 for (i = 0; fses[i] != NULL; i += 2)
623 fprintf (stderr, "\t%s (%s)\n", fses[i], fses[i+1]);
632 add_drives (struct drv *drv, char next_drive)
636 if (next_drive > 'z') {
638 _("guestfish: too many drives added on the command line\n"));
643 next_drive = add_drives (drv->next, next_drive);
648 r = guestfs_add_drive (g, drv->a.filename);
650 r = guestfs_add_drive_ro (g, drv->a.filename);
658 r = add_libvirt_drives (drv->d.guest);
666 /* -N option is not affected by --ro */
667 r = guestfs_add_drive (g, drv->N.filename);
671 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
679 default: /* keep GCC happy */
688 prepare_drives (struct drv *drv)
691 prepare_drives (drv->next);
692 if (drv->type == drv_N)
693 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
698 free_drives (struct drv *drv)
701 free_drives (drv->next);
704 case drv_a: /* a.filename is optarg, don't free it */ break;
705 case drv_d: /* d.filename is optarg, don't free it */ break;
707 free (drv->N.filename);
708 free (drv->N.device);
709 free_prep_data (drv->N.data);
711 default: ; /* keep GCC happy */
717 free_mps (struct mp *mp)
722 /* The drive and mountpoint fields are not allocated
723 * from the heap, so we should not free them here.
732 if (guestfs_is_config (g)) {
733 if (guestfs_launch (g) == -1)
751 #define FISH "><fs> "
753 static char *line_read = NULL;
758 #ifdef HAVE_LIBREADLINE
766 line_read = readline (prompt ? FISH : "");
768 if (line_read && *line_read)
769 add_history_line (line_read);
774 #endif /* HAVE_LIBREADLINE */
776 static char buf[8192];
779 if (prompt) printf (FISH);
780 line_read = fgets (buf, sizeof buf, stdin);
783 len = strlen (line_read);
784 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
798 int global_exit_on_error = !prompt;
803 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
804 "editing virtual machine filesystems.\n"
806 "Type: 'help' for a list of commands\n"
807 " 'man' to read the manual\n"
808 " 'quit' to quit the shell\n"
812 print_inspect_prompt ();
820 exit_on_error = global_exit_on_error;
822 buf = rl_gets (prompt);
828 /* Skip any initial whitespace before the command. */
830 while (*buf && c_isspace (*buf))
835 /* If the next character is '#' then this is a comment. */
836 if (*buf == '#') continue;
838 /* If the next character is '!' then pass the whole lot to system(3). */
846 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
847 WEXITSTATUS (r) != 0)
853 /* If the next character is '-' allow the command to fail without
854 * exiting on error (just for this one command though).
862 /* Get the command (cannot be quoted). */
863 len = strcspn (buf, " \t");
865 if (len == 0) continue;
869 if (buf[len] == '\0') {
876 p += strspn (p, " \t");
878 /* Get the parameters. */
879 while (*p && i < sizeof argv / sizeof argv[0]) {
882 /* Parameters which start with quotes or pipes are treated
883 * specially. Bare parameters are delimited by whitespace.
887 len = strcspn (p, "\"");
888 if (p[len] == '\0') {
889 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
890 if (exit_on_error) exit (EXIT_FAILURE);
893 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
895 _("%s: command arguments not separated by whitespace\n"),
897 if (exit_on_error) exit (EXIT_FAILURE);
901 pend = p[len+1] ? &p[len+2] : &p[len+1];
902 } else if (*p == '\'') {
904 len = strcspn (p, "'");
905 if (p[len] == '\0') {
906 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
907 if (exit_on_error) exit (EXIT_FAILURE);
910 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
912 _("%s: command arguments not separated by whitespace\n"),
914 if (exit_on_error) exit (EXIT_FAILURE);
918 pend = p[len+1] ? &p[len+2] : &p[len+1];
919 } else if (*p == '|') {
924 } else if (*p == '[') {
928 while (*pend && c != 0) {
929 if (*pend == '[') c++;
930 else if (*pend == ']') c--;
935 _("%s: unterminated \"[...]\" sequence\n"), program_name);
936 if (exit_on_error) exit (EXIT_FAILURE);
939 if (*pend && (*pend != ' ' && *pend != '\t')) {
941 _("%s: command arguments not separated by whitespace\n"),
943 if (exit_on_error) exit (EXIT_FAILURE);
948 } else if (*p != ' ' && *p != '\t') {
949 /* If the first character is a ~ then note that this parameter
950 * is a candidate for ~username expansion. NB this does not
951 * apply to quoted parameters.
953 tilde_candidate = *p == '~';
954 len = strcspn (p, " \t");
961 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
966 if (!tilde_candidate)
969 argv[i] = try_tilde_expansion (p);
974 p += strspn (p, " \t");
977 if (i == sizeof argv / sizeof argv[0]) {
978 fprintf (stderr, _("%s: too many arguments\n"), program_name);
979 if (exit_on_error) exit (EXIT_FAILURE);
986 if (issue_command (cmd, argv, pipe) == -1) {
987 if (exit_on_error) exit (EXIT_FAILURE);
992 if (prompt) printf ("\n");
996 cmdline (char *argv[], int optind, int argc)
1003 if (optind >= argc) return;
1005 cmd = argv[optind++];
1006 if (STREQ (cmd, ":")) {
1007 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
1008 exit (EXIT_FAILURE);
1011 /* Allow -cmd on the command line to mean (temporarily) override
1012 * the normal exit on error (RHBZ#578407).
1014 if (cmd[0] == '-') {
1019 params = &argv[optind];
1021 /* Search for end of command list or ":" ... */
1022 while (optind < argc && STRNEQ (argv[optind], ":"))
1025 if (optind == argc) {
1026 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
1027 exit (EXIT_FAILURE);
1029 argv[optind] = NULL;
1030 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
1031 exit (EXIT_FAILURE);
1032 cmdline (argv, optind+1, argc);
1037 issue_command (const char *cmd, char *argv[], const char *pipecmd)
1040 int stdout_saved_fd = -1;
1044 reset_progress_bar ();
1046 /* This counts the commands issued, starting at 1. */
1049 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1053 if (fflush (stdout) == EOF) {
1054 perror ("failed to flush standard output");
1057 if (pipe (fd) < 0) {
1058 perror ("pipe failed");
1067 if (pid == 0) { /* Child process. */
1069 if (dup2 (fd[0], 0) < 0) {
1070 perror ("dup2 of stdin failed");
1074 r = system (pipecmd);
1079 _exit (WEXITSTATUS (r));
1082 if ((stdout_saved_fd = dup (1)) < 0) {
1083 perror ("failed to dup stdout");
1087 if (dup2 (fd[1], 1) < 0) {
1088 perror ("failed to dup stdout");
1089 close (stdout_saved_fd);
1095 for (argc = 0; argv[argc] != NULL; ++argc)
1098 /* If --remote was set, then send this command to a remote process. */
1100 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1102 /* Otherwise execute it locally. */
1103 else if (STRCASEEQ (cmd, "help")) {
1108 r = display_command (argv[0]);
1110 else if (STRCASEEQ (cmd, "quit") ||
1111 STRCASEEQ (cmd, "exit") ||
1112 STRCASEEQ (cmd, "q")) {
1117 r = run_action (cmd, argc, argv);
1119 /* Always flush stdout after every command, so that messages, results
1120 * etc appear immediately.
1122 if (fflush (stdout) == EOF) {
1123 perror ("failed to flush standard output");
1129 if (dup2 (stdout_saved_fd, 1) < 0) {
1130 perror ("failed to dup2 standard output");
1133 close (stdout_saved_fd);
1134 if (waitpid (pid, NULL, 0) < 0) {
1135 perror ("waiting for command to complete");
1144 list_builtin_commands (void)
1146 /* help and quit should appear at the top */
1147 printf ("%-20s %s\n",
1148 "help", _("display a list of commands or help on a command"));
1149 printf ("%-20s %s\n",
1150 "quit", _("quit guestfish"));
1152 /* actions are printed after this (see list_commands) */
1156 display_builtin_command (const char *cmd)
1158 /* help for actions is auto-generated, see display_command */
1160 if (STRCASEEQ (cmd, "help")) {
1161 printf (_("help - display a list of commands or help on a command\n"
1166 else if (STRCASEEQ (cmd, "quit") ||
1167 STRCASEEQ (cmd, "exit") ||
1168 STRCASEEQ (cmd, "q")) {
1169 printf (_("quit - quit guestfish\n"
1174 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1180 /* This is printed when the user types in an unknown command for the
1181 * first command issued. A common case is the user doing:
1182 * guestfish disk.img
1183 * expecting guestfish to open 'disk.img' (in fact, this tried to
1184 * run a command 'disk.img').
1187 extended_help_message (void)
1190 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1191 "For a list of commands: guestfish -h\n"
1192 "For complete documentation: man guestfish\n"));
1196 free_strings (char **argv)
1200 for (argc = 0; argv[argc] != NULL; ++argc)
1206 count_strings (char *const *argv)
1210 for (c = 0; argv[c]; ++c)
1216 print_strings (char *const *argv)
1220 for (argc = 0; argv[argc] != NULL; ++argc)
1221 printf ("%s\n", argv[argc]);
1225 print_table (char *const *argv)
1229 for (i = 0; argv[i] != NULL; i += 2)
1230 printf ("%s: %s\n", argv[i], argv[i+1]);
1234 is_true (const char *str)
1237 STRCASENEQ (str, "0") &&
1238 STRCASENEQ (str, "f") &&
1239 STRCASENEQ (str, "false") &&
1240 STRCASENEQ (str, "n") &&
1241 STRCASENEQ (str, "no");
1244 /* Free strings from a non-NULL terminated char** */
1246 free_n_strings (char **str, size_t len)
1250 for (i = 0; i < len; i++) {
1257 parse_string_list (const char *str)
1260 size_t argv_len = 0;
1262 /* Current position pointer */
1263 const char *p = str;
1265 /* Token might be simple:
1268 * 'This is a single token'
1269 * or contain embedded single-quoted sections:
1270 * This' is a sing'l'e to'ken
1272 * The latter may seem over-complicated, but it's what a normal shell does.
1273 * Not doing it risks surprising somebody.
1275 * This outer loop is over complete tokens.
1281 /* Skip leading whitespace */
1282 p += strspn (p, " \t");
1286 /* This loop is over token 'fragments'. A token can be in multiple bits if
1287 * it contains single quotes. We also treat both sides of an escaped quote
1288 * as separate fragments because we can't just copy it: we have to remove
1291 while (*p && (!c_isblank (*p) || in_quote)) {
1292 const char *end = p;
1294 /* Check if the fragment starts with a quote */
1296 /* Toggle in_quote */
1297 in_quote = !in_quote;
1299 /* Skip the quote */
1303 /* If we're in a quote, look for an end quote */
1305 end += strcspn (end, "'");
1308 /* Otherwise, look for whitespace or a quote */
1310 end += strcspn (end, " \t'");
1313 /* Grow the token to accommodate the fragment */
1314 size_t tok_end = tok_len;
1316 char *tok_new = realloc (tok, tok_len + 1);
1317 if (NULL == tok_new) {
1319 free_n_strings (argv, argv_len);
1321 exit (EXIT_FAILURE);
1325 /* Check if we stopped on an escaped quote */
1326 if ('\'' == *end && end != p && *(end-1) == '\\') {
1327 /* Add everything before \' to the token */
1328 memcpy (&tok[tok_end], p, end - p - 1);
1331 tok[tok_len-1] = '\'';
1333 /* Already processed the quote */
1338 /* Add the whole fragment */
1339 memcpy (&tok[tok_end], p, end - p);
1345 /* We've reached the end of a token. We shouldn't still be in quotes. */
1347 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1349 free_n_strings (argv, argv_len);
1354 /* Add this token if there is one. There might not be if there was
1355 * whitespace at the end of the input string */
1357 /* Add the NULL terminator */
1358 tok[tok_len] = '\0';
1360 /* Add the argument to the argument list */
1362 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1363 if (NULL == argv_new) {
1365 free_n_strings (argv, argv_len-1);
1367 exit (EXIT_FAILURE);
1371 argv[argv_len-1] = tok;
1375 /* NULL terminate the argument list */
1377 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1378 if (NULL == argv_new) {
1380 free_n_strings (argv, argv_len-1);
1381 exit (EXIT_FAILURE);
1385 argv[argv_len-1] = NULL;
1390 #ifdef HAVE_LIBREADLINE
1391 static char histfile[1024];
1392 static int nr_history_lines = 0;
1396 initialize_readline (void)
1398 #ifdef HAVE_LIBREADLINE
1401 home = getenv ("HOME");
1403 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1405 (void) read_history (histfile);
1408 rl_readline_name = "guestfish";
1409 rl_attempted_completion_function = do_completion;
1411 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1412 * call the readline(), which happens later. Therefore, these
1413 * provide default values which can be overridden by the user if
1416 (void) rl_variable_bind ("completion-ignore-case", "on");
1421 cleanup_readline (void)
1423 #ifdef HAVE_LIBREADLINE
1426 if (histfile[0] != '\0') {
1427 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1434 #ifdef HAVE_APPEND_HISTORY
1435 (void) append_history (nr_history_lines, histfile);
1437 (void) write_history (histfile);
1444 #ifdef HAVE_LIBREADLINE
1446 add_history_line (const char *line)
1454 xwrite (int fd, const void *v_buf, size_t len)
1457 const char *buf = v_buf;
1460 r = write (fd, buf, len);
1472 /* Resolve the special "win:..." form for Windows-specific paths.
1473 * This always returns a newly allocated string which is freed by the
1474 * caller function in "cmds.c".
1477 resolve_win_path (const char *path)
1482 if (STRCASENEQLEN (path, "win:", 4)) {
1483 ret = strdup (path);
1491 /* Drop drive letter, if it's "C:". */
1492 if (STRCASEEQLEN (path, "c:", 2))
1502 ret = strdup (path);
1508 /* Blindly convert any backslashes into forward slashes. Is this good? */
1509 for (i = 0; i < strlen (ret); ++i)
1513 char *t = guestfs_case_sensitive_path (g, ret);
1520 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1521 * The caller (cmds.c) will call free_file_in after the command has
1522 * run which should clean up resources.
1524 static char *file_in_heredoc (const char *endmarker);
1525 static char *file_in_tmpfile = NULL;
1528 file_in (const char *arg)
1532 if (STREQ (arg, "-")) {
1533 ret = strdup ("/dev/stdin");
1539 else if (STRPREFIX (arg, "-<<")) {
1540 const char *endmarker = &arg[3];
1541 if (*endmarker == '\0') {
1542 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1546 ret = file_in_heredoc (endmarker);
1562 file_in_heredoc (const char *endmarker)
1564 TMP_TEMPLATE_ON_STACK (template);
1565 file_in_tmpfile = strdup (template);
1566 if (file_in_tmpfile == NULL) {
1571 int fd = mkstemp (file_in_tmpfile);
1577 size_t markerlen = strlen (endmarker);
1579 char buffer[BUFSIZ];
1580 int write_error = 0;
1581 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1582 /* Look for "END"<EOF> or "END\n" in input. */
1583 size_t blen = strlen (buffer);
1584 if (STREQLEN (buffer, endmarker, markerlen) &&
1585 (blen == markerlen ||
1586 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1589 if (xwrite (fd, buffer, blen) == -1) {
1590 if (!write_error) perror ("write");
1592 /* continue reading up to the end marker */
1596 /* Reached EOF of stdin without finding the end marker, which
1597 * is likely to be an error.
1599 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1600 program_name, endmarker);
1609 if (close (fd) == -1) {
1614 return file_in_tmpfile;
1617 unlink (file_in_tmpfile);
1620 free (file_in_tmpfile);
1621 file_in_tmpfile = NULL;
1626 free_file_in (char *s)
1628 if (file_in_tmpfile) {
1629 if (unlink (file_in_tmpfile) == -1)
1630 perror (file_in_tmpfile);
1631 file_in_tmpfile = NULL;
1634 /* Free the device or file name which was strdup'd in file_in().
1635 * Note it's not immediately clear, but for -<< heredocs,
1636 * s == file_in_tmpfile, so this frees up that buffer.
1641 /* Resolve the special FileOut paths ("-" or filename).
1642 * The caller (cmds.c) will call free (str) after the command has run.
1645 file_out (const char *arg)
1649 if (STREQ (arg, "-"))
1650 ret = strdup ("/dev/stdout");
1661 /* Read a passphrase ('Key') from /dev/tty with echo off.
1662 * The caller (cmds.c) will call free on the string afterwards.
1663 * Based on the code in cryptsetup file lib/utils.c.
1666 read_key (const char *param)
1669 struct termios orig, temp;
1672 /* Read and write to /dev/tty if available. */
1673 if (keys_from_stdin ||
1674 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1679 /* Print the prompt and set no echo. */
1680 int tty = isatty (fileno (infp));
1683 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1686 if (tcgetattr (fileno (infp), &orig) == -1) {
1687 perror ("tcgetattr");
1690 memcpy (&temp, &orig, sizeof temp);
1691 temp.c_lflag &= ~ECHO;
1693 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1700 len = getline (&ret, &n, infp);
1707 /* Remove the terminating \n if there is one. */
1708 if (len > 0 && ret[len-1] == '\n')
1712 /* Restore echo, close file descriptor. */
1715 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1719 fclose (infp); /* outfp == infp, so this is closed also */