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 remote_control_listen = 0;
76 int remote_control = 0;
77 int exit_on_error = 1;
81 launch (guestfs_h *_g)
85 if (guestfs_is_config (g)) {
86 if (guestfs_launch (g) == -1)
92 static void __attribute__((noreturn))
95 if (status != EXIT_SUCCESS)
96 fprintf (stderr, _("Try `%s --help' for more information.\n"),
100 _("%s: guest filesystem shell\n"
101 "%s lets you edit virtual machine filesystems\n"
102 "Copyright (C) 2009 Red Hat Inc.\n"
104 " %s [--options] cmd [: cmd : cmd ...]\n"
105 " %s -i libvirt-domain\n"
106 " %s -i disk-image(s)\n"
107 "or for interactive use:\n"
109 "or from a shell script:\n"
115 " -h|--cmd-help List available commands\n"
116 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
117 " -a|--add image Add image\n"
118 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
119 " -f|--file file Read commands from file\n"
120 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
121 " --listen Listen for remote commands\n"
122 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
123 " -n|--no-sync Don't autosync\n"
124 " -N|--new type Create prepared disk (test1.img, ...)\n"
125 " --remote[=pid] Send commands to remote %s\n"
126 " -r|--ro Mount read-only\n"
127 " --selinux Enable SELinux support\n"
128 " -v|--verbose Verbose messages\n"
129 " -x Echo each command before executing it\n"
130 " -V|--version Display version and exit\n"
131 "For more information, see the manpage %s(1).\n"),
132 program_name, program_name, program_name,
133 program_name, program_name, program_name,
134 program_name, program_name, program_name);
140 main (int argc, char *argv[])
142 /* Set global program name that is not polluted with libtool artifacts. */
143 set_program_name (argv[0]);
145 atexit (close_stdout);
147 setlocale (LC_ALL, "");
148 bindtextdomain (PACKAGE, LOCALEBASEDIR);
149 textdomain (PACKAGE);
151 enum { HELP_OPTION = CHAR_MAX + 1 };
153 static const char *options = "a:Df:h::im:nN:rv?Vx";
154 static const struct option long_options[] = {
155 { "add", 1, 0, 'a' },
156 { "cmd-help", 2, 0, 'h' },
157 { "file", 1, 0, 'f' },
158 { "help", 0, 0, HELP_OPTION },
159 { "inspector", 0, 0, 'i' },
160 { "listen", 0, 0, 0 },
161 { "mount", 1, 0, 'm' },
162 { "new", 1, 0, 'N' },
163 { "no-dest-paths", 0, 0, 'D' },
164 { "no-sync", 0, 0, 'n' },
165 { "remote", 2, 0, 0 },
167 { "selinux", 0, 0, 0 },
168 { "verbose", 0, 0, 'v' },
169 { "version", 0, 0, 'V' },
172 struct drv *drvs = NULL;
174 struct mp *mps = NULL;
176 char *p, *file = NULL;
181 char next_drive = 'a';
182 int next_prepared_drive = 1;
184 initialize_readline ();
186 memset (&sa, 0, sizeof sa);
187 sa.sa_handler = SIG_IGN;
188 sa.sa_flags = SA_RESTART;
189 sigaction (SIGPIPE, &sa, NULL);
191 /* guestfs_create is meant to be a lightweight operation, so
192 * it's OK to do it early here.
194 g = guestfs_create ();
196 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
200 guestfs_set_autosync (g, 1);
202 /* If developing, add ./appliance to the path. Note that libtools
203 * interferes with this because uninstalled guestfish is a shell
204 * script that runs the real program with an absolute path. Detect
207 * BUT if LIBGUESTFS_PATH environment variable is already set by
208 * the user, then don't override it.
210 if (getenv ("LIBGUESTFS_PATH") == NULL &&
212 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
213 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
215 /* CAUTION: we are careful to modify argv[0] here, only after
216 * using it just above.
218 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
219 * of the original, in case it's needed in virt-inspector mode, below.
221 char *real_argv0 = argv[0];
222 argv[0] = bad_cast (program_name);
225 c = getopt_long (argc, argv, options, long_options, &option_index);
229 case 0: /* options which are long only */
230 if (STREQ (long_options[option_index].name, "listen"))
231 remote_control_listen = 1;
232 else if (STREQ (long_options[option_index].name, "remote")) {
234 if (sscanf (optarg, "%d", &remote_control) != 1) {
235 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
236 program_name, optarg);
240 p = getenv ("GUESTFISH_PID");
241 if (!p || sscanf (p, "%d", &remote_control) != 1) {
242 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
243 " to the PID of the remote process\n"),
248 } else if (STREQ (long_options[option_index].name, "selinux")) {
249 guestfs_set_selinux (g, 1);
251 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
252 program_name, long_options[option_index].name, option_index);
258 if (access (optarg, R_OK) != 0) {
262 drv = malloc (sizeof (struct drv));
267 drv->filename = optarg;
269 /* We could fill the device field in, but in fact we
270 * only use it for the -N option at present.
279 if (STRCASEEQ (optarg, "list")) {
280 list_prepared_drives ();
283 drv = malloc (sizeof (struct drv));
288 if (asprintf (&drv->filename, "test%d.img",
289 next_prepared_drive++) == -1) {
293 drv->data = create_prepared_file (optarg, drv->filename);
294 if (asprintf (&drv->device, "/dev/sd%c", next_drive++) == -1) {
303 complete_dest_paths = 0;
308 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
317 display_command (optarg);
318 else if (argv[optind] && argv[optind][0] != '-')
319 display_command (argv[optind++]);
329 mp = malloc (sizeof (struct mp));
334 p = strchr (optarg, ':');
337 mp->mountpoint = p+1;
339 mp->mountpoint = bad_cast ("/");
346 guestfs_set_autosync (g, 0);
355 guestfs_set_verbose (g, verbose);
359 printf ("%s %s\n", program_name, PACKAGE_VERSION);
363 guestfs_set_trace (g, 1);
367 usage (EXIT_SUCCESS);
370 usage (EXIT_FAILURE);
374 /* Inspector mode invalidates most of the other arguments. */
379 if (drvs || mps || remote_control_listen || remote_control ||
380 guestfs_get_selinux (g)) {
381 fprintf (stderr, _("%s: cannot use -i option with -a, -m, -N, "
382 "--listen, --remote or --selinux\n"),
386 if (optind >= argc) {
388 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
393 strcpy (cmd, "a=`virt-inspector");
394 while (optind < argc) {
395 if (strlen (cmd) + strlen (argv[optind]) + strlen (real_argv0) + 60
398 _("%s: virt-inspector command too long for fixed-size buffer\n"),
403 strcat (cmd, argv[optind]);
409 strcat (cmd, " --ro-fish");
411 strcat (cmd, " --fish");
413 sprintf (&cmd[strlen(cmd)], "` && %s $a", real_argv0);
415 if (guestfs_get_verbose (g))
417 if (!guestfs_get_autosync (g))
422 "%s -i: running virt-inspector command:\n%s\n", program_name, cmd);
429 exit (WEXITSTATUS (r));
432 /* If we've got drives to add, add them now. */
435 /* If we've got mountpoints or prepared drives, we must launch the
436 * guest and mount them.
438 if (next_prepared_drive > 1 || mps != NULL) {
439 if (launch (g) == -1) exit (EXIT_FAILURE);
440 prepare_drives (drvs);
444 /* Remote control? */
445 if (remote_control_listen && remote_control) {
447 _("%s: cannot use --listen and --remote options at the same time\n"),
452 if (remote_control_listen) {
455 _("%s: extra parameters on the command line with --listen flag\n"),
461 _("%s: cannot use --listen and --file options at the same time\n"),
468 /* -f (file) parameter? */
471 if (open (file, O_RDONLY) == -1) {
477 /* Interactive, shell script, or command(s) on the command line? */
478 if (optind >= argc) {
485 cmdline (argv, optind, argc);
493 pod2text (const char *name, const char *shortdesc, const char *str)
497 fp = popen ("pod2text", "w");
499 /* pod2text failed, maybe not found, so let's just print the
500 * source instead, since that's better than doing nothing.
502 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
505 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
510 /* List is built in reverse order, so mount them in reverse order. */
512 mount_mps (struct mp *mp)
517 mount_mps (mp->next);
519 /* Don't use guestfs_mount here because that will default to mount
520 * options -o sync,noatime. For more information, see guestfs(3)
521 * section "LIBGUESTFS GOTCHAS".
523 const char *options = read_only ? "ro" : "";
524 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
531 add_drives (struct drv *drv)
536 add_drives (drv->next);
538 if (drv->data /* -N option is not affected by --ro */ || !read_only)
539 r = guestfs_add_drive (g, drv->filename);
541 r = guestfs_add_drive_ro (g, drv->filename);
548 prepare_drives (struct drv *drv)
551 prepare_drives (drv->next);
553 prepare_drive (drv->filename, drv->data, drv->device);
569 #define FISH "><fs> "
571 static char *line_read = NULL;
576 #ifdef HAVE_LIBREADLINE
584 line_read = readline (prompt ? FISH : "");
586 if (line_read && *line_read)
587 add_history_line (line_read);
592 #endif /* HAVE_LIBREADLINE */
594 static char buf[8192];
597 if (prompt) printf (FISH);
598 line_read = fgets (buf, sizeof buf, stdin);
601 len = strlen (line_read);
602 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
616 int global_exit_on_error = !prompt;
621 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
622 "editing virtual machine filesystems.\n"
624 "Type: 'help' for a list of commands\n"
625 " 'man' to read the manual\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. */
859 /* For | ... commands. Annoyingly we can't use popen(3) here. */
863 if (fflush (stdout) == EOF) {
864 perror ("failed to flush standard output");
868 perror ("pipe failed");
877 if (pid == 0) { /* Child process. */
879 if (dup2 (fd[0], 0) < 0) {
880 perror ("dup2 of stdin failed");
884 r = system (pipecmd);
889 _exit (WEXITSTATUS (r));
892 if ((stdout_saved_fd = dup (1)) < 0) {
893 perror ("failed to dup stdout");
897 if (dup2 (fd[1], 1) < 0) {
898 perror ("failed to dup stdout");
899 close (stdout_saved_fd);
905 for (argc = 0; argv[argc] != NULL; ++argc)
908 /* If --remote was set, then send this command to a remote process. */
910 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
912 /* Otherwise execute it locally. */
913 else if (STRCASEEQ (cmd, "help")) {
917 display_command (argv[0]);
920 else if (STRCASEEQ (cmd, "quit") ||
921 STRCASEEQ (cmd, "exit") ||
922 STRCASEEQ (cmd, "q")) {
926 else if (STRCASEEQ (cmd, "alloc") ||
927 STRCASEEQ (cmd, "allocate"))
928 r = do_alloc (cmd, argc, argv);
929 else if (STRCASEEQ (cmd, "echo"))
930 r = do_echo (cmd, argc, argv);
931 else if (STRCASEEQ (cmd, "edit") ||
932 STRCASEEQ (cmd, "vi") ||
933 STRCASEEQ (cmd, "emacs"))
934 r = do_edit (cmd, argc, argv);
935 else if (STRCASEEQ (cmd, "lcd"))
936 r = do_lcd (cmd, argc, argv);
937 else if (STRCASEEQ (cmd, "glob"))
938 r = do_glob (cmd, argc, argv);
939 else if (STRCASEEQ (cmd, "man") ||
940 STRCASEEQ (cmd, "manual"))
941 r = do_man (cmd, argc, argv);
942 else if (STRCASEEQ (cmd, "more") ||
943 STRCASEEQ (cmd, "less"))
944 r = do_more (cmd, argc, argv);
945 else if (STRCASEEQ (cmd, "reopen"))
946 r = do_reopen (cmd, argc, argv);
947 else if (STRCASEEQ (cmd, "sparse"))
948 r = do_sparse (cmd, argc, argv);
949 else if (STRCASEEQ (cmd, "time"))
950 r = do_time (cmd, argc, argv);
952 r = run_action (cmd, argc, argv);
954 /* Always flush stdout after every command, so that messages, results
955 * etc appear immediately.
957 if (fflush (stdout) == EOF) {
958 perror ("failed to flush standard output");
964 if (dup2 (stdout_saved_fd, 1) < 0) {
965 perror ("failed to dup2 standard output");
968 close (stdout_saved_fd);
969 if (waitpid (pid, NULL, 0) < 0) {
970 perror ("waiting for command to complete");
979 list_builtin_commands (void)
981 /* help, man and quit should appear at the top */
982 printf ("%-20s %s\n",
983 "help", _("display a list of commands or help on a command"));
984 printf ("%-20s %s\n",
985 "man", _("read the manual"));
986 printf ("%-20s %s\n",
987 "quit", _("quit guestfish"));
989 printf ("%-20s %s\n",
990 "alloc", _("allocate an image"));
991 printf ("%-20s %s\n",
992 "echo", _("display a line of text"));
993 printf ("%-20s %s\n",
994 "edit", _("edit a file in the image"));
995 printf ("%-20s %s\n",
996 "lcd", _("local change directory"));
997 printf ("%-20s %s\n",
998 "glob", _("expand wildcards in command"));
999 printf ("%-20s %s\n",
1000 "more", _("view a file in the pager"));
1001 printf ("%-20s %s\n",
1002 "reopen", _("close and reopen libguestfs handle"));
1003 printf ("%-20s %s\n",
1004 "sparse", _("allocate a sparse image file"));
1005 printf ("%-20s %s\n",
1006 "time", _("measure time taken to run command"));
1008 /* actions are printed after this (see list_commands) */
1012 display_builtin_command (const char *cmd)
1014 /* help for actions is auto-generated, see display_command */
1016 if (STRCASEEQ (cmd, "alloc") ||
1017 STRCASEEQ (cmd, "allocate"))
1018 printf (_("alloc - allocate an image\n"
1019 " alloc <filename> <size>\n"
1021 " This creates an empty (zeroed) file of the given size,\n"
1022 " and then adds so it can be further examined.\n"
1024 " For more advanced image creation, see qemu-img utility.\n"
1026 " Size can be specified (where <nn> means a number):\n"
1027 " <nn> number of kilobytes\n"
1028 " eg: 1440 standard 3.5\" floppy\n"
1029 " <nn>K or <nn>KB number of kilobytes\n"
1030 " <nn>M or <nn>MB number of megabytes\n"
1031 " <nn>G or <nn>GB number of gigabytes\n"
1032 " <nn>T or <nn>TB number of terabytes\n"
1033 " <nn>P or <nn>PB number of petabytes\n"
1034 " <nn>E or <nn>EB number of exabytes\n"
1035 " <nn>sects number of 512 byte sectors\n"));
1036 else if (STRCASEEQ (cmd, "echo"))
1037 printf (_("echo - display a line of text\n"
1038 " echo [<params> ...]\n"
1040 " This echos the parameters to the terminal.\n"));
1041 else if (STRCASEEQ (cmd, "edit") ||
1042 STRCASEEQ (cmd, "vi") ||
1043 STRCASEEQ (cmd, "emacs"))
1044 printf (_("edit - edit a file in the image\n"
1045 " edit <filename>\n"
1047 " This is used to edit a file.\n"
1049 " It is the equivalent of (and is implemented by)\n"
1050 " running \"cat\", editing locally, and then \"write-file\".\n"
1052 " Normally it uses $EDITOR, but if you use the aliases\n"
1053 " \"vi\" or \"emacs\" you will get those editors.\n"
1055 " NOTE: This will not work reliably for large files\n"
1056 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1057 else if (STRCASEEQ (cmd, "lcd"))
1058 printf (_("lcd - local change directory\n"
1059 " lcd <directory>\n"
1061 " Change guestfish's current directory. This command is\n"
1062 " useful if you want to download files to a particular\n"
1064 else if (STRCASEEQ (cmd, "glob"))
1065 printf (_("glob - expand wildcards in command\n"
1066 " glob <command> [<args> ...]\n"
1068 " Glob runs <command> with wildcards expanded in any\n"
1069 " command args. Note that the command is run repeatedly\n"
1070 " once for each expanded argument.\n"));
1071 else if (STRCASEEQ (cmd, "man") ||
1072 STRCASEEQ (cmd, "manual"))
1073 printf (_("man - read the manual\n"
1076 " Opens the manual page for guestfish.\n"));
1077 else if (STRCASEEQ (cmd, "help"))
1078 printf (_("help - display a list of commands or help on a command\n"
1081 else if (STRCASEEQ (cmd, "more") ||
1082 STRCASEEQ (cmd, "less"))
1083 printf (_("more - view a file in the pager\n"
1084 " more <filename>\n"
1086 " This is used to view a file in the pager.\n"
1088 " It is the equivalent of (and is implemented by)\n"
1089 " running \"cat\" and using the pager.\n"
1091 " Normally it uses $PAGER, but if you use the alias\n"
1092 " \"less\" then it always uses \"less\".\n"
1094 " NOTE: This will not work reliably for large files\n"
1095 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1096 else if (STRCASEEQ (cmd, "quit") ||
1097 STRCASEEQ (cmd, "exit") ||
1098 STRCASEEQ (cmd, "q"))
1099 printf (_("quit - quit guestfish\n"
1101 else if (STRCASEEQ (cmd, "reopen"))
1102 printf (_("reopen - close and reopen the libguestfs handle\n"
1105 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1106 "this normally, because the handle is closed properly when guestfish\n"
1107 "exits. However this is occasionally useful for testing.\n"));
1108 else if (STRCASEEQ (cmd, "sparse"))
1109 printf (_("sparse - allocate a sparse image file\n"
1110 " sparse <filename> <size>\n"
1112 " This creates an empty sparse file of the given size,\n"
1113 " and then adds so it can be further examined.\n"
1115 " In all respects it works the same as the 'alloc'\n"
1116 " command, except that the image file is allocated\n"
1117 " sparsely, which means that disk blocks are not assigned\n"
1118 " to the file until they are needed. Sparse disk files\n"
1119 " only use space when written to, but they are slower\n"
1120 " and there is a danger you could run out of real disk\n"
1121 " space during a write operation.\n"
1123 " For more advanced image creation, see qemu-img utility.\n"
1125 " Size can be specified (where <nn> means a number):\n"
1126 " <nn> number of kilobytes\n"
1127 " eg: 1440 standard 3.5\" floppy\n"
1128 " <nn>K or <nn>KB number of kilobytes\n"
1129 " <nn>M or <nn>MB number of megabytes\n"
1130 " <nn>G or <nn>GB number of gigabytes\n"
1131 " <nn>T or <nn>TB number of terabytes\n"
1132 " <nn>P or <nn>PB number of petabytes\n"
1133 " <nn>E or <nn>EB number of exabytes\n"
1134 " <nn>sects number of 512 byte sectors\n"));
1135 else if (STRCASEEQ (cmd, "time"))
1136 printf (_("time - measure time taken to run command\n"
1137 " time <command> [<args> ...]\n"
1139 " This runs <command> as usual, and prints the elapsed\n"
1140 " time afterwards.\n"));
1142 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1146 /* This is printed when the user types in an unknown command for the
1147 * first command issued. A common case is the user doing:
1148 * guestfish disk.img
1149 * expecting guestfish to open 'disk.img' (in fact, this tried to
1150 * run a command 'disk.img').
1153 extended_help_message (void)
1156 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1157 "For a list of commands: guestfish -h\n"
1158 "For complete documentation: man guestfish\n"));
1162 free_strings (char **argv)
1166 for (argc = 0; argv[argc] != NULL; ++argc)
1172 count_strings (char *const *argv)
1176 for (c = 0; argv[c]; ++c)
1182 print_strings (char *const *argv)
1186 for (argc = 0; argv[argc] != NULL; ++argc)
1187 printf ("%s\n", argv[argc]);
1191 print_table (char *const *argv)
1195 for (i = 0; argv[i] != NULL; i += 2)
1196 printf ("%s: %s\n", argv[i], argv[i+1]);
1200 is_true (const char *str)
1203 STRCASENEQ (str, "0") &&
1204 STRCASENEQ (str, "f") &&
1205 STRCASENEQ (str, "false") &&
1206 STRCASENEQ (str, "n") &&
1207 STRCASENEQ (str, "no");
1210 /* Free strings from a non-NULL terminated char** */
1212 free_n_strings (char **str, size_t len)
1216 for (i = 0; i < len; i++) {
1223 parse_string_list (const char *str)
1226 size_t argv_len = 0;
1228 /* Current position pointer */
1229 const char *p = str;
1231 /* Token might be simple:
1234 * 'This is a single token'
1235 * or contain embedded single-quoted sections:
1236 * This' is a sing'l'e to'ken
1238 * The latter may seem over-complicated, but it's what a normal shell does.
1239 * Not doing it risks surprising somebody.
1241 * This outer loop is over complete tokens.
1247 /* Skip leading whitespace */
1248 p += strspn (p, " \t");
1252 /* This loop is over token 'fragments'. A token can be in multiple bits if
1253 * it contains single quotes. We also treat both sides of an escaped quote
1254 * as separate fragments because we can't just copy it: we have to remove
1257 while (*p && (!c_isblank (*p) || in_quote)) {
1258 const char *end = p;
1260 /* Check if the fragment starts with a quote */
1262 /* Toggle in_quote */
1263 in_quote = !in_quote;
1265 /* Skip the quote */
1269 /* If we're in a quote, look for an end quote */
1271 end += strcspn (end, "'");
1274 /* Otherwise, look for whitespace or a quote */
1276 end += strcspn (end, " \t'");
1279 /* Grow the token to accommodate the fragment */
1280 size_t tok_end = tok_len;
1282 char *tok_new = realloc (tok, tok_len + 1);
1283 if (NULL == tok_new) {
1285 free_n_strings (argv, argv_len);
1287 exit (EXIT_FAILURE);
1291 /* Check if we stopped on an escaped quote */
1292 if ('\'' == *end && end != p && *(end-1) == '\\') {
1293 /* Add everything before \' to the token */
1294 memcpy (&tok[tok_end], p, end - p - 1);
1297 tok[tok_len-1] = '\'';
1299 /* Already processed the quote */
1304 /* Add the whole fragment */
1305 memcpy (&tok[tok_end], p, end - p);
1311 /* We've reached the end of a token. We shouldn't still be in quotes. */
1313 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1315 free_n_strings (argv, argv_len);
1320 /* Add this token if there is one. There might not be if there was
1321 * whitespace at the end of the input string */
1323 /* Add the NULL terminator */
1324 tok[tok_len] = '\0';
1326 /* Add the argument to the argument list */
1328 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1329 if (NULL == argv_new) {
1331 free_n_strings (argv, argv_len-1);
1333 exit (EXIT_FAILURE);
1337 argv[argv_len-1] = tok;
1341 /* NULL terminate the argument list */
1343 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1344 if (NULL == argv_new) {
1346 free_n_strings (argv, argv_len-1);
1347 exit (EXIT_FAILURE);
1351 argv[argv_len-1] = NULL;
1356 #ifdef HAVE_LIBREADLINE
1357 static char histfile[1024];
1358 static int nr_history_lines = 0;
1362 initialize_readline (void)
1364 #ifdef HAVE_LIBREADLINE
1367 home = getenv ("HOME");
1369 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1371 (void) read_history (histfile);
1374 rl_readline_name = "guestfish";
1375 rl_attempted_completion_function = do_completion;
1380 cleanup_readline (void)
1382 #ifdef HAVE_LIBREADLINE
1385 if (histfile[0] != '\0') {
1386 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1393 #ifdef HAVE_APPEND_HISTORY
1394 (void) append_history (nr_history_lines, histfile);
1396 (void) write_history (histfile);
1403 add_history_line (const char *line)
1405 #ifdef HAVE_LIBREADLINE
1412 xwrite (int fd, const void *v_buf, size_t len)
1415 const char *buf = v_buf;
1418 r = write (fd, buf, len);
1430 /* Resolve the special "win:..." form for Windows-specific paths.
1431 * This always returns a newly allocated string which is freed by the
1432 * caller function in "cmds.c".
1435 resolve_win_path (const char *path)
1440 if (STRCASENEQLEN (path, "win:", 4)) {
1441 ret = strdup (path);
1449 /* Drop drive letter, if it's "C:". */
1450 if (STRCASEEQLEN (path, "c:", 2))
1460 ret = strdup (path);
1466 /* Blindly convert any backslashes into forward slashes. Is this good? */
1467 for (i = 0; i < strlen (ret); ++i)
1471 char *t = guestfs_case_sensitive_path (g, ret);
1478 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1479 * The caller (cmds.c) will call free_file_in after the command has
1480 * run which should clean up resources.
1482 static char *file_in_heredoc (const char *endmarker);
1483 static char *file_in_tmpfile = NULL;
1486 file_in (const char *arg)
1490 if (STREQ (arg, "-")) {
1491 ret = strdup ("/dev/stdin");
1497 else if (STRPREFIX (arg, "-<<")) {
1498 const char *endmarker = &arg[3];
1499 if (*endmarker == '\0') {
1500 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1504 ret = file_in_heredoc (endmarker);
1520 file_in_heredoc (const char *endmarker)
1522 static const char template[] = "/tmp/heredocXXXXXX";
1523 file_in_tmpfile = strdup (template);
1524 if (file_in_tmpfile == NULL) {
1529 int fd = mkstemp (file_in_tmpfile);
1535 size_t markerlen = strlen (endmarker);
1537 char buffer[BUFSIZ];
1538 int write_error = 0;
1539 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1540 /* Look for "END"<EOF> or "END\n" in input. */
1541 size_t blen = strlen (buffer);
1542 if (STREQLEN (buffer, endmarker, markerlen) &&
1543 (blen == markerlen ||
1544 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1547 if (xwrite (fd, buffer, blen) == -1) {
1548 if (!write_error) perror ("write");
1550 /* continue reading up to the end marker */
1554 /* Reached EOF of stdin without finding the end marker, which
1555 * is likely to be an error.
1557 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1558 program_name, endmarker);
1567 if (close (fd) == -1) {
1572 return file_in_tmpfile;
1575 unlink (file_in_tmpfile);
1578 free (file_in_tmpfile);
1579 file_in_tmpfile = NULL;
1584 free_file_in (char *s)
1586 if (file_in_tmpfile) {
1587 if (unlink (file_in_tmpfile) == -1)
1588 perror (file_in_tmpfile);
1589 file_in_tmpfile = NULL;
1592 /* Free the device or file name which was strdup'd in file_in().
1593 * Note it's not immediately clear, but for -<< heredocs,
1594 * s == file_in_tmpfile, so this frees up that buffer.
1599 /* Resolve the special FileOut paths ("-" or filename).
1600 * The caller (cmds.c) will call free (str) after the command has run.
1603 file_out (const char *arg)
1607 if (STREQ (arg, "-"))
1608 ret = strdup ("/dev/stdout");