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 char *filename; /* disk filename (for -a or -N options) */
49 prep_data *data; /* prepared type (for -N option only) */
50 char *device; /* device inside the appliance */
59 static void add_drives (struct drv *drv);
60 static void prepare_drives (struct drv *drv);
61 static void mount_mps (struct mp *mp);
62 static int launch (void);
63 static void interactive (void);
64 static void shell_script (void);
65 static void script (int prompt);
66 static void cmdline (char *argv[], int optind, int argc);
67 static void initialize_readline (void);
68 static void cleanup_readline (void);
69 #ifdef HAVE_LIBREADLINE
70 static void add_history_line (const char *);
72 static void print_shell_quote (FILE *stream, const char *str);
74 /* Currently open libguestfs handle. */
80 int remote_control_listen = 0;
81 int remote_control = 0;
82 int exit_on_error = 1;
84 int keys_from_stdin = 0;
86 static void __attribute__((noreturn))
89 if (status != EXIT_SUCCESS)
90 fprintf (stderr, _("Try `%s --help' for more information.\n"),
94 _("%s: guest filesystem shell\n"
95 "%s lets you edit virtual machine filesystems\n"
96 "Copyright (C) 2009 Red Hat Inc.\n"
98 " %s [--options] cmd [: cmd : cmd ...]\n"
99 " %s -i libvirt-domain\n"
100 " %s -i disk-image(s)\n"
101 "or for interactive use:\n"
103 "or from a shell script:\n"
109 " -h|--cmd-help List available commands\n"
110 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
111 " -a|--add image Add image\n"
112 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
113 " -f|--file file Read commands from file\n"
114 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
115 " --keys-from-stdin Read passphrases from stdin\n"
116 " --listen Listen for remote commands\n"
117 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
118 " -n|--no-sync Don't autosync\n"
119 " -N|--new type Create prepared disk (test1.img, ...)\n"
120 " --remote[=pid] Send commands to remote %s\n"
121 " -r|--ro Mount read-only\n"
122 " --selinux Enable SELinux support\n"
123 " -v|--verbose Verbose messages\n"
124 " -x Echo each command before executing it\n"
125 " -V|--version Display version and exit\n"
126 "For more information, see the manpage %s(1).\n"),
127 program_name, program_name, program_name,
128 program_name, program_name, program_name,
129 program_name, program_name, program_name);
135 main (int argc, char *argv[])
137 /* Set global program name that is not polluted with libtool artifacts. */
138 set_program_name (argv[0]);
140 atexit (close_stdout);
142 setlocale (LC_ALL, "");
143 bindtextdomain (PACKAGE, LOCALEBASEDIR);
144 textdomain (PACKAGE);
146 enum { HELP_OPTION = CHAR_MAX + 1 };
148 static const char *options = "a:Df:h::im:nN:rv?Vx";
149 static const struct option long_options[] = {
150 { "add", 1, 0, 'a' },
151 { "cmd-help", 2, 0, 'h' },
152 { "file", 1, 0, 'f' },
153 { "help", 0, 0, HELP_OPTION },
154 { "inspector", 0, 0, 'i' },
155 { "keys-from-stdin", 0, 0, 0 },
156 { "listen", 0, 0, 0 },
157 { "mount", 1, 0, 'm' },
158 { "new", 1, 0, 'N' },
159 { "no-dest-paths", 0, 0, 'D' },
160 { "no-sync", 0, 0, 'n' },
161 { "remote", 2, 0, 0 },
163 { "selinux", 0, 0, 0 },
164 { "verbose", 0, 0, 'v' },
165 { "version", 0, 0, 'V' },
168 struct drv *drvs = NULL;
170 struct mp *mps = NULL;
172 char *p, *file = NULL;
177 char next_drive = 'a';
178 int next_prepared_drive = 1;
180 initialize_readline ();
182 memset (&sa, 0, sizeof sa);
183 sa.sa_handler = SIG_IGN;
184 sa.sa_flags = SA_RESTART;
185 sigaction (SIGPIPE, &sa, NULL);
187 /* guestfs_create is meant to be a lightweight operation, so
188 * it's OK to do it early here.
190 g = guestfs_create ();
192 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
196 guestfs_set_autosync (g, 1);
198 /* If developing, add ./appliance to the path. Note that libtools
199 * interferes with this because uninstalled guestfish is a shell
200 * script that runs the real program with an absolute path. Detect
203 * BUT if LIBGUESTFS_PATH environment variable is already set by
204 * the user, then don't override it.
206 if (getenv ("LIBGUESTFS_PATH") == NULL &&
208 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
209 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
211 /* CAUTION: we are careful to modify argv[0] here, only after
212 * using it just above.
214 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
215 * of the original, in case it's needed in virt-inspector mode, below.
217 char *real_argv0 = argv[0];
218 argv[0] = bad_cast (program_name);
221 c = getopt_long (argc, argv, options, long_options, &option_index);
225 case 0: /* options which are long only */
226 if (STREQ (long_options[option_index].name, "listen"))
227 remote_control_listen = 1;
228 else if (STREQ (long_options[option_index].name, "remote")) {
230 if (sscanf (optarg, "%d", &remote_control) != 1) {
231 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
232 program_name, optarg);
236 p = getenv ("GUESTFISH_PID");
237 if (!p || sscanf (p, "%d", &remote_control) != 1) {
238 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
239 " to the PID of the remote process\n"),
244 } else if (STREQ (long_options[option_index].name, "selinux")) {
245 guestfs_set_selinux (g, 1);
246 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
249 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
250 program_name, long_options[option_index].name, option_index);
256 if (access (optarg, R_OK) != 0) {
260 drv = malloc (sizeof (struct drv));
265 drv->filename = optarg;
267 /* We could fill the device field in, but in fact we
268 * only use it for the -N option at present.
277 if (STRCASEEQ (optarg, "list")) {
278 list_prepared_drives ();
281 drv = malloc (sizeof (struct drv));
286 if (asprintf (&drv->filename, "test%d.img",
287 next_prepared_drive++) == -1) {
291 drv->data = create_prepared_file (optarg, drv->filename);
292 if (asprintf (&drv->device, "/dev/sd%c", next_drive++) == -1) {
301 complete_dest_paths = 0;
306 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
317 r = display_command (optarg);
318 else if (argv[optind] && argv[optind][0] != '-')
319 r = display_command (argv[optind++]);
323 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
331 mp = malloc (sizeof (struct mp));
336 p = strchr (optarg, ':');
339 mp->mountpoint = p+1;
341 mp->mountpoint = bad_cast ("/");
348 guestfs_set_autosync (g, 0);
357 guestfs_set_verbose (g, verbose);
361 printf ("%s %s\n", program_name, PACKAGE_VERSION);
365 guestfs_set_trace (g, 1);
369 usage (EXIT_SUCCESS);
372 usage (EXIT_FAILURE);
376 /* Inspector mode invalidates most of the other arguments. */
378 if (drvs || mps || remote_control_listen || remote_control ||
379 guestfs_get_selinux (g)) {
380 fprintf (stderr, _("%s: cannot use -i option with -a, -m, -N, "
381 "--listen, --remote or --selinux\n"),
385 if (optind >= argc) {
387 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
394 FILE *fp = open_memstream (&cmd, &cmdlen);
396 perror ("open_memstream");
400 fprintf (fp, "virt-inspector");
401 while (optind < argc) {
403 print_shell_quote (fp, argv[optind]);
408 fprintf (fp, " --ro-fish");
410 fprintf (fp, " --fish");
412 if (fclose (fp) == -1) {
419 "%s -i: running: %s\n", program_name, cmd);
421 FILE *pp = popen (cmd, "r");
428 fp = open_memstream (&cmd2, &cmdlen);
430 perror ("open_memstream");
434 fprintf (fp, "%s", real_argv0);
436 if (guestfs_get_verbose (g))
438 if (!guestfs_get_autosync (g))
440 if (guestfs_get_trace (g))
445 if (getline (&insp, &insplen, pp) == -1) {
449 fprintf (fp, " %s", insp);
451 if (pclose (pp) == -1) {
456 if (fclose (fp) == -1) {
463 "%s -i: running: %s\n", program_name, cmd2);
465 int r = system (cmd2);
475 exit (WEXITSTATUS (r));
478 /* If we've got drives to add, add them now. */
481 /* If we've got mountpoints or prepared drives, we must launch the
482 * guest and mount them.
484 if (next_prepared_drive > 1 || mps != NULL) {
485 /* RHBZ#612178: If --listen flag is given, then we will fork into
486 * the background in rc_listen(). However you can't do this while
487 * holding a libguestfs handle open because the recovery process
488 * will think the main program has died and kill qemu. Therefore
489 * don't use the recovery process for this case. (A better
490 * solution would be to call launch () etc after the fork, but
491 * that greatly complicates the code here).
493 if (remote_control_listen)
494 guestfs_set_recovery_proc (g, 0);
496 if (launch () == -1) exit (EXIT_FAILURE);
497 prepare_drives (drvs);
501 /* Remote control? */
502 if (remote_control_listen && remote_control) {
504 _("%s: cannot use --listen and --remote options at the same time\n"),
509 if (remote_control_listen) {
512 _("%s: extra parameters on the command line with --listen flag\n"),
518 _("%s: cannot use --listen and --file options at the same time\n"),
525 /* -f (file) parameter? */
528 if (open (file, O_RDONLY) == -1) {
534 /* Interactive, shell script, or command(s) on the command line? */
535 if (optind >= argc) {
542 cmdline (argv, optind, argc);
550 pod2text (const char *name, const char *shortdesc, const char *str)
554 fp = popen ("pod2text", "w");
556 /* pod2text failed, maybe not found, so let's just print the
557 * source instead, since that's better than doing nothing.
559 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
562 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
567 /* List is built in reverse order, so mount them in reverse order. */
569 mount_mps (struct mp *mp)
574 mount_mps (mp->next);
576 /* Don't use guestfs_mount here because that will default to mount
577 * options -o sync,noatime. For more information, see guestfs(3)
578 * section "LIBGUESTFS GOTCHAS".
580 const char *options = read_only ? "ro" : "";
581 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
588 add_drives (struct drv *drv)
593 add_drives (drv->next);
595 if (drv->data /* -N option is not affected by --ro */ || !read_only)
596 r = guestfs_add_drive (g, drv->filename);
598 r = guestfs_add_drive_ro (g, drv->filename);
605 prepare_drives (struct drv *drv)
608 prepare_drives (drv->next);
610 prepare_drive (drv->filename, drv->data, drv->device);
617 if (guestfs_is_config (g)) {
618 if (guestfs_launch (g) == -1)
636 #define FISH "><fs> "
638 static char *line_read = NULL;
643 #ifdef HAVE_LIBREADLINE
651 line_read = readline (prompt ? FISH : "");
653 if (line_read && *line_read)
654 add_history_line (line_read);
659 #endif /* HAVE_LIBREADLINE */
661 static char buf[8192];
664 if (prompt) printf (FISH);
665 line_read = fgets (buf, sizeof buf, stdin);
668 len = strlen (line_read);
669 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
683 int global_exit_on_error = !prompt;
688 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
689 "editing virtual machine filesystems.\n"
691 "Type: 'help' for a list of commands\n"
692 " 'man' to read the manual\n"
693 " 'quit' to quit the shell\n"
699 exit_on_error = global_exit_on_error;
701 buf = rl_gets (prompt);
707 /* Skip any initial whitespace before the command. */
709 while (*buf && c_isspace (*buf))
714 /* If the next character is '#' then this is a comment. */
715 if (*buf == '#') continue;
717 /* If the next character is '!' then pass the whole lot to system(3). */
725 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
726 WEXITSTATUS (r) != 0)
732 /* If the next character is '-' allow the command to fail without
733 * exiting on error (just for this one command though).
741 /* Get the command (cannot be quoted). */
742 len = strcspn (buf, " \t");
744 if (len == 0) continue;
748 if (buf[len] == '\0') {
755 p += strspn (p, " \t");
757 /* Get the parameters. */
758 while (*p && i < sizeof argv / sizeof argv[0]) {
761 /* Parameters which start with quotes or pipes are treated
762 * specially. Bare parameters are delimited by whitespace.
766 len = strcspn (p, "\"");
767 if (p[len] == '\0') {
768 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
769 if (exit_on_error) exit (EXIT_FAILURE);
772 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
774 _("%s: command arguments not separated by whitespace\n"),
776 if (exit_on_error) exit (EXIT_FAILURE);
780 pend = p[len+1] ? &p[len+2] : &p[len+1];
781 } else if (*p == '\'') {
783 len = strcspn (p, "'");
784 if (p[len] == '\0') {
785 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
786 if (exit_on_error) exit (EXIT_FAILURE);
789 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
791 _("%s: command arguments not separated by whitespace\n"),
793 if (exit_on_error) exit (EXIT_FAILURE);
797 pend = p[len+1] ? &p[len+2] : &p[len+1];
798 } else if (*p == '|') {
803 } else if (*p == '[') {
807 while (*pend && c != 0) {
808 if (*pend == '[') c++;
809 else if (*pend == ']') c--;
814 _("%s: unterminated \"[...]\" sequence\n"), program_name);
815 if (exit_on_error) exit (EXIT_FAILURE);
818 if (*pend && (*pend != ' ' && *pend != '\t')) {
820 _("%s: command arguments not separated by whitespace\n"),
822 if (exit_on_error) exit (EXIT_FAILURE);
827 } else if (*p != ' ' && *p != '\t') {
828 /* If the first character is a ~ then note that this parameter
829 * is a candidate for ~username expansion. NB this does not
830 * apply to quoted parameters.
832 tilde_candidate = *p == '~';
833 len = strcspn (p, " \t");
840 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
845 if (!tilde_candidate)
848 argv[i] = try_tilde_expansion (p);
853 p += strspn (p, " \t");
856 if (i == sizeof argv / sizeof argv[0]) {
857 fprintf (stderr, _("%s: too many arguments\n"), program_name);
858 if (exit_on_error) exit (EXIT_FAILURE);
865 if (issue_command (cmd, argv, pipe) == -1) {
866 if (exit_on_error) exit (EXIT_FAILURE);
871 if (prompt) printf ("\n");
875 cmdline (char *argv[], int optind, int argc)
882 if (optind >= argc) return;
884 cmd = argv[optind++];
885 if (STREQ (cmd, ":")) {
886 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
890 /* Allow -cmd on the command line to mean (temporarily) override
891 * the normal exit on error (RHBZ#578407).
898 params = &argv[optind];
900 /* Search for end of command list or ":" ... */
901 while (optind < argc && STRNEQ (argv[optind], ":"))
904 if (optind == argc) {
905 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
909 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
911 cmdline (argv, optind+1, argc);
916 issue_command (const char *cmd, char *argv[], const char *pipecmd)
919 int stdout_saved_fd = -1;
923 /* This counts the commands issued, starting at 1. */
926 /* For | ... commands. Annoyingly we can't use popen(3) here. */
930 if (fflush (stdout) == EOF) {
931 perror ("failed to flush standard output");
935 perror ("pipe failed");
944 if (pid == 0) { /* Child process. */
946 if (dup2 (fd[0], 0) < 0) {
947 perror ("dup2 of stdin failed");
951 r = system (pipecmd);
956 _exit (WEXITSTATUS (r));
959 if ((stdout_saved_fd = dup (1)) < 0) {
960 perror ("failed to dup stdout");
964 if (dup2 (fd[1], 1) < 0) {
965 perror ("failed to dup stdout");
966 close (stdout_saved_fd);
972 for (argc = 0; argv[argc] != NULL; ++argc)
975 /* If --remote was set, then send this command to a remote process. */
977 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
979 /* Otherwise execute it locally. */
980 else if (STRCASEEQ (cmd, "help")) {
985 r = display_command (argv[0]);
987 else if (STRCASEEQ (cmd, "quit") ||
988 STRCASEEQ (cmd, "exit") ||
989 STRCASEEQ (cmd, "q")) {
993 else if (STRCASEEQ (cmd, "alloc") ||
994 STRCASEEQ (cmd, "allocate"))
995 r = do_alloc (cmd, argc, argv);
996 else if (STRCASEEQ (cmd, "echo"))
997 r = do_echo (cmd, argc, argv);
998 else if (STRCASEEQ (cmd, "edit") ||
999 STRCASEEQ (cmd, "vi") ||
1000 STRCASEEQ (cmd, "emacs"))
1001 r = do_edit (cmd, argc, argv);
1002 else if (STRCASEEQ (cmd, "lcd"))
1003 r = do_lcd (cmd, argc, argv);
1004 else if (STRCASEEQ (cmd, "glob"))
1005 r = do_glob (cmd, argc, argv);
1006 else if (STRCASEEQ (cmd, "man") ||
1007 STRCASEEQ (cmd, "manual"))
1008 r = do_man (cmd, argc, argv);
1009 else if (STRCASEEQ (cmd, "more") ||
1010 STRCASEEQ (cmd, "less"))
1011 r = do_more (cmd, argc, argv);
1012 else if (STRCASEEQ (cmd, "reopen"))
1013 r = do_reopen (cmd, argc, argv);
1014 else if (STRCASEEQ (cmd, "sparse"))
1015 r = do_sparse (cmd, argc, argv);
1016 else if (STRCASEEQ (cmd, "supported"))
1017 r = do_supported (cmd, argc, argv);
1018 else if (STRCASEEQ (cmd, "time"))
1019 r = do_time (cmd, argc, argv);
1021 r = run_action (cmd, argc, argv);
1023 /* Always flush stdout after every command, so that messages, results
1024 * etc appear immediately.
1026 if (fflush (stdout) == EOF) {
1027 perror ("failed to flush standard output");
1033 if (dup2 (stdout_saved_fd, 1) < 0) {
1034 perror ("failed to dup2 standard output");
1037 close (stdout_saved_fd);
1038 if (waitpid (pid, NULL, 0) < 0) {
1039 perror ("waiting for command to complete");
1048 list_builtin_commands (void)
1050 /* help, man and quit should appear at the top */
1051 printf ("%-20s %s\n",
1052 "help", _("display a list of commands or help on a command"));
1053 printf ("%-20s %s\n",
1054 "man", _("read the manual"));
1055 printf ("%-20s %s\n",
1056 "quit", _("quit guestfish"));
1058 printf ("%-20s %s\n",
1059 "alloc", _("allocate an image"));
1060 printf ("%-20s %s\n",
1061 "echo", _("display a line of text"));
1062 printf ("%-20s %s\n",
1063 "edit", _("edit a file in the image"));
1064 printf ("%-20s %s\n",
1065 "lcd", _("local change directory"));
1066 printf ("%-20s %s\n",
1067 "glob", _("expand wildcards in command"));
1068 printf ("%-20s %s\n",
1069 "more", _("view a file in the pager"));
1070 printf ("%-20s %s\n",
1071 "reopen", _("close and reopen libguestfs handle"));
1072 printf ("%-20s %s\n",
1073 "sparse", _("allocate a sparse image file"));
1074 printf ("%-20s %s\n",
1075 "supported", _("list supported groups of commands"));
1076 printf ("%-20s %s\n",
1077 "time", _("measure time taken to run command"));
1079 /* actions are printed after this (see list_commands) */
1083 display_builtin_command (const char *cmd)
1085 /* help for actions is auto-generated, see display_command */
1087 if (STRCASEEQ (cmd, "alloc") ||
1088 STRCASEEQ (cmd, "allocate")) {
1089 printf (_("alloc - allocate an image\n"
1090 " alloc <filename> <size>\n"
1092 " This creates an empty (zeroed) file of the given size,\n"
1093 " and then adds so it can be further examined.\n"
1095 " For more advanced image creation, see qemu-img utility.\n"
1097 " Size can be specified using standard suffixes, eg. '1M'.\n"
1101 else if (STRCASEEQ (cmd, "echo")) {
1102 printf (_("echo - display a line of text\n"
1103 " echo [<params> ...]\n"
1105 " This echos the parameters to the terminal.\n"));
1108 else if (STRCASEEQ (cmd, "edit") ||
1109 STRCASEEQ (cmd, "vi") ||
1110 STRCASEEQ (cmd, "emacs")) {
1111 printf (_("edit - edit a file in the image\n"
1112 " edit <filename>\n"
1114 " This is used to edit a file.\n"
1116 " It is the equivalent of (and is implemented by)\n"
1117 " running \"cat\", editing locally, and then \"write\".\n"
1119 " Normally it uses $EDITOR, but if you use the aliases\n"
1120 " \"vi\" or \"emacs\" you will get those editors.\n"
1122 " NOTE: This will not work reliably for large files\n"
1123 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1126 else if (STRCASEEQ (cmd, "lcd")) {
1127 printf (_("lcd - local change directory\n"
1128 " lcd <directory>\n"
1130 " Change guestfish's current directory. This command is\n"
1131 " useful if you want to download files to a particular\n"
1135 else if (STRCASEEQ (cmd, "glob")) {
1136 printf (_("glob - expand wildcards in command\n"
1137 " glob <command> [<args> ...]\n"
1139 " Glob runs <command> with wildcards expanded in any\n"
1140 " command args. Note that the command is run repeatedly\n"
1141 " once for each expanded argument.\n"));
1144 else if (STRCASEEQ (cmd, "man") ||
1145 STRCASEEQ (cmd, "manual")) {
1146 printf (_("man - read the manual\n"
1149 " Opens the manual page for guestfish.\n"));
1152 else if (STRCASEEQ (cmd, "help")) {
1153 printf (_("help - display a list of commands or help on a command\n"
1158 else if (STRCASEEQ (cmd, "more") ||
1159 STRCASEEQ (cmd, "less")) {
1160 printf (_("more - view a file in the pager\n"
1161 " more <filename>\n"
1163 " This is used to view a file in the pager.\n"
1165 " It is the equivalent of (and is implemented by)\n"
1166 " running \"cat\" and using the pager.\n"
1168 " Normally it uses $PAGER, but if you use the alias\n"
1169 " \"less\" then it always uses \"less\".\n"
1171 " NOTE: This will not work reliably for large files\n"
1172 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1175 else if (STRCASEEQ (cmd, "quit") ||
1176 STRCASEEQ (cmd, "exit") ||
1177 STRCASEEQ (cmd, "q")) {
1178 printf (_("quit - quit guestfish\n"
1182 else if (STRCASEEQ (cmd, "reopen")) {
1183 printf (_("reopen - close and reopen the libguestfs handle\n"
1186 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1187 "this normally, because the handle is closed properly when guestfish\n"
1188 "exits. However this is occasionally useful for testing.\n"));
1191 else if (STRCASEEQ (cmd, "sparse")) {
1192 printf (_("sparse - allocate a sparse image file\n"
1193 " sparse <filename> <size>\n"
1195 " This creates an empty sparse file of the given size,\n"
1196 " and then adds so it can be further examined.\n"
1198 " In all respects it works the same as the 'alloc'\n"
1199 " command, except that the image file is allocated\n"
1200 " sparsely, which means that disk blocks are not assigned\n"
1201 " to the file until they are needed. Sparse disk files\n"
1202 " only use space when written to, but they are slower\n"
1203 " and there is a danger you could run out of real disk\n"
1204 " space during a write operation.\n"
1206 " For more advanced image creation, see qemu-img utility.\n"
1208 " Size can be specified using standard suffixes, eg. '1M'.\n"
1212 else if (STRCASEEQ (cmd, "supported")) {
1213 printf (_("supported - list supported groups of commands\n"
1216 " This command returns a list of the optional groups\n"
1217 " known to the daemon, and indicates which ones are\n"
1218 " supported by this build of the libguestfs appliance.\n"
1220 " See also guestfs(3) section AVAILABILITY.\n"
1224 else if (STRCASEEQ (cmd, "time")) {
1225 printf (_("time - measure time taken to run command\n"
1226 " time <command> [<args> ...]\n"
1228 " This runs <command> as usual, and prints the elapsed\n"
1229 " time afterwards.\n"));
1233 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1239 /* This is printed when the user types in an unknown command for the
1240 * first command issued. A common case is the user doing:
1241 * guestfish disk.img
1242 * expecting guestfish to open 'disk.img' (in fact, this tried to
1243 * run a command 'disk.img').
1246 extended_help_message (void)
1249 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1250 "For a list of commands: guestfish -h\n"
1251 "For complete documentation: man guestfish\n"));
1255 free_strings (char **argv)
1259 for (argc = 0; argv[argc] != NULL; ++argc)
1265 count_strings (char *const *argv)
1269 for (c = 0; argv[c]; ++c)
1275 print_strings (char *const *argv)
1279 for (argc = 0; argv[argc] != NULL; ++argc)
1280 printf ("%s\n", argv[argc]);
1284 print_table (char *const *argv)
1288 for (i = 0; argv[i] != NULL; i += 2)
1289 printf ("%s: %s\n", argv[i], argv[i+1]);
1293 is_true (const char *str)
1296 STRCASENEQ (str, "0") &&
1297 STRCASENEQ (str, "f") &&
1298 STRCASENEQ (str, "false") &&
1299 STRCASENEQ (str, "n") &&
1300 STRCASENEQ (str, "no");
1303 /* Free strings from a non-NULL terminated char** */
1305 free_n_strings (char **str, size_t len)
1309 for (i = 0; i < len; i++) {
1316 parse_string_list (const char *str)
1319 size_t argv_len = 0;
1321 /* Current position pointer */
1322 const char *p = str;
1324 /* Token might be simple:
1327 * 'This is a single token'
1328 * or contain embedded single-quoted sections:
1329 * This' is a sing'l'e to'ken
1331 * The latter may seem over-complicated, but it's what a normal shell does.
1332 * Not doing it risks surprising somebody.
1334 * This outer loop is over complete tokens.
1340 /* Skip leading whitespace */
1341 p += strspn (p, " \t");
1345 /* This loop is over token 'fragments'. A token can be in multiple bits if
1346 * it contains single quotes. We also treat both sides of an escaped quote
1347 * as separate fragments because we can't just copy it: we have to remove
1350 while (*p && (!c_isblank (*p) || in_quote)) {
1351 const char *end = p;
1353 /* Check if the fragment starts with a quote */
1355 /* Toggle in_quote */
1356 in_quote = !in_quote;
1358 /* Skip the quote */
1362 /* If we're in a quote, look for an end quote */
1364 end += strcspn (end, "'");
1367 /* Otherwise, look for whitespace or a quote */
1369 end += strcspn (end, " \t'");
1372 /* Grow the token to accommodate the fragment */
1373 size_t tok_end = tok_len;
1375 char *tok_new = realloc (tok, tok_len + 1);
1376 if (NULL == tok_new) {
1378 free_n_strings (argv, argv_len);
1380 exit (EXIT_FAILURE);
1384 /* Check if we stopped on an escaped quote */
1385 if ('\'' == *end && end != p && *(end-1) == '\\') {
1386 /* Add everything before \' to the token */
1387 memcpy (&tok[tok_end], p, end - p - 1);
1390 tok[tok_len-1] = '\'';
1392 /* Already processed the quote */
1397 /* Add the whole fragment */
1398 memcpy (&tok[tok_end], p, end - p);
1404 /* We've reached the end of a token. We shouldn't still be in quotes. */
1406 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1408 free_n_strings (argv, argv_len);
1413 /* Add this token if there is one. There might not be if there was
1414 * whitespace at the end of the input string */
1416 /* Add the NULL terminator */
1417 tok[tok_len] = '\0';
1419 /* Add the argument to the argument list */
1421 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1422 if (NULL == argv_new) {
1424 free_n_strings (argv, argv_len-1);
1426 exit (EXIT_FAILURE);
1430 argv[argv_len-1] = tok;
1434 /* NULL terminate the argument list */
1436 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1437 if (NULL == argv_new) {
1439 free_n_strings (argv, argv_len-1);
1440 exit (EXIT_FAILURE);
1444 argv[argv_len-1] = NULL;
1449 #ifdef HAVE_LIBREADLINE
1450 static char histfile[1024];
1451 static int nr_history_lines = 0;
1455 initialize_readline (void)
1457 #ifdef HAVE_LIBREADLINE
1460 home = getenv ("HOME");
1462 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1464 (void) read_history (histfile);
1467 rl_readline_name = "guestfish";
1468 rl_attempted_completion_function = do_completion;
1470 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1471 * call the readline(), which happens later. Therefore, these
1472 * provide default values which can be overridden by the user if
1475 (void) rl_variable_bind ("completion-ignore-case", "on");
1480 cleanup_readline (void)
1482 #ifdef HAVE_LIBREADLINE
1485 if (histfile[0] != '\0') {
1486 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1493 #ifdef HAVE_APPEND_HISTORY
1494 (void) append_history (nr_history_lines, histfile);
1496 (void) write_history (histfile);
1502 #ifdef HAVE_LIBREADLINE
1504 add_history_line (const char *line)
1512 xwrite (int fd, const void *v_buf, size_t len)
1515 const char *buf = v_buf;
1518 r = write (fd, buf, len);
1530 /* Resolve the special "win:..." form for Windows-specific paths.
1531 * This always returns a newly allocated string which is freed by the
1532 * caller function in "cmds.c".
1535 resolve_win_path (const char *path)
1540 if (STRCASENEQLEN (path, "win:", 4)) {
1541 ret = strdup (path);
1549 /* Drop drive letter, if it's "C:". */
1550 if (STRCASEEQLEN (path, "c:", 2))
1560 ret = strdup (path);
1566 /* Blindly convert any backslashes into forward slashes. Is this good? */
1567 for (i = 0; i < strlen (ret); ++i)
1571 char *t = guestfs_case_sensitive_path (g, ret);
1578 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1579 * The caller (cmds.c) will call free_file_in after the command has
1580 * run which should clean up resources.
1582 static char *file_in_heredoc (const char *endmarker);
1583 static char *file_in_tmpfile = NULL;
1586 file_in (const char *arg)
1590 if (STREQ (arg, "-")) {
1591 ret = strdup ("/dev/stdin");
1597 else if (STRPREFIX (arg, "-<<")) {
1598 const char *endmarker = &arg[3];
1599 if (*endmarker == '\0') {
1600 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1604 ret = file_in_heredoc (endmarker);
1620 file_in_heredoc (const char *endmarker)
1622 static const char template[] = "/tmp/heredocXXXXXX";
1623 file_in_tmpfile = strdup (template);
1624 if (file_in_tmpfile == NULL) {
1629 int fd = mkstemp (file_in_tmpfile);
1635 size_t markerlen = strlen (endmarker);
1637 char buffer[BUFSIZ];
1638 int write_error = 0;
1639 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1640 /* Look for "END"<EOF> or "END\n" in input. */
1641 size_t blen = strlen (buffer);
1642 if (STREQLEN (buffer, endmarker, markerlen) &&
1643 (blen == markerlen ||
1644 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1647 if (xwrite (fd, buffer, blen) == -1) {
1648 if (!write_error) perror ("write");
1650 /* continue reading up to the end marker */
1654 /* Reached EOF of stdin without finding the end marker, which
1655 * is likely to be an error.
1657 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1658 program_name, endmarker);
1667 if (close (fd) == -1) {
1672 return file_in_tmpfile;
1675 unlink (file_in_tmpfile);
1678 free (file_in_tmpfile);
1679 file_in_tmpfile = NULL;
1684 free_file_in (char *s)
1686 if (file_in_tmpfile) {
1687 if (unlink (file_in_tmpfile) == -1)
1688 perror (file_in_tmpfile);
1689 file_in_tmpfile = NULL;
1692 /* Free the device or file name which was strdup'd in file_in().
1693 * Note it's not immediately clear, but for -<< heredocs,
1694 * s == file_in_tmpfile, so this frees up that buffer.
1699 /* Resolve the special FileOut paths ("-" or filename).
1700 * The caller (cmds.c) will call free (str) after the command has run.
1703 file_out (const char *arg)
1707 if (STREQ (arg, "-"))
1708 ret = strdup ("/dev/stdout");
1719 /* Read a passphrase ('Key') from /dev/tty with echo off.
1720 * The caller (cmds.c) will call free on the string afterwards.
1721 * Based on the code in cryptsetup file lib/utils.c.
1724 read_key (const char *param)
1727 struct termios orig, temp;
1730 /* Read and write to /dev/tty if available. */
1731 if (keys_from_stdin ||
1732 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1737 /* Print the prompt and set no echo. */
1738 int tty = isatty (fileno (infp));
1741 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1743 if (tcgetattr (fileno (infp), &orig) == -1) {
1744 perror ("tcgetattr");
1747 memcpy (&temp, &orig, sizeof temp);
1748 temp.c_lflag &= ~ECHO;
1750 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1756 len = getline (&ret, &n, infp);
1763 /* Remove the terminating \n if there is one. */
1764 if (len > 0 && ret[len-1] == '\n')
1768 /* Restore echo, close file descriptor. */
1771 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1775 fclose (infp); /* outfp == infp, so this is closed also */
1781 print_shell_quote (FILE *stream, const char *str)
1783 #define SAFE(c) (c_isalnum((c)) || \
1784 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
1787 for (i = 0; str[i]; ++i) {
1789 putc ('\\', stream);
1790 putc (str[i], stream);