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 void interactive (void);
62 static void shell_script (void);
63 static void script (int prompt);
64 static void cmdline (char *argv[], int optind, int argc);
65 static void initialize_readline (void);
66 static void cleanup_readline (void);
67 static void add_history_line (const char *);
69 /* Currently open libguestfs handle. */
75 int echo_commands = 0;
76 int remote_control_listen = 0;
77 int remote_control = 0;
78 int exit_on_error = 1;
82 launch (guestfs_h *_g)
86 if (guestfs_is_config (g)) {
87 if (guestfs_launch (g) == -1)
93 static void __attribute__((noreturn))
96 if (status != EXIT_SUCCESS)
97 fprintf (stderr, _("Try `%s --help' for more information.\n"),
101 _("%s: guest filesystem shell\n"
102 "%s lets you edit virtual machine filesystems\n"
103 "Copyright (C) 2009 Red Hat Inc.\n"
105 " %s [--options] cmd [: cmd : cmd ...]\n"
106 " %s -i libvirt-domain\n"
107 " %s -i disk-image(s)\n"
108 "or for interactive use:\n"
110 "or from a shell script:\n"
116 " -h|--cmd-help List available commands\n"
117 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
118 " -a|--add image Add image\n"
119 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
120 " -f|--file file Read commands from file\n"
121 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
122 " --listen Listen for remote commands\n"
123 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
124 " -n|--no-sync Don't autosync\n"
125 " -N|--new type Create prepared disk (test1.img, ...)\n"
126 " --remote[=pid] Send commands to remote %s\n"
127 " -r|--ro Mount read-only\n"
128 " --selinux Enable SELinux support\n"
129 " -v|--verbose Verbose messages\n"
130 " -x Echo each command before executing it\n"
131 " -V|--version Display version and exit\n"
132 "For more information, see the manpage %s(1).\n"),
133 program_name, program_name, program_name,
134 program_name, program_name, program_name,
135 program_name, program_name, program_name);
141 main (int argc, char *argv[])
143 /* Set global program name that is not polluted with libtool artifacts. */
144 set_program_name (argv[0]);
146 atexit (close_stdout);
148 setlocale (LC_ALL, "");
149 bindtextdomain (PACKAGE, LOCALEBASEDIR);
150 textdomain (PACKAGE);
152 enum { HELP_OPTION = CHAR_MAX + 1 };
154 static const char *options = "a:Df:h::im:nN:rv?Vx";
155 static const struct option long_options[] = {
156 { "add", 1, 0, 'a' },
157 { "cmd-help", 2, 0, 'h' },
158 { "file", 1, 0, 'f' },
159 { "help", 0, 0, HELP_OPTION },
160 { "inspector", 0, 0, 'i' },
161 { "listen", 0, 0, 0 },
162 { "mount", 1, 0, 'm' },
163 { "new", 1, 0, 'N' },
164 { "no-dest-paths", 0, 0, 'D' },
165 { "no-sync", 0, 0, 'n' },
166 { "remote", 2, 0, 0 },
168 { "selinux", 0, 0, 0 },
169 { "verbose", 0, 0, 'v' },
170 { "version", 0, 0, 'V' },
173 struct drv *drvs = NULL;
175 struct mp *mps = NULL;
177 char *p, *file = NULL;
182 char next_drive = 'a';
183 int next_prepared_drive = 1;
185 initialize_readline ();
187 memset (&sa, 0, sizeof sa);
188 sa.sa_handler = SIG_IGN;
189 sa.sa_flags = SA_RESTART;
190 sigaction (SIGPIPE, &sa, NULL);
192 /* guestfs_create is meant to be a lightweight operation, so
193 * it's OK to do it early here.
195 g = guestfs_create ();
197 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
201 guestfs_set_autosync (g, 1);
203 /* If developing, add ./appliance to the path. Note that libtools
204 * interferes with this because uninstalled guestfish is a shell
205 * script that runs the real program with an absolute path. Detect
208 * BUT if LIBGUESTFS_PATH environment variable is already set by
209 * the user, then don't override it.
211 if (getenv ("LIBGUESTFS_PATH") == NULL &&
213 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
214 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
216 /* CAUTION: we are careful to modify argv[0] here, only after
217 * using it just above.
219 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
220 * of the original, in case it's needed in virt-inspector mode, below.
222 char *real_argv0 = argv[0];
223 argv[0] = bad_cast (program_name);
226 c = getopt_long (argc, argv, options, long_options, &option_index);
230 case 0: /* options which are long only */
231 if (STREQ (long_options[option_index].name, "listen"))
232 remote_control_listen = 1;
233 else if (STREQ (long_options[option_index].name, "remote")) {
235 if (sscanf (optarg, "%d", &remote_control) != 1) {
236 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
237 program_name, optarg);
241 p = getenv ("GUESTFISH_PID");
242 if (!p || sscanf (p, "%d", &remote_control) != 1) {
243 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
244 " to the PID of the remote process\n"),
249 } else if (STREQ (long_options[option_index].name, "selinux")) {
250 guestfs_set_selinux (g, 1);
252 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
253 program_name, long_options[option_index].name, option_index);
259 if (access (optarg, R_OK) != 0) {
263 drv = malloc (sizeof (struct drv));
268 drv->filename = optarg;
270 /* We could fill the device field in, but in fact we
271 * only use it for the -N option at present.
280 if (STRCASEEQ (optarg, "list")) {
281 list_prepared_drives ();
284 drv = malloc (sizeof (struct drv));
289 if (asprintf (&drv->filename, "test%d.img",
290 next_prepared_drive++) == -1) {
294 drv->data = create_prepared_file (optarg, drv->filename);
295 if (asprintf (&drv->device, "/dev/sd%c", next_drive++) == -1) {
304 complete_dest_paths = 0;
309 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
318 display_command (optarg);
319 else if (argv[optind] && argv[optind][0] != '-')
320 display_command (argv[optind++]);
330 mp = malloc (sizeof (struct mp));
335 p = strchr (optarg, ':');
338 mp->mountpoint = p+1;
340 mp->mountpoint = bad_cast ("/");
347 guestfs_set_autosync (g, 0);
356 guestfs_set_verbose (g, verbose);
360 printf ("%s %s\n", program_name, PACKAGE_VERSION);
368 usage (EXIT_SUCCESS);
371 usage (EXIT_FAILURE);
375 /* Inspector mode invalidates most of the other arguments. */
380 if (drvs || mps || remote_control_listen || remote_control ||
381 guestfs_get_selinux (g)) {
382 fprintf (stderr, _("%s: cannot use -i option with -a, -m, -N, "
383 "--listen, --remote or --selinux\n"),
387 if (optind >= argc) {
389 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
394 strcpy (cmd, "a=`virt-inspector");
395 while (optind < argc) {
396 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
399 _("%s: virt-inspector command too long for fixed-size buffer\n"),
404 strcat (cmd, argv[optind]);
410 strcat (cmd, " --ro-fish");
412 strcat (cmd, " --fish");
414 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
416 if (guestfs_get_verbose (g))
418 if (!guestfs_get_autosync (g))
423 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
430 exit (WEXITSTATUS (r));
433 /* If we've got drives to add, add them now. */
436 /* If we've got mountpoints or prepared drives, we must launch the
437 * guest and mount them.
439 if (next_prepared_drive > 1 || mps != NULL) {
440 if (launch (g) == -1) exit (EXIT_FAILURE);
441 prepare_drives (drvs);
445 /* Remote control? */
446 if (remote_control_listen && remote_control) {
448 _("%s: cannot use --listen and --remote options at the same time\n"),
453 if (remote_control_listen) {
456 _("%s: extra parameters on the command line with --listen flag\n"),
462 _("%s: cannot use --listen and --file options at the same time\n"),
469 /* -f (file) parameter? */
472 if (open (file, O_RDONLY) == -1) {
478 /* Interactive, shell script, or command(s) on the command line? */
479 if (optind >= argc) {
486 cmdline (argv, optind, argc);
494 pod2text (const char *name, const char *shortdesc, const char *str)
498 fp = popen ("pod2text", "w");
500 /* pod2text failed, maybe not found, so let's just print the
501 * source instead, since that's better than doing nothing.
503 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
506 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
511 /* List is built in reverse order, so mount them in reverse order. */
513 mount_mps (struct mp *mp)
518 mount_mps (mp->next);
520 /* Don't use guestfs_mount here because that will default to mount
521 * options -o sync,noatime. For more information, see guestfs(3)
522 * section "LIBGUESTFS GOTCHAS".
524 const char *options = read_only ? "ro" : "";
525 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
532 add_drives (struct drv *drv)
537 add_drives (drv->next);
539 if (drv->data /* -N option is not affected by --ro */ || !read_only)
540 r = guestfs_add_drive (g, drv->filename);
542 r = guestfs_add_drive_ro (g, drv->filename);
549 prepare_drives (struct drv *drv)
552 prepare_drives (drv->next);
554 prepare_drive (drv->filename, drv->data, drv->device);
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 help with commands\n"
626 " 'quit' to quit the shell\n"
632 exit_on_error = global_exit_on_error;
634 buf = rl_gets (prompt);
640 /* Skip any initial whitespace before the command. */
642 while (*buf && c_isspace (*buf))
647 /* If the next character is '#' then this is a comment. */
648 if (*buf == '#') continue;
650 /* If the next character is '!' then pass the whole lot to system(3). */
658 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
659 WEXITSTATUS (r) != 0)
665 /* If the next character is '-' allow the command to fail without
666 * exiting on error (just for this one command though).
674 /* Get the command (cannot be quoted). */
675 len = strcspn (buf, " \t");
677 if (len == 0) continue;
681 if (buf[len] == '\0') {
688 p += strspn (p, " \t");
690 /* Get the parameters. */
691 while (*p && i < sizeof argv / sizeof argv[0]) {
694 /* Parameters which start with quotes or pipes are treated
695 * specially. Bare parameters are delimited by whitespace.
699 len = strcspn (p, "\"");
700 if (p[len] == '\0') {
701 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
702 if (exit_on_error) exit (EXIT_FAILURE);
705 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
707 _("%s: command arguments not separated by whitespace\n"),
709 if (exit_on_error) exit (EXIT_FAILURE);
713 pend = p[len+1] ? &p[len+2] : &p[len+1];
714 } else if (*p == '\'') {
716 len = strcspn (p, "'");
717 if (p[len] == '\0') {
718 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
719 if (exit_on_error) exit (EXIT_FAILURE);
722 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
724 _("%s: command arguments not separated by whitespace\n"),
726 if (exit_on_error) exit (EXIT_FAILURE);
730 pend = p[len+1] ? &p[len+2] : &p[len+1];
731 } else if (*p == '|') {
736 } else if (*p == '[') {
740 while (*pend && c != 0) {
741 if (*pend == '[') c++;
742 else if (*pend == ']') c--;
747 _("%s: unterminated \"[...]\" sequence\n"), program_name);
748 if (exit_on_error) exit (EXIT_FAILURE);
751 if (*pend && (*pend != ' ' && *pend != '\t')) {
753 _("%s: command arguments not separated by whitespace\n"),
755 if (exit_on_error) exit (EXIT_FAILURE);
760 } else if (*p != ' ' && *p != '\t') {
761 /* If the first character is a ~ then note that this parameter
762 * is a candidate for ~username expansion. NB this does not
763 * apply to quoted parameters.
765 tilde_candidate = *p == '~';
766 len = strcspn (p, " \t");
773 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
778 if (!tilde_candidate)
781 argv[i] = try_tilde_expansion (p);
786 p += strspn (p, " \t");
789 if (i == sizeof argv / sizeof argv[0]) {
790 fprintf (stderr, _("%s: too many arguments\n"), program_name);
791 if (exit_on_error) exit (EXIT_FAILURE);
798 if (issue_command (cmd, argv, pipe) == -1) {
799 if (exit_on_error) exit (EXIT_FAILURE);
804 if (prompt) printf ("\n");
808 cmdline (char *argv[], int optind, int argc)
815 if (optind >= argc) return;
817 cmd = argv[optind++];
818 if (STREQ (cmd, ":")) {
819 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
823 /* Allow -cmd on the command line to mean (temporarily) override
824 * the normal exit on error (RHBZ#578407).
831 params = &argv[optind];
833 /* Search for end of command list or ":" ... */
834 while (optind < argc && STRNEQ (argv[optind], ":"))
837 if (optind == argc) {
838 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
842 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
844 cmdline (argv, optind+1, argc);
849 issue_command (const char *cmd, char *argv[], const char *pipecmd)
852 int stdout_saved_fd = -1;
856 /* This counts the commands issued, starting at 1. */
861 for (i = 0; argv[i] != NULL; ++i)
862 printf (" %s", argv[i]);
866 /* For | ... commands. Annoyingly we can't use popen(3) here. */
870 if (fflush (stdout) == EOF) {
871 perror ("failed to flush standard output");
875 perror ("pipe failed");
884 if (pid == 0) { /* Child process. */
886 if (dup2 (fd[0], 0) < 0) {
887 perror ("dup2 of stdin failed");
891 r = system (pipecmd);
896 _exit (WEXITSTATUS (r));
899 if ((stdout_saved_fd = dup (1)) < 0) {
900 perror ("failed to dup stdout");
904 if (dup2 (fd[1], 1) < 0) {
905 perror ("failed to dup stdout");
906 close (stdout_saved_fd);
912 for (argc = 0; argv[argc] != NULL; ++argc)
915 /* If --remote was set, then send this command to a remote process. */
917 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
919 /* Otherwise execute it locally. */
920 else if (STRCASEEQ (cmd, "help")) {
924 display_command (argv[0]);
927 else if (STRCASEEQ (cmd, "quit") ||
928 STRCASEEQ (cmd, "exit") ||
929 STRCASEEQ (cmd, "q")) {
933 else if (STRCASEEQ (cmd, "alloc") ||
934 STRCASEEQ (cmd, "allocate"))
935 r = do_alloc (cmd, argc, argv);
936 else if (STRCASEEQ (cmd, "echo"))
937 r = do_echo (cmd, argc, argv);
938 else if (STRCASEEQ (cmd, "edit") ||
939 STRCASEEQ (cmd, "vi") ||
940 STRCASEEQ (cmd, "emacs"))
941 r = do_edit (cmd, argc, argv);
942 else if (STRCASEEQ (cmd, "lcd"))
943 r = do_lcd (cmd, argc, argv);
944 else if (STRCASEEQ (cmd, "glob"))
945 r = do_glob (cmd, argc, argv);
946 else if (STRCASEEQ (cmd, "more") ||
947 STRCASEEQ (cmd, "less"))
948 r = do_more (cmd, argc, argv);
949 else if (STRCASEEQ (cmd, "reopen"))
950 r = do_reopen (cmd, argc, argv);
951 else if (STRCASEEQ (cmd, "sparse"))
952 r = do_sparse (cmd, argc, argv);
953 else if (STRCASEEQ (cmd, "time"))
954 r = do_time (cmd, argc, argv);
956 r = run_action (cmd, argc, argv);
958 /* Always flush stdout after every command, so that messages, results
959 * etc appear immediately.
961 if (fflush (stdout) == EOF) {
962 perror ("failed to flush standard output");
968 if (dup2 (stdout_saved_fd, 1) < 0) {
969 perror ("failed to dup2 standard output");
972 close (stdout_saved_fd);
973 if (waitpid (pid, NULL, 0) < 0) {
974 perror ("waiting for command to complete");
983 list_builtin_commands (void)
985 /* help and quit should appear at the top */
986 printf ("%-20s %s\n",
987 "help", _("display a list of commands or help on a command"));
988 printf ("%-20s %s\n",
989 "quit", _("quit guestfish"));
991 printf ("%-20s %s\n",
992 "alloc", _("allocate an image"));
993 printf ("%-20s %s\n",
994 "echo", _("display a line of text"));
995 printf ("%-20s %s\n",
996 "edit", _("edit a file in the image"));
997 printf ("%-20s %s\n",
998 "lcd", _("local change directory"));
999 printf ("%-20s %s\n",
1000 "glob", _("expand wildcards in command"));
1001 printf ("%-20s %s\n",
1002 "more", _("view a file in the pager"));
1003 printf ("%-20s %s\n",
1004 "reopen", _("close and reopen libguestfs handle"));
1005 printf ("%-20s %s\n",
1006 "sparse", _("allocate a sparse image file"));
1007 printf ("%-20s %s\n",
1008 "time", _("measure time taken to run command"));
1010 /* actions are printed after this (see list_commands) */
1014 display_builtin_command (const char *cmd)
1016 /* help for actions is auto-generated, see display_command */
1018 if (STRCASEEQ (cmd, "alloc") ||
1019 STRCASEEQ (cmd, "allocate"))
1020 printf (_("alloc - allocate an image\n"
1021 " alloc <filename> <size>\n"
1023 " This creates an empty (zeroed) file of the given size,\n"
1024 " and then adds so it can be further examined.\n"
1026 " For more advanced image creation, see qemu-img utility.\n"
1028 " Size can be specified (where <nn> means a number):\n"
1029 " <nn> number of kilobytes\n"
1030 " eg: 1440 standard 3.5\" floppy\n"
1031 " <nn>K or <nn>KB number of kilobytes\n"
1032 " <nn>M or <nn>MB number of megabytes\n"
1033 " <nn>G or <nn>GB number of gigabytes\n"
1034 " <nn>T or <nn>TB number of terabytes\n"
1035 " <nn>P or <nn>PB number of petabytes\n"
1036 " <nn>E or <nn>EB number of exabytes\n"
1037 " <nn>sects number of 512 byte sectors\n"));
1038 else if (STRCASEEQ (cmd, "echo"))
1039 printf (_("echo - display a line of text\n"
1040 " echo [<params> ...]\n"
1042 " This echos the parameters to the terminal.\n"));
1043 else if (STRCASEEQ (cmd, "edit") ||
1044 STRCASEEQ (cmd, "vi") ||
1045 STRCASEEQ (cmd, "emacs"))
1046 printf (_("edit - edit a file in the image\n"
1047 " edit <filename>\n"
1049 " This is used to edit a file.\n"
1051 " It is the equivalent of (and is implemented by)\n"
1052 " running \"cat\", editing locally, and then \"write-file\".\n"
1054 " Normally it uses $EDITOR, but if you use the aliases\n"
1055 " \"vi\" or \"emacs\" you will get those editors.\n"
1057 " NOTE: This will not work reliably for large files\n"
1058 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1059 else if (STRCASEEQ (cmd, "lcd"))
1060 printf (_("lcd - local change directory\n"
1061 " lcd <directory>\n"
1063 " Change guestfish's current directory. This command is\n"
1064 " useful if you want to download files to a particular\n"
1066 else if (STRCASEEQ (cmd, "glob"))
1067 printf (_("glob - expand wildcards in command\n"
1068 " glob <command> [<args> ...]\n"
1070 " Glob runs <command> with wildcards expanded in any\n"
1071 " command args. Note that the command is run repeatedly\n"
1072 " once for each expanded argument.\n"));
1073 else if (STRCASEEQ (cmd, "help"))
1074 printf (_("help - display a list of commands or help on a command\n"
1077 else if (STRCASEEQ (cmd, "more") ||
1078 STRCASEEQ (cmd, "less"))
1079 printf (_("more - view a file in the pager\n"
1080 " more <filename>\n"
1082 " This is used to view a file in the pager.\n"
1084 " It is the equivalent of (and is implemented by)\n"
1085 " running \"cat\" and using the pager.\n"
1087 " Normally it uses $PAGER, but if you use the alias\n"
1088 " \"less\" then it always uses \"less\".\n"
1090 " NOTE: This will not work reliably for large files\n"
1091 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1092 else if (STRCASEEQ (cmd, "quit") ||
1093 STRCASEEQ (cmd, "exit") ||
1094 STRCASEEQ (cmd, "q"))
1095 printf (_("quit - quit guestfish\n"
1097 else if (STRCASEEQ (cmd, "reopen"))
1098 printf (_("reopen - close and reopen the libguestfs handle\n"
1101 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1102 "this normally, because the handle is closed properly when guestfish\n"
1103 "exits. However this is occasionally useful for testing.\n"));
1104 else if (STRCASEEQ (cmd, "sparse"))
1105 printf (_("sparse - allocate a sparse image file\n"
1106 " sparse <filename> <size>\n"
1108 " This creates an empty sparse file of the given size,\n"
1109 " and then adds so it can be further examined.\n"
1111 " In all respects it works the same as the 'alloc'\n"
1112 " command, except that the image file is allocated\n"
1113 " sparsely, which means that disk blocks are not assigned\n"
1114 " to the file until they are needed. Sparse disk files\n"
1115 " only use space when written to, but they are slower\n"
1116 " and there is a danger you could run out of real disk\n"
1117 " space during a write operation.\n"
1119 " For more advanced image creation, see qemu-img utility.\n"
1121 " Size can be specified (where <nn> means a number):\n"
1122 " <nn> number of kilobytes\n"
1123 " eg: 1440 standard 3.5\" floppy\n"
1124 " <nn>K or <nn>KB number of kilobytes\n"
1125 " <nn>M or <nn>MB number of megabytes\n"
1126 " <nn>G or <nn>GB number of gigabytes\n"
1127 " <nn>T or <nn>TB number of terabytes\n"
1128 " <nn>P or <nn>PB number of petabytes\n"
1129 " <nn>E or <nn>EB number of exabytes\n"
1130 " <nn>sects number of 512 byte sectors\n"));
1131 else if (STRCASEEQ (cmd, "time"))
1132 printf (_("time - measure time taken to run command\n"
1133 " time <command> [<args> ...]\n"
1135 " This runs <command> as usual, and prints the elapsed\n"
1136 " time afterwards.\n"));
1138 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1142 /* This is printed when the user types in an unknown command for the
1143 * first command issued. A common case is the user doing:
1144 * guestfish disk.img
1145 * expecting guestfish to open 'disk.img' (in fact, this tried to
1146 * run a command 'disk.img').
1149 extended_help_message (void)
1152 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1153 "For a list of commands: guestfish -h\n"
1154 "For complete documentation: man guestfish\n"));
1158 free_strings (char **argv)
1162 for (argc = 0; argv[argc] != NULL; ++argc)
1168 count_strings (char *const *argv)
1172 for (c = 0; argv[c]; ++c)
1178 print_strings (char *const *argv)
1182 for (argc = 0; argv[argc] != NULL; ++argc)
1183 printf ("%s\n", argv[argc]);
1187 print_table (char *const *argv)
1191 for (i = 0; argv[i] != NULL; i += 2)
1192 printf ("%s: %s\n", argv[i], argv[i+1]);
1196 is_true (const char *str)
1199 STRCASENEQ (str, "0") &&
1200 STRCASENEQ (str, "f") &&
1201 STRCASENEQ (str, "false") &&
1202 STRCASENEQ (str, "n") &&
1203 STRCASENEQ (str, "no");
1206 /* Free strings from a non-NULL terminated char** */
1208 free_n_strings (char **str, size_t len)
1212 for (i = 0; i < len; i++) {
1219 parse_string_list (const char *str)
1222 size_t argv_len = 0;
1224 /* Current position pointer */
1225 const char *p = str;
1227 /* Token might be simple:
1230 * 'This is a single token'
1231 * or contain embedded single-quoted sections:
1232 * This' is a sing'l'e to'ken
1234 * The latter may seem over-complicated, but it's what a normal shell does.
1235 * Not doing it risks surprising somebody.
1237 * This outer loop is over complete tokens.
1243 /* Skip leading whitespace */
1244 p += strspn (p, " \t");
1248 /* This loop is over token 'fragments'. A token can be in multiple bits if
1249 * it contains single quotes. We also treat both sides of an escaped quote
1250 * as separate fragments because we can't just copy it: we have to remove
1253 while (*p && (!c_isblank (*p) || in_quote)) {
1254 const char *end = p;
1256 /* Check if the fragment starts with a quote */
1258 /* Toggle in_quote */
1259 in_quote = !in_quote;
1261 /* Skip the quote */
1265 /* If we're in a quote, look for an end quote */
1267 end += strcspn (end, "'");
1270 /* Otherwise, look for whitespace or a quote */
1272 end += strcspn (end, " \t'");
1275 /* Grow the token to accommodate the fragment */
1276 size_t tok_end = tok_len;
1278 char *tok_new = realloc (tok, tok_len + 1);
1279 if (NULL == tok_new) {
1281 free_n_strings (argv, argv_len);
1283 exit (EXIT_FAILURE);
1287 /* Check if we stopped on an escaped quote */
1288 if ('\'' == *end && end != p && *(end-1) == '\\') {
1289 /* Add everything before \' to the token */
1290 memcpy (&tok[tok_end], p, end - p - 1);
1293 tok[tok_len-1] = '\'';
1295 /* Already processed the quote */
1300 /* Add the whole fragment */
1301 memcpy (&tok[tok_end], p, end - p);
1307 /* We've reached the end of a token. We shouldn't still be in quotes. */
1309 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1311 free_n_strings (argv, argv_len);
1316 /* Add this token if there is one. There might not be if there was
1317 * whitespace at the end of the input string */
1319 /* Add the NULL terminator */
1320 tok[tok_len] = '\0';
1322 /* Add the argument to the argument list */
1324 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1325 if (NULL == argv_new) {
1327 free_n_strings (argv, argv_len-1);
1329 exit (EXIT_FAILURE);
1333 argv[argv_len-1] = tok;
1337 /* NULL terminate the argument list */
1339 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1340 if (NULL == argv_new) {
1342 free_n_strings (argv, argv_len-1);
1343 exit (EXIT_FAILURE);
1347 argv[argv_len-1] = NULL;
1352 #ifdef HAVE_LIBREADLINE
1353 static char histfile[1024];
1354 static int nr_history_lines = 0;
1358 initialize_readline (void)
1360 #ifdef HAVE_LIBREADLINE
1363 home = getenv ("HOME");
1365 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1367 (void) read_history (histfile);
1370 rl_readline_name = "guestfish";
1371 rl_attempted_completion_function = do_completion;
1376 cleanup_readline (void)
1378 #ifdef HAVE_LIBREADLINE
1381 if (histfile[0] != '\0') {
1382 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1389 #ifdef HAVE_APPEND_HISTORY
1390 (void) append_history (nr_history_lines, histfile);
1392 (void) write_history (histfile);
1399 add_history_line (const char *line)
1401 #ifdef HAVE_LIBREADLINE
1408 xwrite (int fd, const void *v_buf, size_t len)
1411 const char *buf = v_buf;
1414 r = write (fd, buf, len);
1426 /* Resolve the special "win:..." form for Windows-specific paths.
1427 * This always returns a newly allocated string which is freed by the
1428 * caller function in "cmds.c".
1431 resolve_win_path (const char *path)
1436 if (STRCASENEQLEN (path, "win:", 4)) {
1437 ret = strdup (path);
1445 /* Drop drive letter, if it's "C:". */
1446 if (STRCASEEQLEN (path, "c:", 2))
1456 ret = strdup (path);
1462 /* Blindly convert any backslashes into forward slashes. Is this good? */
1463 for (i = 0; i < strlen (ret); ++i)
1467 char *t = guestfs_case_sensitive_path (g, ret);
1474 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1475 * The caller (cmds.c) will call free_file_in after the command has
1476 * run which should clean up resources.
1478 static char *file_in_heredoc (const char *endmarker);
1479 static char *file_in_tmpfile = NULL;
1482 file_in (const char *arg)
1486 if (STREQ (arg, "-")) {
1487 ret = strdup ("/dev/stdin");
1493 else if (STRPREFIX (arg, "-<<")) {
1494 const char *endmarker = &arg[3];
1495 if (*endmarker == '\0') {
1496 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1500 ret = file_in_heredoc (endmarker);
1516 file_in_heredoc (const char *endmarker)
1518 static const char template[] = "/tmp/heredocXXXXXX";
1519 file_in_tmpfile = strdup (template);
1520 if (file_in_tmpfile == NULL) {
1525 int fd = mkstemp (file_in_tmpfile);
1531 size_t markerlen = strlen (endmarker);
1533 char buffer[BUFSIZ];
1534 int write_error = 0;
1535 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1536 /* Look for "END"<EOF> or "END\n" in input. */
1537 size_t blen = strlen (buffer);
1538 if (STREQLEN (buffer, endmarker, markerlen) &&
1539 (blen == markerlen ||
1540 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1543 if (xwrite (fd, buffer, blen) == -1) {
1544 if (!write_error) perror ("write");
1546 /* continue reading up to the end marker */
1550 /* Reached EOF of stdin without finding the end marker, which
1551 * is likely to be an error.
1553 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1554 program_name, endmarker);
1563 if (close (fd) == -1) {
1568 return file_in_tmpfile;
1571 unlink (file_in_tmpfile);
1574 free (file_in_tmpfile);
1575 file_in_tmpfile = NULL;
1580 free_file_in (char *s)
1582 if (file_in_tmpfile) {
1583 if (unlink (file_in_tmpfile) == -1)
1584 perror (file_in_tmpfile);
1585 file_in_tmpfile = NULL;
1588 /* Free the device or file name which was strdup'd in file_in().
1589 * Note it's not immediately clear, but for -<< heredocs,
1590 * s == file_in_tmpfile, so this frees up that buffer.
1595 /* Resolve the special FileOut paths ("-" or filename).
1596 * The caller (cmds.c) will call free (str) after the command has run.
1599 file_out (const char *arg)
1603 if (STREQ (arg, "-"))
1604 ret = strdup ("/dev/stdout");