1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009 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 static void add_history_line (const char *);
70 /* Currently open libguestfs handle. */
76 int remote_control_listen = 0;
77 int remote_control = 0;
78 int exit_on_error = 1;
81 static void __attribute__((noreturn))
84 if (status != EXIT_SUCCESS)
85 fprintf (stderr, _("Try `%s --help' for more information.\n"),
89 _("%s: guest filesystem shell\n"
90 "%s lets you edit virtual machine filesystems\n"
91 "Copyright (C) 2009 Red Hat Inc.\n"
93 " %s [--options] cmd [: cmd : cmd ...]\n"
94 " %s -i libvirt-domain\n"
95 " %s -i disk-image(s)\n"
96 "or for interactive use:\n"
98 "or from a shell script:\n"
104 " -h|--cmd-help List available commands\n"
105 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
106 " -a|--add image Add image\n"
107 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
108 " -f|--file file Read commands from file\n"
109 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
110 " --listen Listen for remote commands\n"
111 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
112 " -n|--no-sync Don't autosync\n"
113 " -N|--new type Create prepared disk (test1.img, ...)\n"
114 " --remote[=pid] Send commands to remote %s\n"
115 " -r|--ro Mount read-only\n"
116 " --selinux Enable SELinux support\n"
117 " -v|--verbose Verbose messages\n"
118 " -x Echo each command before executing it\n"
119 " -V|--version Display version and exit\n"
120 "For more information, see the manpage %s(1).\n"),
121 program_name, program_name, program_name,
122 program_name, program_name, program_name,
123 program_name, program_name, program_name);
129 main (int argc, char *argv[])
131 /* Set global program name that is not polluted with libtool artifacts. */
132 set_program_name (argv[0]);
134 atexit (close_stdout);
136 setlocale (LC_ALL, "");
137 bindtextdomain (PACKAGE, LOCALEBASEDIR);
138 textdomain (PACKAGE);
140 enum { HELP_OPTION = CHAR_MAX + 1 };
142 static const char *options = "a:Df:h::im:nN:rv?Vx";
143 static const struct option long_options[] = {
144 { "add", 1, 0, 'a' },
145 { "cmd-help", 2, 0, 'h' },
146 { "file", 1, 0, 'f' },
147 { "help", 0, 0, HELP_OPTION },
148 { "inspector", 0, 0, 'i' },
149 { "listen", 0, 0, 0 },
150 { "mount", 1, 0, 'm' },
151 { "new", 1, 0, 'N' },
152 { "no-dest-paths", 0, 0, 'D' },
153 { "no-sync", 0, 0, 'n' },
154 { "remote", 2, 0, 0 },
156 { "selinux", 0, 0, 0 },
157 { "verbose", 0, 0, 'v' },
158 { "version", 0, 0, 'V' },
161 struct drv *drvs = NULL;
163 struct mp *mps = NULL;
165 char *p, *file = NULL;
170 char next_drive = 'a';
171 int next_prepared_drive = 1;
173 initialize_readline ();
175 memset (&sa, 0, sizeof sa);
176 sa.sa_handler = SIG_IGN;
177 sa.sa_flags = SA_RESTART;
178 sigaction (SIGPIPE, &sa, NULL);
180 /* guestfs_create is meant to be a lightweight operation, so
181 * it's OK to do it early here.
183 g = guestfs_create ();
185 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
189 guestfs_set_autosync (g, 1);
191 /* If developing, add ./appliance to the path. Note that libtools
192 * interferes with this because uninstalled guestfish is a shell
193 * script that runs the real program with an absolute path. Detect
196 * BUT if LIBGUESTFS_PATH environment variable is already set by
197 * the user, then don't override it.
199 if (getenv ("LIBGUESTFS_PATH") == NULL &&
201 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
202 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
204 /* CAUTION: we are careful to modify argv[0] here, only after
205 * using it just above.
207 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
208 * of the original, in case it's needed in virt-inspector mode, below.
210 char *real_argv0 = argv[0];
211 argv[0] = bad_cast (program_name);
214 c = getopt_long (argc, argv, options, long_options, &option_index);
218 case 0: /* options which are long only */
219 if (STREQ (long_options[option_index].name, "listen"))
220 remote_control_listen = 1;
221 else if (STREQ (long_options[option_index].name, "remote")) {
223 if (sscanf (optarg, "%d", &remote_control) != 1) {
224 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
225 program_name, optarg);
229 p = getenv ("GUESTFISH_PID");
230 if (!p || sscanf (p, "%d", &remote_control) != 1) {
231 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
232 " to the PID of the remote process\n"),
237 } else if (STREQ (long_options[option_index].name, "selinux")) {
238 guestfs_set_selinux (g, 1);
240 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
241 program_name, long_options[option_index].name, option_index);
247 if (access (optarg, R_OK) != 0) {
251 drv = malloc (sizeof (struct drv));
256 drv->filename = optarg;
258 /* We could fill the device field in, but in fact we
259 * only use it for the -N option at present.
268 if (STRCASEEQ (optarg, "list")) {
269 list_prepared_drives ();
272 drv = malloc (sizeof (struct drv));
277 if (asprintf (&drv->filename, "test%d.img",
278 next_prepared_drive++) == -1) {
282 drv->data = create_prepared_file (optarg, drv->filename);
283 if (asprintf (&drv->device, "/dev/sd%c", next_drive++) == -1) {
292 complete_dest_paths = 0;
297 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
306 display_command (optarg);
307 else if (argv[optind] && argv[optind][0] != '-')
308 display_command (argv[optind++]);
318 mp = malloc (sizeof (struct mp));
323 p = strchr (optarg, ':');
326 mp->mountpoint = p+1;
328 mp->mountpoint = bad_cast ("/");
335 guestfs_set_autosync (g, 0);
344 guestfs_set_verbose (g, verbose);
348 printf ("%s %s\n", program_name, PACKAGE_VERSION);
352 guestfs_set_trace (g, 1);
356 usage (EXIT_SUCCESS);
359 usage (EXIT_FAILURE);
363 /* Inspector mode invalidates most of the other arguments. */
368 if (drvs || mps || remote_control_listen || remote_control ||
369 guestfs_get_selinux (g)) {
370 fprintf (stderr, _("%s: cannot use -i option with -a, -m, -N, "
371 "--listen, --remote or --selinux\n"),
375 if (optind >= argc) {
377 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
382 strcpy (cmd, "a=`virt-inspector");
383 while (optind < argc) {
384 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
387 _("%s: virt-inspector command too long for fixed-size buffer\n"),
392 strcat (cmd, argv[optind]);
398 strcat (cmd, " --ro-fish");
400 strcat (cmd, " --fish");
402 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
404 if (guestfs_get_verbose (g))
406 if (!guestfs_get_autosync (g))
408 if (guestfs_get_trace (g))
413 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
420 exit (WEXITSTATUS (r));
423 /* If we've got drives to add, add them now. */
426 /* If we've got mountpoints or prepared drives, we must launch the
427 * guest and mount them.
429 if (next_prepared_drive > 1 || mps != NULL) {
430 if (launch () == -1) exit (EXIT_FAILURE);
431 prepare_drives (drvs);
435 /* Remote control? */
436 if (remote_control_listen && remote_control) {
438 _("%s: cannot use --listen and --remote options at the same time\n"),
443 if (remote_control_listen) {
446 _("%s: extra parameters on the command line with --listen flag\n"),
452 _("%s: cannot use --listen and --file options at the same time\n"),
459 /* -f (file) parameter? */
462 if (open (file, O_RDONLY) == -1) {
468 /* Interactive, shell script, or command(s) on the command line? */
469 if (optind >= argc) {
476 cmdline (argv, optind, argc);
484 pod2text (const char *name, const char *shortdesc, const char *str)
488 fp = popen ("pod2text", "w");
490 /* pod2text failed, maybe not found, so let's just print the
491 * source instead, since that's better than doing nothing.
493 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
496 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
501 /* List is built in reverse order, so mount them in reverse order. */
503 mount_mps (struct mp *mp)
508 mount_mps (mp->next);
510 /* Don't use guestfs_mount here because that will default to mount
511 * options -o sync,noatime. For more information, see guestfs(3)
512 * section "LIBGUESTFS GOTCHAS".
514 const char *options = read_only ? "ro" : "";
515 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
522 add_drives (struct drv *drv)
527 add_drives (drv->next);
529 if (drv->data /* -N option is not affected by --ro */ || !read_only)
530 r = guestfs_add_drive (g, drv->filename);
532 r = guestfs_add_drive_ro (g, drv->filename);
539 prepare_drives (struct drv *drv)
542 prepare_drives (drv->next);
544 prepare_drive (drv->filename, drv->data, drv->device);
551 if (guestfs_is_config (g)) {
552 if (guestfs_launch (g) == -1)
570 #define FISH "><fs> "
572 static char *line_read = NULL;
577 #ifdef HAVE_LIBREADLINE
585 line_read = readline (prompt ? FISH : "");
587 if (line_read && *line_read)
588 add_history_line (line_read);
593 #endif /* HAVE_LIBREADLINE */
595 static char buf[8192];
598 if (prompt) printf (FISH);
599 line_read = fgets (buf, sizeof buf, stdin);
602 len = strlen (line_read);
603 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
617 int global_exit_on_error = !prompt;
622 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
623 "editing virtual machine filesystems.\n"
625 "Type: 'help' for a list of commands\n"
626 " 'man' to read the manual\n"
627 " 'quit' to quit the shell\n"
633 exit_on_error = global_exit_on_error;
635 buf = rl_gets (prompt);
641 /* Skip any initial whitespace before the command. */
643 while (*buf && c_isspace (*buf))
648 /* If the next character is '#' then this is a comment. */
649 if (*buf == '#') continue;
651 /* If the next character is '!' then pass the whole lot to system(3). */
659 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
660 WEXITSTATUS (r) != 0)
666 /* If the next character is '-' allow the command to fail without
667 * exiting on error (just for this one command though).
675 /* Get the command (cannot be quoted). */
676 len = strcspn (buf, " \t");
678 if (len == 0) continue;
682 if (buf[len] == '\0') {
689 p += strspn (p, " \t");
691 /* Get the parameters. */
692 while (*p && i < sizeof argv / sizeof argv[0]) {
695 /* Parameters which start with quotes or pipes are treated
696 * specially. Bare parameters are delimited by whitespace.
700 len = strcspn (p, "\"");
701 if (p[len] == '\0') {
702 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
703 if (exit_on_error) exit (EXIT_FAILURE);
706 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
708 _("%s: command arguments not separated by whitespace\n"),
710 if (exit_on_error) exit (EXIT_FAILURE);
714 pend = p[len+1] ? &p[len+2] : &p[len+1];
715 } else if (*p == '\'') {
717 len = strcspn (p, "'");
718 if (p[len] == '\0') {
719 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
720 if (exit_on_error) exit (EXIT_FAILURE);
723 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
725 _("%s: command arguments not separated by whitespace\n"),
727 if (exit_on_error) exit (EXIT_FAILURE);
731 pend = p[len+1] ? &p[len+2] : &p[len+1];
732 } else if (*p == '|') {
737 } else if (*p == '[') {
741 while (*pend && c != 0) {
742 if (*pend == '[') c++;
743 else if (*pend == ']') c--;
748 _("%s: unterminated \"[...]\" sequence\n"), program_name);
749 if (exit_on_error) exit (EXIT_FAILURE);
752 if (*pend && (*pend != ' ' && *pend != '\t')) {
754 _("%s: command arguments not separated by whitespace\n"),
756 if (exit_on_error) exit (EXIT_FAILURE);
761 } else if (*p != ' ' && *p != '\t') {
762 /* If the first character is a ~ then note that this parameter
763 * is a candidate for ~username expansion. NB this does not
764 * apply to quoted parameters.
766 tilde_candidate = *p == '~';
767 len = strcspn (p, " \t");
774 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
779 if (!tilde_candidate)
782 argv[i] = try_tilde_expansion (p);
787 p += strspn (p, " \t");
790 if (i == sizeof argv / sizeof argv[0]) {
791 fprintf (stderr, _("%s: too many arguments\n"), program_name);
792 if (exit_on_error) exit (EXIT_FAILURE);
799 if (issue_command (cmd, argv, pipe) == -1) {
800 if (exit_on_error) exit (EXIT_FAILURE);
805 if (prompt) printf ("\n");
809 cmdline (char *argv[], int optind, int argc)
816 if (optind >= argc) return;
818 cmd = argv[optind++];
819 if (STREQ (cmd, ":")) {
820 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
824 /* Allow -cmd on the command line to mean (temporarily) override
825 * the normal exit on error (RHBZ#578407).
832 params = &argv[optind];
834 /* Search for end of command list or ":" ... */
835 while (optind < argc && STRNEQ (argv[optind], ":"))
838 if (optind == argc) {
839 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
843 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
845 cmdline (argv, optind+1, argc);
850 issue_command (const char *cmd, char *argv[], const char *pipecmd)
853 int stdout_saved_fd = -1;
857 /* This counts the commands issued, starting at 1. */
860 /* For | ... commands. Annoyingly we can't use popen(3) here. */
864 if (fflush (stdout) == EOF) {
865 perror ("failed to flush standard output");
869 perror ("pipe failed");
878 if (pid == 0) { /* Child process. */
880 if (dup2 (fd[0], 0) < 0) {
881 perror ("dup2 of stdin failed");
885 r = system (pipecmd);
890 _exit (WEXITSTATUS (r));
893 if ((stdout_saved_fd = dup (1)) < 0) {
894 perror ("failed to dup stdout");
898 if (dup2 (fd[1], 1) < 0) {
899 perror ("failed to dup stdout");
900 close (stdout_saved_fd);
906 for (argc = 0; argv[argc] != NULL; ++argc)
909 /* If --remote was set, then send this command to a remote process. */
911 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
913 /* Otherwise execute it locally. */
914 else if (STRCASEEQ (cmd, "help")) {
918 display_command (argv[0]);
921 else if (STRCASEEQ (cmd, "quit") ||
922 STRCASEEQ (cmd, "exit") ||
923 STRCASEEQ (cmd, "q")) {
927 else if (STRCASEEQ (cmd, "alloc") ||
928 STRCASEEQ (cmd, "allocate"))
929 r = do_alloc (cmd, argc, argv);
930 else if (STRCASEEQ (cmd, "echo"))
931 r = do_echo (cmd, argc, argv);
932 else if (STRCASEEQ (cmd, "edit") ||
933 STRCASEEQ (cmd, "vi") ||
934 STRCASEEQ (cmd, "emacs"))
935 r = do_edit (cmd, argc, argv);
936 else if (STRCASEEQ (cmd, "lcd"))
937 r = do_lcd (cmd, argc, argv);
938 else if (STRCASEEQ (cmd, "glob"))
939 r = do_glob (cmd, argc, argv);
940 else if (STRCASEEQ (cmd, "man") ||
941 STRCASEEQ (cmd, "manual"))
942 r = do_man (cmd, argc, argv);
943 else if (STRCASEEQ (cmd, "more") ||
944 STRCASEEQ (cmd, "less"))
945 r = do_more (cmd, argc, argv);
946 else if (STRCASEEQ (cmd, "reopen"))
947 r = do_reopen (cmd, argc, argv);
948 else if (STRCASEEQ (cmd, "sparse"))
949 r = do_sparse (cmd, argc, argv);
950 else if (STRCASEEQ (cmd, "time"))
951 r = do_time (cmd, argc, argv);
953 r = run_action (cmd, argc, argv);
955 /* Always flush stdout after every command, so that messages, results
956 * etc appear immediately.
958 if (fflush (stdout) == EOF) {
959 perror ("failed to flush standard output");
965 if (dup2 (stdout_saved_fd, 1) < 0) {
966 perror ("failed to dup2 standard output");
969 close (stdout_saved_fd);
970 if (waitpid (pid, NULL, 0) < 0) {
971 perror ("waiting for command to complete");
980 list_builtin_commands (void)
982 /* help, man and quit should appear at the top */
983 printf ("%-20s %s\n",
984 "help", _("display a list of commands or help on a command"));
985 printf ("%-20s %s\n",
986 "man", _("read the manual"));
987 printf ("%-20s %s\n",
988 "quit", _("quit guestfish"));
990 printf ("%-20s %s\n",
991 "alloc", _("allocate an image"));
992 printf ("%-20s %s\n",
993 "echo", _("display a line of text"));
994 printf ("%-20s %s\n",
995 "edit", _("edit a file in the image"));
996 printf ("%-20s %s\n",
997 "lcd", _("local change directory"));
998 printf ("%-20s %s\n",
999 "glob", _("expand wildcards in command"));
1000 printf ("%-20s %s\n",
1001 "more", _("view a file in the pager"));
1002 printf ("%-20s %s\n",
1003 "reopen", _("close and reopen libguestfs handle"));
1004 printf ("%-20s %s\n",
1005 "sparse", _("allocate a sparse image file"));
1006 printf ("%-20s %s\n",
1007 "time", _("measure time taken to run command"));
1009 /* actions are printed after this (see list_commands) */
1013 display_builtin_command (const char *cmd)
1015 /* help for actions is auto-generated, see display_command */
1017 if (STRCASEEQ (cmd, "alloc") ||
1018 STRCASEEQ (cmd, "allocate"))
1019 printf (_("alloc - allocate an image\n"
1020 " alloc <filename> <size>\n"
1022 " This creates an empty (zeroed) file of the given size,\n"
1023 " and then adds so it can be further examined.\n"
1025 " For more advanced image creation, see qemu-img utility.\n"
1027 " Size can be specified (where <nn> means a number):\n"
1028 " <nn> number of kilobytes\n"
1029 " eg: 1440 standard 3.5\" floppy\n"
1030 " <nn>K or <nn>KB number of kilobytes\n"
1031 " <nn>M or <nn>MB number of megabytes\n"
1032 " <nn>G or <nn>GB number of gigabytes\n"
1033 " <nn>T or <nn>TB number of terabytes\n"
1034 " <nn>P or <nn>PB number of petabytes\n"
1035 " <nn>E or <nn>EB number of exabytes\n"
1036 " <nn>sects number of 512 byte sectors\n"));
1037 else if (STRCASEEQ (cmd, "echo"))
1038 printf (_("echo - display a line of text\n"
1039 " echo [<params> ...]\n"
1041 " This echos the parameters to the terminal.\n"));
1042 else if (STRCASEEQ (cmd, "edit") ||
1043 STRCASEEQ (cmd, "vi") ||
1044 STRCASEEQ (cmd, "emacs"))
1045 printf (_("edit - edit a file in the image\n"
1046 " edit <filename>\n"
1048 " This is used to edit a file.\n"
1050 " It is the equivalent of (and is implemented by)\n"
1051 " running \"cat\", editing locally, and then \"write-file\".\n"
1053 " Normally it uses $EDITOR, but if you use the aliases\n"
1054 " \"vi\" or \"emacs\" you will get those editors.\n"
1056 " NOTE: This will not work reliably for large files\n"
1057 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1058 else if (STRCASEEQ (cmd, "lcd"))
1059 printf (_("lcd - local change directory\n"
1060 " lcd <directory>\n"
1062 " Change guestfish's current directory. This command is\n"
1063 " useful if you want to download files to a particular\n"
1065 else if (STRCASEEQ (cmd, "glob"))
1066 printf (_("glob - expand wildcards in command\n"
1067 " glob <command> [<args> ...]\n"
1069 " Glob runs <command> with wildcards expanded in any\n"
1070 " command args. Note that the command is run repeatedly\n"
1071 " once for each expanded argument.\n"));
1072 else if (STRCASEEQ (cmd, "man") ||
1073 STRCASEEQ (cmd, "manual"))
1074 printf (_("man - read the manual\n"
1077 " Opens the manual page for guestfish.\n"));
1078 else if (STRCASEEQ (cmd, "help"))
1079 printf (_("help - display a list of commands or help on a command\n"
1082 else if (STRCASEEQ (cmd, "more") ||
1083 STRCASEEQ (cmd, "less"))
1084 printf (_("more - view a file in the pager\n"
1085 " more <filename>\n"
1087 " This is used to view a file in the pager.\n"
1089 " It is the equivalent of (and is implemented by)\n"
1090 " running \"cat\" and using the pager.\n"
1092 " Normally it uses $PAGER, but if you use the alias\n"
1093 " \"less\" then it always uses \"less\".\n"
1095 " NOTE: This will not work reliably for large files\n"
1096 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1097 else if (STRCASEEQ (cmd, "quit") ||
1098 STRCASEEQ (cmd, "exit") ||
1099 STRCASEEQ (cmd, "q"))
1100 printf (_("quit - quit guestfish\n"
1102 else if (STRCASEEQ (cmd, "reopen"))
1103 printf (_("reopen - close and reopen the libguestfs handle\n"
1106 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1107 "this normally, because the handle is closed properly when guestfish\n"
1108 "exits. However this is occasionally useful for testing.\n"));
1109 else if (STRCASEEQ (cmd, "sparse"))
1110 printf (_("sparse - allocate a sparse image file\n"
1111 " sparse <filename> <size>\n"
1113 " This creates an empty sparse file of the given size,\n"
1114 " and then adds so it can be further examined.\n"
1116 " In all respects it works the same as the 'alloc'\n"
1117 " command, except that the image file is allocated\n"
1118 " sparsely, which means that disk blocks are not assigned\n"
1119 " to the file until they are needed. Sparse disk files\n"
1120 " only use space when written to, but they are slower\n"
1121 " and there is a danger you could run out of real disk\n"
1122 " space during a write operation.\n"
1124 " For more advanced image creation, see qemu-img utility.\n"
1126 " Size can be specified (where <nn> means a number):\n"
1127 " <nn> number of kilobytes\n"
1128 " eg: 1440 standard 3.5\" floppy\n"
1129 " <nn>K or <nn>KB number of kilobytes\n"
1130 " <nn>M or <nn>MB number of megabytes\n"
1131 " <nn>G or <nn>GB number of gigabytes\n"
1132 " <nn>T or <nn>TB number of terabytes\n"
1133 " <nn>P or <nn>PB number of petabytes\n"
1134 " <nn>E or <nn>EB number of exabytes\n"
1135 " <nn>sects number of 512 byte sectors\n"));
1136 else if (STRCASEEQ (cmd, "time"))
1137 printf (_("time - measure time taken to run command\n"
1138 " time <command> [<args> ...]\n"
1140 " This runs <command> as usual, and prints the elapsed\n"
1141 " time afterwards.\n"));
1143 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1147 /* This is printed when the user types in an unknown command for the
1148 * first command issued. A common case is the user doing:
1149 * guestfish disk.img
1150 * expecting guestfish to open 'disk.img' (in fact, this tried to
1151 * run a command 'disk.img').
1154 extended_help_message (void)
1157 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1158 "For a list of commands: guestfish -h\n"
1159 "For complete documentation: man guestfish\n"));
1163 free_strings (char **argv)
1167 for (argc = 0; argv[argc] != NULL; ++argc)
1173 count_strings (char *const *argv)
1177 for (c = 0; argv[c]; ++c)
1183 print_strings (char *const *argv)
1187 for (argc = 0; argv[argc] != NULL; ++argc)
1188 printf ("%s\n", argv[argc]);
1192 print_table (char *const *argv)
1196 for (i = 0; argv[i] != NULL; i += 2)
1197 printf ("%s: %s\n", argv[i], argv[i+1]);
1201 is_true (const char *str)
1204 STRCASENEQ (str, "0") &&
1205 STRCASENEQ (str, "f") &&
1206 STRCASENEQ (str, "false") &&
1207 STRCASENEQ (str, "n") &&
1208 STRCASENEQ (str, "no");
1211 /* Free strings from a non-NULL terminated char** */
1213 free_n_strings (char **str, size_t len)
1217 for (i = 0; i < len; i++) {
1224 parse_string_list (const char *str)
1227 size_t argv_len = 0;
1229 /* Current position pointer */
1230 const char *p = str;
1232 /* Token might be simple:
1235 * 'This is a single token'
1236 * or contain embedded single-quoted sections:
1237 * This' is a sing'l'e to'ken
1239 * The latter may seem over-complicated, but it's what a normal shell does.
1240 * Not doing it risks surprising somebody.
1242 * This outer loop is over complete tokens.
1248 /* Skip leading whitespace */
1249 p += strspn (p, " \t");
1253 /* This loop is over token 'fragments'. A token can be in multiple bits if
1254 * it contains single quotes. We also treat both sides of an escaped quote
1255 * as separate fragments because we can't just copy it: we have to remove
1258 while (*p && (!c_isblank (*p) || in_quote)) {
1259 const char *end = p;
1261 /* Check if the fragment starts with a quote */
1263 /* Toggle in_quote */
1264 in_quote = !in_quote;
1266 /* Skip the quote */
1270 /* If we're in a quote, look for an end quote */
1272 end += strcspn (end, "'");
1275 /* Otherwise, look for whitespace or a quote */
1277 end += strcspn (end, " \t'");
1280 /* Grow the token to accommodate the fragment */
1281 size_t tok_end = tok_len;
1283 char *tok_new = realloc (tok, tok_len + 1);
1284 if (NULL == tok_new) {
1286 free_n_strings (argv, argv_len);
1288 exit (EXIT_FAILURE);
1292 /* Check if we stopped on an escaped quote */
1293 if ('\'' == *end && end != p && *(end-1) == '\\') {
1294 /* Add everything before \' to the token */
1295 memcpy (&tok[tok_end], p, end - p - 1);
1298 tok[tok_len-1] = '\'';
1300 /* Already processed the quote */
1305 /* Add the whole fragment */
1306 memcpy (&tok[tok_end], p, end - p);
1312 /* We've reached the end of a token. We shouldn't still be in quotes. */
1314 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1316 free_n_strings (argv, argv_len);
1321 /* Add this token if there is one. There might not be if there was
1322 * whitespace at the end of the input string */
1324 /* Add the NULL terminator */
1325 tok[tok_len] = '\0';
1327 /* Add the argument to the argument list */
1329 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1330 if (NULL == argv_new) {
1332 free_n_strings (argv, argv_len-1);
1334 exit (EXIT_FAILURE);
1338 argv[argv_len-1] = tok;
1342 /* NULL terminate the argument list */
1344 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1345 if (NULL == argv_new) {
1347 free_n_strings (argv, argv_len-1);
1348 exit (EXIT_FAILURE);
1352 argv[argv_len-1] = NULL;
1357 #ifdef HAVE_LIBREADLINE
1358 static char histfile[1024];
1359 static int nr_history_lines = 0;
1363 initialize_readline (void)
1365 #ifdef HAVE_LIBREADLINE
1368 home = getenv ("HOME");
1370 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1372 (void) read_history (histfile);
1375 rl_readline_name = "guestfish";
1376 rl_attempted_completion_function = do_completion;
1381 cleanup_readline (void)
1383 #ifdef HAVE_LIBREADLINE
1386 if (histfile[0] != '\0') {
1387 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1394 #ifdef HAVE_APPEND_HISTORY
1395 (void) append_history (nr_history_lines, histfile);
1397 (void) write_history (histfile);
1404 add_history_line (const char *line)
1406 #ifdef HAVE_LIBREADLINE
1413 xwrite (int fd, const void *v_buf, size_t len)
1416 const char *buf = v_buf;
1419 r = write (fd, buf, len);
1431 /* Resolve the special "win:..." form for Windows-specific paths.
1432 * This always returns a newly allocated string which is freed by the
1433 * caller function in "cmds.c".
1436 resolve_win_path (const char *path)
1441 if (STRCASENEQLEN (path, "win:", 4)) {
1442 ret = strdup (path);
1450 /* Drop drive letter, if it's "C:". */
1451 if (STRCASEEQLEN (path, "c:", 2))
1461 ret = strdup (path);
1467 /* Blindly convert any backslashes into forward slashes. Is this good? */
1468 for (i = 0; i < strlen (ret); ++i)
1472 char *t = guestfs_case_sensitive_path (g, ret);
1479 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1480 * The caller (cmds.c) will call free_file_in after the command has
1481 * run which should clean up resources.
1483 static char *file_in_heredoc (const char *endmarker);
1484 static char *file_in_tmpfile = NULL;
1487 file_in (const char *arg)
1491 if (STREQ (arg, "-")) {
1492 ret = strdup ("/dev/stdin");
1498 else if (STRPREFIX (arg, "-<<")) {
1499 const char *endmarker = &arg[3];
1500 if (*endmarker == '\0') {
1501 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1505 ret = file_in_heredoc (endmarker);
1521 file_in_heredoc (const char *endmarker)
1523 static const char template[] = "/tmp/heredocXXXXXX";
1524 file_in_tmpfile = strdup (template);
1525 if (file_in_tmpfile == NULL) {
1530 int fd = mkstemp (file_in_tmpfile);
1536 size_t markerlen = strlen (endmarker);
1538 char buffer[BUFSIZ];
1539 int write_error = 0;
1540 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1541 /* Look for "END"<EOF> or "END\n" in input. */
1542 size_t blen = strlen (buffer);
1543 if (STREQLEN (buffer, endmarker, markerlen) &&
1544 (blen == markerlen ||
1545 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1548 if (xwrite (fd, buffer, blen) == -1) {
1549 if (!write_error) perror ("write");
1551 /* continue reading up to the end marker */
1555 /* Reached EOF of stdin without finding the end marker, which
1556 * is likely to be an error.
1558 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1559 program_name, endmarker);
1568 if (close (fd) == -1) {
1573 return file_in_tmpfile;
1576 unlink (file_in_tmpfile);
1579 free (file_in_tmpfile);
1580 file_in_tmpfile = NULL;
1585 free_file_in (char *s)
1587 if (file_in_tmpfile) {
1588 if (unlink (file_in_tmpfile) == -1)
1589 perror (file_in_tmpfile);
1590 file_in_tmpfile = NULL;
1593 /* Free the device or file name which was strdup'd in file_in().
1594 * Note it's not immediately clear, but for -<< heredocs,
1595 * s == file_in_tmpfile, so this frees up that buffer.
1600 /* Resolve the special FileOut paths ("-" or filename).
1601 * The caller (cmds.c) will call free (str) after the command has run.
1604 file_out (const char *arg)
1608 if (STREQ (arg, "-"))
1609 ret = strdup ("/dev/stdout");