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>
33 #ifdef HAVE_LIBREADLINE
34 #include <readline/readline.h>
35 #include <readline/history.h>
47 char *filename; /* disk filename (for -a or -N options) */
48 prep_data *data; /* prepared type (for -N option only) */
49 char *device; /* device inside the appliance */
58 static void add_drives (struct drv *drv);
59 static void prepare_drives (struct drv *drv);
60 static void mount_mps (struct mp *mp);
61 static int launch (void);
62 static void interactive (void);
63 static void shell_script (void);
64 static void script (int prompt);
65 static void cmdline (char *argv[], int optind, int argc);
66 static void initialize_readline (void);
67 static void cleanup_readline (void);
68 #ifdef HAVE_LIBREADLINE
69 static void add_history_line (const char *);
71 static void print_shell_quote (FILE *stream, const char *str);
73 /* Currently open libguestfs handle. */
79 int remote_control_listen = 0;
80 int remote_control = 0;
81 int exit_on_error = 1;
84 static void __attribute__((noreturn))
87 if (status != EXIT_SUCCESS)
88 fprintf (stderr, _("Try `%s --help' for more information.\n"),
92 _("%s: guest filesystem shell\n"
93 "%s lets you edit virtual machine filesystems\n"
94 "Copyright (C) 2009 Red Hat Inc.\n"
96 " %s [--options] cmd [: cmd : cmd ...]\n"
97 " %s -i libvirt-domain\n"
98 " %s -i disk-image(s)\n"
99 "or for interactive use:\n"
101 "or from a shell script:\n"
107 " -h|--cmd-help List available commands\n"
108 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
109 " -a|--add image Add image\n"
110 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
111 " -f|--file file Read commands from file\n"
112 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
113 " --listen Listen for remote commands\n"
114 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
115 " -n|--no-sync Don't autosync\n"
116 " -N|--new type Create prepared disk (test1.img, ...)\n"
117 " --remote[=pid] Send commands to remote %s\n"
118 " -r|--ro Mount read-only\n"
119 " --selinux Enable SELinux support\n"
120 " -v|--verbose Verbose messages\n"
121 " -x Echo each command before executing it\n"
122 " -V|--version Display version and exit\n"
123 "For more information, see the manpage %s(1).\n"),
124 program_name, program_name, program_name,
125 program_name, program_name, program_name,
126 program_name, program_name, program_name);
132 main (int argc, char *argv[])
134 /* Set global program name that is not polluted with libtool artifacts. */
135 set_program_name (argv[0]);
137 atexit (close_stdout);
139 setlocale (LC_ALL, "");
140 bindtextdomain (PACKAGE, LOCALEBASEDIR);
141 textdomain (PACKAGE);
143 enum { HELP_OPTION = CHAR_MAX + 1 };
145 static const char *options = "a:Df:h::im:nN:rv?Vx";
146 static const struct option long_options[] = {
147 { "add", 1, 0, 'a' },
148 { "cmd-help", 2, 0, 'h' },
149 { "file", 1, 0, 'f' },
150 { "help", 0, 0, HELP_OPTION },
151 { "inspector", 0, 0, 'i' },
152 { "listen", 0, 0, 0 },
153 { "mount", 1, 0, 'm' },
154 { "new", 1, 0, 'N' },
155 { "no-dest-paths", 0, 0, 'D' },
156 { "no-sync", 0, 0, 'n' },
157 { "remote", 2, 0, 0 },
159 { "selinux", 0, 0, 0 },
160 { "verbose", 0, 0, 'v' },
161 { "version", 0, 0, 'V' },
164 struct drv *drvs = NULL;
166 struct mp *mps = NULL;
168 char *p, *file = NULL;
173 char next_drive = 'a';
174 int next_prepared_drive = 1;
176 initialize_readline ();
178 memset (&sa, 0, sizeof sa);
179 sa.sa_handler = SIG_IGN;
180 sa.sa_flags = SA_RESTART;
181 sigaction (SIGPIPE, &sa, NULL);
183 /* guestfs_create is meant to be a lightweight operation, so
184 * it's OK to do it early here.
186 g = guestfs_create ();
188 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
192 guestfs_set_autosync (g, 1);
194 /* If developing, add ./appliance to the path. Note that libtools
195 * interferes with this because uninstalled guestfish is a shell
196 * script that runs the real program with an absolute path. Detect
199 * BUT if LIBGUESTFS_PATH environment variable is already set by
200 * the user, then don't override it.
202 if (getenv ("LIBGUESTFS_PATH") == NULL &&
204 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
205 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
207 /* CAUTION: we are careful to modify argv[0] here, only after
208 * using it just above.
210 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
211 * of the original, in case it's needed in virt-inspector mode, below.
213 char *real_argv0 = argv[0];
214 argv[0] = bad_cast (program_name);
217 c = getopt_long (argc, argv, options, long_options, &option_index);
221 case 0: /* options which are long only */
222 if (STREQ (long_options[option_index].name, "listen"))
223 remote_control_listen = 1;
224 else if (STREQ (long_options[option_index].name, "remote")) {
226 if (sscanf (optarg, "%d", &remote_control) != 1) {
227 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
228 program_name, optarg);
232 p = getenv ("GUESTFISH_PID");
233 if (!p || sscanf (p, "%d", &remote_control) != 1) {
234 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
235 " to the PID of the remote process\n"),
240 } else if (STREQ (long_options[option_index].name, "selinux")) {
241 guestfs_set_selinux (g, 1);
243 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
244 program_name, long_options[option_index].name, option_index);
250 if (access (optarg, R_OK) != 0) {
254 drv = malloc (sizeof (struct drv));
259 drv->filename = optarg;
261 /* We could fill the device field in, but in fact we
262 * only use it for the -N option at present.
271 if (STRCASEEQ (optarg, "list")) {
272 list_prepared_drives ();
275 drv = malloc (sizeof (struct drv));
280 if (asprintf (&drv->filename, "test%d.img",
281 next_prepared_drive++) == -1) {
285 drv->data = create_prepared_file (optarg, drv->filename);
286 if (asprintf (&drv->device, "/dev/sd%c", next_drive++) == -1) {
295 complete_dest_paths = 0;
300 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
311 r = display_command (optarg);
312 else if (argv[optind] && argv[optind][0] != '-')
313 r = display_command (argv[optind++]);
317 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
325 mp = malloc (sizeof (struct mp));
330 p = strchr (optarg, ':');
333 mp->mountpoint = p+1;
335 mp->mountpoint = bad_cast ("/");
342 guestfs_set_autosync (g, 0);
351 guestfs_set_verbose (g, verbose);
355 printf ("%s %s\n", program_name, PACKAGE_VERSION);
359 guestfs_set_trace (g, 1);
363 usage (EXIT_SUCCESS);
366 usage (EXIT_FAILURE);
370 /* Inspector mode invalidates most of the other arguments. */
372 if (drvs || mps || remote_control_listen || remote_control ||
373 guestfs_get_selinux (g)) {
374 fprintf (stderr, _("%s: cannot use -i option with -a, -m, -N, "
375 "--listen, --remote or --selinux\n"),
379 if (optind >= argc) {
381 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
388 FILE *fp = open_memstream (&cmd, &cmdlen);
390 perror ("open_memstream");
394 fprintf (fp, "virt-inspector");
395 while (optind < argc) {
397 print_shell_quote (fp, argv[optind]);
402 fprintf (fp, " --ro-fish");
404 fprintf (fp, " --fish");
406 if (fclose (fp) == -1) {
413 "%s -i: running: %s\n", program_name, cmd);
415 FILE *pp = popen (cmd, "r");
422 fp = open_memstream (&cmd2, &cmdlen);
424 perror ("open_memstream");
428 fprintf (fp, "%s", real_argv0);
430 if (guestfs_get_verbose (g))
432 if (!guestfs_get_autosync (g))
434 if (guestfs_get_trace (g))
439 if (getline (&insp, &insplen, pp) == -1) {
443 fprintf (fp, " %s", insp);
445 if (pclose (pp) == -1) {
450 if (fclose (fp) == -1) {
457 "%s -i: running: %s\n", program_name, cmd2);
459 int r = system (cmd2);
469 exit (WEXITSTATUS (r));
472 /* If we've got drives to add, add them now. */
475 /* If we've got mountpoints or prepared drives, we must launch the
476 * guest and mount them.
478 if (next_prepared_drive > 1 || mps != NULL) {
479 if (launch () == -1) exit (EXIT_FAILURE);
480 prepare_drives (drvs);
484 /* Remote control? */
485 if (remote_control_listen && remote_control) {
487 _("%s: cannot use --listen and --remote options at the same time\n"),
492 if (remote_control_listen) {
495 _("%s: extra parameters on the command line with --listen flag\n"),
501 _("%s: cannot use --listen and --file options at the same time\n"),
508 /* -f (file) parameter? */
511 if (open (file, O_RDONLY) == -1) {
517 /* Interactive, shell script, or command(s) on the command line? */
518 if (optind >= argc) {
525 cmdline (argv, optind, argc);
533 pod2text (const char *name, const char *shortdesc, const char *str)
537 fp = popen ("pod2text", "w");
539 /* pod2text failed, maybe not found, so let's just print the
540 * source instead, since that's better than doing nothing.
542 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
545 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
550 /* List is built in reverse order, so mount them in reverse order. */
552 mount_mps (struct mp *mp)
557 mount_mps (mp->next);
559 /* Don't use guestfs_mount here because that will default to mount
560 * options -o sync,noatime. For more information, see guestfs(3)
561 * section "LIBGUESTFS GOTCHAS".
563 const char *options = read_only ? "ro" : "";
564 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
571 add_drives (struct drv *drv)
576 add_drives (drv->next);
578 if (drv->data /* -N option is not affected by --ro */ || !read_only)
579 r = guestfs_add_drive (g, drv->filename);
581 r = guestfs_add_drive_ro (g, drv->filename);
588 prepare_drives (struct drv *drv)
591 prepare_drives (drv->next);
593 prepare_drive (drv->filename, drv->data, drv->device);
600 if (guestfs_is_config (g)) {
601 if (guestfs_launch (g) == -1)
619 #define FISH "><fs> "
621 static char *line_read = NULL;
626 #ifdef HAVE_LIBREADLINE
634 line_read = readline (prompt ? FISH : "");
636 if (line_read && *line_read)
637 add_history_line (line_read);
642 #endif /* HAVE_LIBREADLINE */
644 static char buf[8192];
647 if (prompt) printf (FISH);
648 line_read = fgets (buf, sizeof buf, stdin);
651 len = strlen (line_read);
652 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
666 int global_exit_on_error = !prompt;
671 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
672 "editing virtual machine filesystems.\n"
674 "Type: 'help' for a list of commands\n"
675 " 'man' to read the manual\n"
676 " 'quit' to quit the shell\n"
682 exit_on_error = global_exit_on_error;
684 buf = rl_gets (prompt);
690 /* Skip any initial whitespace before the command. */
692 while (*buf && c_isspace (*buf))
697 /* If the next character is '#' then this is a comment. */
698 if (*buf == '#') continue;
700 /* If the next character is '!' then pass the whole lot to system(3). */
708 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
709 WEXITSTATUS (r) != 0)
715 /* If the next character is '-' allow the command to fail without
716 * exiting on error (just for this one command though).
724 /* Get the command (cannot be quoted). */
725 len = strcspn (buf, " \t");
727 if (len == 0) continue;
731 if (buf[len] == '\0') {
738 p += strspn (p, " \t");
740 /* Get the parameters. */
741 while (*p && i < sizeof argv / sizeof argv[0]) {
744 /* Parameters which start with quotes or pipes are treated
745 * specially. Bare parameters are delimited by whitespace.
749 len = strcspn (p, "\"");
750 if (p[len] == '\0') {
751 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
752 if (exit_on_error) exit (EXIT_FAILURE);
755 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
757 _("%s: command arguments not separated by whitespace\n"),
759 if (exit_on_error) exit (EXIT_FAILURE);
763 pend = p[len+1] ? &p[len+2] : &p[len+1];
764 } else if (*p == '\'') {
766 len = strcspn (p, "'");
767 if (p[len] == '\0') {
768 fprintf (stderr, _("%s: unterminated single 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 == '|') {
786 } else if (*p == '[') {
790 while (*pend && c != 0) {
791 if (*pend == '[') c++;
792 else if (*pend == ']') c--;
797 _("%s: unterminated \"[...]\" sequence\n"), program_name);
798 if (exit_on_error) exit (EXIT_FAILURE);
801 if (*pend && (*pend != ' ' && *pend != '\t')) {
803 _("%s: command arguments not separated by whitespace\n"),
805 if (exit_on_error) exit (EXIT_FAILURE);
810 } else if (*p != ' ' && *p != '\t') {
811 /* If the first character is a ~ then note that this parameter
812 * is a candidate for ~username expansion. NB this does not
813 * apply to quoted parameters.
815 tilde_candidate = *p == '~';
816 len = strcspn (p, " \t");
823 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
828 if (!tilde_candidate)
831 argv[i] = try_tilde_expansion (p);
836 p += strspn (p, " \t");
839 if (i == sizeof argv / sizeof argv[0]) {
840 fprintf (stderr, _("%s: too many arguments\n"), program_name);
841 if (exit_on_error) exit (EXIT_FAILURE);
848 if (issue_command (cmd, argv, pipe) == -1) {
849 if (exit_on_error) exit (EXIT_FAILURE);
854 if (prompt) printf ("\n");
858 cmdline (char *argv[], int optind, int argc)
865 if (optind >= argc) return;
867 cmd = argv[optind++];
868 if (STREQ (cmd, ":")) {
869 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
873 /* Allow -cmd on the command line to mean (temporarily) override
874 * the normal exit on error (RHBZ#578407).
881 params = &argv[optind];
883 /* Search for end of command list or ":" ... */
884 while (optind < argc && STRNEQ (argv[optind], ":"))
887 if (optind == argc) {
888 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
892 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
894 cmdline (argv, optind+1, argc);
899 issue_command (const char *cmd, char *argv[], const char *pipecmd)
902 int stdout_saved_fd = -1;
906 /* This counts the commands issued, starting at 1. */
909 /* For | ... commands. Annoyingly we can't use popen(3) here. */
913 if (fflush (stdout) == EOF) {
914 perror ("failed to flush standard output");
918 perror ("pipe failed");
927 if (pid == 0) { /* Child process. */
929 if (dup2 (fd[0], 0) < 0) {
930 perror ("dup2 of stdin failed");
934 r = system (pipecmd);
939 _exit (WEXITSTATUS (r));
942 if ((stdout_saved_fd = dup (1)) < 0) {
943 perror ("failed to dup stdout");
947 if (dup2 (fd[1], 1) < 0) {
948 perror ("failed to dup stdout");
949 close (stdout_saved_fd);
955 for (argc = 0; argv[argc] != NULL; ++argc)
958 /* If --remote was set, then send this command to a remote process. */
960 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
962 /* Otherwise execute it locally. */
963 else if (STRCASEEQ (cmd, "help")) {
968 r = display_command (argv[0]);
970 else if (STRCASEEQ (cmd, "quit") ||
971 STRCASEEQ (cmd, "exit") ||
972 STRCASEEQ (cmd, "q")) {
976 else if (STRCASEEQ (cmd, "alloc") ||
977 STRCASEEQ (cmd, "allocate"))
978 r = do_alloc (cmd, argc, argv);
979 else if (STRCASEEQ (cmd, "echo"))
980 r = do_echo (cmd, argc, argv);
981 else if (STRCASEEQ (cmd, "edit") ||
982 STRCASEEQ (cmd, "vi") ||
983 STRCASEEQ (cmd, "emacs"))
984 r = do_edit (cmd, argc, argv);
985 else if (STRCASEEQ (cmd, "lcd"))
986 r = do_lcd (cmd, argc, argv);
987 else if (STRCASEEQ (cmd, "glob"))
988 r = do_glob (cmd, argc, argv);
989 else if (STRCASEEQ (cmd, "man") ||
990 STRCASEEQ (cmd, "manual"))
991 r = do_man (cmd, argc, argv);
992 else if (STRCASEEQ (cmd, "more") ||
993 STRCASEEQ (cmd, "less"))
994 r = do_more (cmd, argc, argv);
995 else if (STRCASEEQ (cmd, "reopen"))
996 r = do_reopen (cmd, argc, argv);
997 else if (STRCASEEQ (cmd, "sparse"))
998 r = do_sparse (cmd, argc, argv);
999 else if (STRCASEEQ (cmd, "supported"))
1000 r = do_supported (cmd, argc, argv);
1001 else if (STRCASEEQ (cmd, "time"))
1002 r = do_time (cmd, argc, argv);
1004 r = run_action (cmd, argc, argv);
1006 /* Always flush stdout after every command, so that messages, results
1007 * etc appear immediately.
1009 if (fflush (stdout) == EOF) {
1010 perror ("failed to flush standard output");
1016 if (dup2 (stdout_saved_fd, 1) < 0) {
1017 perror ("failed to dup2 standard output");
1020 close (stdout_saved_fd);
1021 if (waitpid (pid, NULL, 0) < 0) {
1022 perror ("waiting for command to complete");
1031 list_builtin_commands (void)
1033 /* help, man and quit should appear at the top */
1034 printf ("%-20s %s\n",
1035 "help", _("display a list of commands or help on a command"));
1036 printf ("%-20s %s\n",
1037 "man", _("read the manual"));
1038 printf ("%-20s %s\n",
1039 "quit", _("quit guestfish"));
1041 printf ("%-20s %s\n",
1042 "alloc", _("allocate an image"));
1043 printf ("%-20s %s\n",
1044 "echo", _("display a line of text"));
1045 printf ("%-20s %s\n",
1046 "edit", _("edit a file in the image"));
1047 printf ("%-20s %s\n",
1048 "lcd", _("local change directory"));
1049 printf ("%-20s %s\n",
1050 "glob", _("expand wildcards in command"));
1051 printf ("%-20s %s\n",
1052 "more", _("view a file in the pager"));
1053 printf ("%-20s %s\n",
1054 "reopen", _("close and reopen libguestfs handle"));
1055 printf ("%-20s %s\n",
1056 "sparse", _("allocate a sparse image file"));
1057 printf ("%-20s %s\n",
1058 "supported", _("list supported groups of commands"));
1059 printf ("%-20s %s\n",
1060 "time", _("measure time taken to run command"));
1062 /* actions are printed after this (see list_commands) */
1066 display_builtin_command (const char *cmd)
1068 /* help for actions is auto-generated, see display_command */
1070 if (STRCASEEQ (cmd, "alloc") ||
1071 STRCASEEQ (cmd, "allocate")) {
1072 printf (_("alloc - allocate an image\n"
1073 " alloc <filename> <size>\n"
1075 " This creates an empty (zeroed) file of the given size,\n"
1076 " and then adds so it can be further examined.\n"
1078 " For more advanced image creation, see qemu-img utility.\n"
1080 " Size can be specified using standard suffixes, eg. '1M'.\n"
1084 else if (STRCASEEQ (cmd, "echo")) {
1085 printf (_("echo - display a line of text\n"
1086 " echo [<params> ...]\n"
1088 " This echos the parameters to the terminal.\n"));
1091 else if (STRCASEEQ (cmd, "edit") ||
1092 STRCASEEQ (cmd, "vi") ||
1093 STRCASEEQ (cmd, "emacs")) {
1094 printf (_("edit - edit a file in the image\n"
1095 " edit <filename>\n"
1097 " This is used to edit a file.\n"
1099 " It is the equivalent of (and is implemented by)\n"
1100 " running \"cat\", editing locally, and then \"write\".\n"
1102 " Normally it uses $EDITOR, but if you use the aliases\n"
1103 " \"vi\" or \"emacs\" you will get those editors.\n"
1105 " NOTE: This will not work reliably for large files\n"
1106 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1109 else if (STRCASEEQ (cmd, "lcd")) {
1110 printf (_("lcd - local change directory\n"
1111 " lcd <directory>\n"
1113 " Change guestfish's current directory. This command is\n"
1114 " useful if you want to download files to a particular\n"
1118 else if (STRCASEEQ (cmd, "glob")) {
1119 printf (_("glob - expand wildcards in command\n"
1120 " glob <command> [<args> ...]\n"
1122 " Glob runs <command> with wildcards expanded in any\n"
1123 " command args. Note that the command is run repeatedly\n"
1124 " once for each expanded argument.\n"));
1127 else if (STRCASEEQ (cmd, "man") ||
1128 STRCASEEQ (cmd, "manual")) {
1129 printf (_("man - read the manual\n"
1132 " Opens the manual page for guestfish.\n"));
1135 else if (STRCASEEQ (cmd, "help")) {
1136 printf (_("help - display a list of commands or help on a command\n"
1141 else if (STRCASEEQ (cmd, "more") ||
1142 STRCASEEQ (cmd, "less")) {
1143 printf (_("more - view a file in the pager\n"
1144 " more <filename>\n"
1146 " This is used to view a file in the pager.\n"
1148 " It is the equivalent of (and is implemented by)\n"
1149 " running \"cat\" and using the pager.\n"
1151 " Normally it uses $PAGER, but if you use the alias\n"
1152 " \"less\" then it always uses \"less\".\n"
1154 " NOTE: This will not work reliably for large files\n"
1155 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1158 else if (STRCASEEQ (cmd, "quit") ||
1159 STRCASEEQ (cmd, "exit") ||
1160 STRCASEEQ (cmd, "q")) {
1161 printf (_("quit - quit guestfish\n"
1165 else if (STRCASEEQ (cmd, "reopen")) {
1166 printf (_("reopen - close and reopen the libguestfs handle\n"
1169 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1170 "this normally, because the handle is closed properly when guestfish\n"
1171 "exits. However this is occasionally useful for testing.\n"));
1174 else if (STRCASEEQ (cmd, "sparse")) {
1175 printf (_("sparse - allocate a sparse image file\n"
1176 " sparse <filename> <size>\n"
1178 " This creates an empty sparse file of the given size,\n"
1179 " and then adds so it can be further examined.\n"
1181 " In all respects it works the same as the 'alloc'\n"
1182 " command, except that the image file is allocated\n"
1183 " sparsely, which means that disk blocks are not assigned\n"
1184 " to the file until they are needed. Sparse disk files\n"
1185 " only use space when written to, but they are slower\n"
1186 " and there is a danger you could run out of real disk\n"
1187 " space during a write operation.\n"
1189 " For more advanced image creation, see qemu-img utility.\n"
1191 " Size can be specified using standard suffixes, eg. '1M'.\n"
1195 else if (STRCASEEQ (cmd, "supported")) {
1196 printf (_("supported - list supported groups of commands\n"
1199 " This command returns a list of the optional groups\n"
1200 " known to the daemon, and indicates which ones are\n"
1201 " supported by this build of the libguestfs appliance.\n"
1203 " See also guestfs(3) section AVAILABILITY.\n"
1207 else if (STRCASEEQ (cmd, "time")) {
1208 printf (_("time - measure time taken to run command\n"
1209 " time <command> [<args> ...]\n"
1211 " This runs <command> as usual, and prints the elapsed\n"
1212 " time afterwards.\n"));
1216 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1222 /* This is printed when the user types in an unknown command for the
1223 * first command issued. A common case is the user doing:
1224 * guestfish disk.img
1225 * expecting guestfish to open 'disk.img' (in fact, this tried to
1226 * run a command 'disk.img').
1229 extended_help_message (void)
1232 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1233 "For a list of commands: guestfish -h\n"
1234 "For complete documentation: man guestfish\n"));
1238 free_strings (char **argv)
1242 for (argc = 0; argv[argc] != NULL; ++argc)
1248 count_strings (char *const *argv)
1252 for (c = 0; argv[c]; ++c)
1258 print_strings (char *const *argv)
1262 for (argc = 0; argv[argc] != NULL; ++argc)
1263 printf ("%s\n", argv[argc]);
1267 print_table (char *const *argv)
1271 for (i = 0; argv[i] != NULL; i += 2)
1272 printf ("%s: %s\n", argv[i], argv[i+1]);
1276 is_true (const char *str)
1279 STRCASENEQ (str, "0") &&
1280 STRCASENEQ (str, "f") &&
1281 STRCASENEQ (str, "false") &&
1282 STRCASENEQ (str, "n") &&
1283 STRCASENEQ (str, "no");
1286 /* Free strings from a non-NULL terminated char** */
1288 free_n_strings (char **str, size_t len)
1292 for (i = 0; i < len; i++) {
1299 parse_string_list (const char *str)
1302 size_t argv_len = 0;
1304 /* Current position pointer */
1305 const char *p = str;
1307 /* Token might be simple:
1310 * 'This is a single token'
1311 * or contain embedded single-quoted sections:
1312 * This' is a sing'l'e to'ken
1314 * The latter may seem over-complicated, but it's what a normal shell does.
1315 * Not doing it risks surprising somebody.
1317 * This outer loop is over complete tokens.
1323 /* Skip leading whitespace */
1324 p += strspn (p, " \t");
1328 /* This loop is over token 'fragments'. A token can be in multiple bits if
1329 * it contains single quotes. We also treat both sides of an escaped quote
1330 * as separate fragments because we can't just copy it: we have to remove
1333 while (*p && (!c_isblank (*p) || in_quote)) {
1334 const char *end = p;
1336 /* Check if the fragment starts with a quote */
1338 /* Toggle in_quote */
1339 in_quote = !in_quote;
1341 /* Skip the quote */
1345 /* If we're in a quote, look for an end quote */
1347 end += strcspn (end, "'");
1350 /* Otherwise, look for whitespace or a quote */
1352 end += strcspn (end, " \t'");
1355 /* Grow the token to accommodate the fragment */
1356 size_t tok_end = tok_len;
1358 char *tok_new = realloc (tok, tok_len + 1);
1359 if (NULL == tok_new) {
1361 free_n_strings (argv, argv_len);
1363 exit (EXIT_FAILURE);
1367 /* Check if we stopped on an escaped quote */
1368 if ('\'' == *end && end != p && *(end-1) == '\\') {
1369 /* Add everything before \' to the token */
1370 memcpy (&tok[tok_end], p, end - p - 1);
1373 tok[tok_len-1] = '\'';
1375 /* Already processed the quote */
1380 /* Add the whole fragment */
1381 memcpy (&tok[tok_end], p, end - p);
1387 /* We've reached the end of a token. We shouldn't still be in quotes. */
1389 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1391 free_n_strings (argv, argv_len);
1396 /* Add this token if there is one. There might not be if there was
1397 * whitespace at the end of the input string */
1399 /* Add the NULL terminator */
1400 tok[tok_len] = '\0';
1402 /* Add the argument to the argument list */
1404 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1405 if (NULL == argv_new) {
1407 free_n_strings (argv, argv_len-1);
1409 exit (EXIT_FAILURE);
1413 argv[argv_len-1] = tok;
1417 /* NULL terminate the argument list */
1419 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1420 if (NULL == argv_new) {
1422 free_n_strings (argv, argv_len-1);
1423 exit (EXIT_FAILURE);
1427 argv[argv_len-1] = NULL;
1432 #ifdef HAVE_LIBREADLINE
1433 static char histfile[1024];
1434 static int nr_history_lines = 0;
1438 initialize_readline (void)
1440 #ifdef HAVE_LIBREADLINE
1443 home = getenv ("HOME");
1445 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1447 (void) read_history (histfile);
1450 rl_readline_name = "guestfish";
1451 rl_attempted_completion_function = do_completion;
1453 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1454 * call the readline(), which happens later. Therefore, these
1455 * provide default values which can be overridden by the user if
1458 (void) rl_variable_bind ("completion-ignore-case", "on");
1463 cleanup_readline (void)
1465 #ifdef HAVE_LIBREADLINE
1468 if (histfile[0] != '\0') {
1469 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1476 #ifdef HAVE_APPEND_HISTORY
1477 (void) append_history (nr_history_lines, histfile);
1479 (void) write_history (histfile);
1485 #ifdef HAVE_LIBREADLINE
1487 add_history_line (const char *line)
1495 xwrite (int fd, const void *v_buf, size_t len)
1498 const char *buf = v_buf;
1501 r = write (fd, buf, len);
1513 /* Resolve the special "win:..." form for Windows-specific paths.
1514 * This always returns a newly allocated string which is freed by the
1515 * caller function in "cmds.c".
1518 resolve_win_path (const char *path)
1523 if (STRCASENEQLEN (path, "win:", 4)) {
1524 ret = strdup (path);
1532 /* Drop drive letter, if it's "C:". */
1533 if (STRCASEEQLEN (path, "c:", 2))
1543 ret = strdup (path);
1549 /* Blindly convert any backslashes into forward slashes. Is this good? */
1550 for (i = 0; i < strlen (ret); ++i)
1554 char *t = guestfs_case_sensitive_path (g, ret);
1561 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1562 * The caller (cmds.c) will call free_file_in after the command has
1563 * run which should clean up resources.
1565 static char *file_in_heredoc (const char *endmarker);
1566 static char *file_in_tmpfile = NULL;
1569 file_in (const char *arg)
1573 if (STREQ (arg, "-")) {
1574 ret = strdup ("/dev/stdin");
1580 else if (STRPREFIX (arg, "-<<")) {
1581 const char *endmarker = &arg[3];
1582 if (*endmarker == '\0') {
1583 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1587 ret = file_in_heredoc (endmarker);
1603 file_in_heredoc (const char *endmarker)
1605 static const char template[] = "/tmp/heredocXXXXXX";
1606 file_in_tmpfile = strdup (template);
1607 if (file_in_tmpfile == NULL) {
1612 int fd = mkstemp (file_in_tmpfile);
1618 size_t markerlen = strlen (endmarker);
1620 char buffer[BUFSIZ];
1621 int write_error = 0;
1622 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1623 /* Look for "END"<EOF> or "END\n" in input. */
1624 size_t blen = strlen (buffer);
1625 if (STREQLEN (buffer, endmarker, markerlen) &&
1626 (blen == markerlen ||
1627 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1630 if (xwrite (fd, buffer, blen) == -1) {
1631 if (!write_error) perror ("write");
1633 /* continue reading up to the end marker */
1637 /* Reached EOF of stdin without finding the end marker, which
1638 * is likely to be an error.
1640 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1641 program_name, endmarker);
1650 if (close (fd) == -1) {
1655 return file_in_tmpfile;
1658 unlink (file_in_tmpfile);
1661 free (file_in_tmpfile);
1662 file_in_tmpfile = NULL;
1667 free_file_in (char *s)
1669 if (file_in_tmpfile) {
1670 if (unlink (file_in_tmpfile) == -1)
1671 perror (file_in_tmpfile);
1672 file_in_tmpfile = NULL;
1675 /* Free the device or file name which was strdup'd in file_in().
1676 * Note it's not immediately clear, but for -<< heredocs,
1677 * s == file_in_tmpfile, so this frees up that buffer.
1682 /* Resolve the special FileOut paths ("-" or filename).
1683 * The caller (cmds.c) will call free (str) after the command has run.
1686 file_out (const char *arg)
1690 if (STREQ (arg, "-"))
1691 ret = strdup ("/dev/stdout");
1703 print_shell_quote (FILE *stream, const char *str)
1705 #define SAFE(c) (c_isalnum((c)) || \
1706 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
1709 for (i = 0; str[i]; ++i) {
1711 putc ('\\', stream);
1712 putc (str[i], stream);