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.
30 #include <sys/types.h>
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
48 char *filename; /* disk filename (for -a or -N options) */
49 prep_data *data; /* prepared type (for -N option only) */
50 char *device; /* device inside the appliance */
59 static void add_drives (struct drv *drv);
60 static void prepare_drives (struct drv *drv);
61 static void mount_mps (struct mp *mp);
62 static int launch (void);
63 static void interactive (void);
64 static void shell_script (void);
65 static void script (int prompt);
66 static void cmdline (char *argv[], int optind, int argc);
67 static void initialize_readline (void);
68 static void cleanup_readline (void);
69 #ifdef HAVE_LIBREADLINE
70 static void add_history_line (const char *);
72 static void print_shell_quote (FILE *stream, const char *str);
74 /* Currently open libguestfs handle. */
80 int remote_control_listen = 0;
81 int remote_control = 0;
82 int exit_on_error = 1;
85 static void __attribute__((noreturn))
88 if (status != EXIT_SUCCESS)
89 fprintf (stderr, _("Try `%s --help' for more information.\n"),
93 _("%s: guest filesystem shell\n"
94 "%s lets you edit virtual machine filesystems\n"
95 "Copyright (C) 2009-2010 Red Hat Inc.\n"
97 " %s [--options] cmd [: cmd : cmd ...]\n"
98 " %s -i libvirt-domain\n"
99 " %s -i disk-image(s)\n"
100 "or for interactive use:\n"
102 "or from a shell script:\n"
108 " -h|--cmd-help List available commands\n"
109 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
110 " -a|--add image Add image\n"
111 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
112 " -f|--file file Read commands from file\n"
113 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
114 " --listen Listen for remote commands\n"
115 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
116 " -n|--no-sync Don't autosync\n"
117 " -N|--new type Create prepared disk (test1.img, ...)\n"
118 " --remote[=pid] Send commands to remote %s\n"
119 " -r|--ro Mount read-only\n"
120 " --selinux Enable SELinux support\n"
121 " -v|--verbose Verbose messages\n"
122 " -x Echo each command before executing it\n"
123 " -V|--version Display version and exit\n"
124 "For more information, see the manpage %s(1).\n"),
125 program_name, program_name, program_name,
126 program_name, program_name, program_name,
127 program_name, program_name, program_name);
133 main (int argc, char *argv[])
135 /* Set global program name that is not polluted with libtool artifacts. */
136 set_program_name (argv[0]);
138 atexit (close_stdout);
140 setlocale (LC_ALL, "");
141 bindtextdomain (PACKAGE, LOCALEBASEDIR);
142 textdomain (PACKAGE);
144 enum { HELP_OPTION = CHAR_MAX + 1 };
146 static const char *options = "a:Df:h::im:nN:rv?Vx";
147 static const struct option long_options[] = {
148 { "add", 1, 0, 'a' },
149 { "cmd-help", 2, 0, 'h' },
150 { "file", 1, 0, 'f' },
151 { "help", 0, 0, HELP_OPTION },
152 { "inspector", 0, 0, 'i' },
153 { "listen", 0, 0, 0 },
154 { "mount", 1, 0, 'm' },
155 { "new", 1, 0, 'N' },
156 { "no-dest-paths", 0, 0, 'D' },
157 { "no-sync", 0, 0, 'n' },
158 { "remote", 2, 0, 0 },
160 { "selinux", 0, 0, 0 },
161 { "verbose", 0, 0, 'v' },
162 { "version", 0, 0, 'V' },
165 struct drv *drvs = NULL;
167 struct mp *mps = NULL;
169 char *p, *file = NULL;
174 char next_drive = 'a';
175 int next_prepared_drive = 1;
177 initialize_readline ();
179 memset (&sa, 0, sizeof sa);
180 sa.sa_handler = SIG_IGN;
181 sa.sa_flags = SA_RESTART;
182 sigaction (SIGPIPE, &sa, NULL);
184 /* guestfs_create is meant to be a lightweight operation, so
185 * it's OK to do it early here.
187 g = guestfs_create ();
189 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
193 guestfs_set_autosync (g, 1);
195 /* If developing, add ./appliance to the path. Note that libtools
196 * interferes with this because uninstalled guestfish is a shell
197 * script that runs the real program with an absolute path. Detect
200 * BUT if LIBGUESTFS_PATH environment variable is already set by
201 * the user, then don't override it.
203 if (getenv ("LIBGUESTFS_PATH") == NULL &&
205 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
206 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
208 /* CAUTION: we are careful to modify argv[0] here, only after
209 * using it just above.
211 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
212 * of the original, in case it's needed in virt-inspector mode, below.
214 char *real_argv0 = argv[0];
215 argv[0] = bad_cast (program_name);
218 c = getopt_long (argc, argv, options, long_options, &option_index);
222 case 0: /* options which are long only */
223 if (STREQ (long_options[option_index].name, "listen"))
224 remote_control_listen = 1;
225 else if (STREQ (long_options[option_index].name, "remote")) {
227 if (sscanf (optarg, "%d", &remote_control) != 1) {
228 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
229 program_name, optarg);
233 p = getenv ("GUESTFISH_PID");
234 if (!p || sscanf (p, "%d", &remote_control) != 1) {
235 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
236 " to the PID of the remote process\n"),
241 } else if (STREQ (long_options[option_index].name, "selinux")) {
242 guestfs_set_selinux (g, 1);
244 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
245 program_name, long_options[option_index].name, option_index);
251 if (access (optarg, R_OK) != 0) {
255 drv = malloc (sizeof (struct drv));
260 drv->filename = optarg;
262 /* We could fill the device field in, but in fact we
263 * only use it for the -N option at present.
272 if (STRCASEEQ (optarg, "list")) {
273 list_prepared_drives ();
276 drv = malloc (sizeof (struct drv));
281 if (asprintf (&drv->filename, "test%d.img",
282 next_prepared_drive++) == -1) {
286 drv->data = create_prepared_file (optarg, drv->filename);
287 if (asprintf (&drv->device, "/dev/sd%c", next_drive++) == -1) {
296 complete_dest_paths = 0;
301 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
312 r = display_command (optarg);
313 else if (argv[optind] && argv[optind][0] != '-')
314 r = display_command (argv[optind++]);
318 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
326 mp = malloc (sizeof (struct mp));
331 p = strchr (optarg, ':');
334 mp->mountpoint = p+1;
336 mp->mountpoint = bad_cast ("/");
343 guestfs_set_autosync (g, 0);
352 guestfs_set_verbose (g, verbose);
356 struct guestfs_version *v = guestfs_version (g);
357 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
358 v->major, v->minor, v->release, v->extra);
363 guestfs_set_trace (g, 1);
367 usage (EXIT_SUCCESS);
370 usage (EXIT_FAILURE);
374 /* Inspector mode invalidates most of the other arguments. */
376 if (drvs || mps || remote_control_listen || remote_control ||
377 guestfs_get_selinux (g)) {
378 fprintf (stderr, _("%s: cannot use -i option with -a, -m, -N, "
379 "--listen, --remote or --selinux\n"),
383 if (optind >= argc) {
385 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
392 FILE *fp = open_memstream (&cmd, &cmdlen);
394 perror ("open_memstream");
398 fprintf (fp, "virt-inspector");
399 while (optind < argc) {
401 print_shell_quote (fp, argv[optind]);
406 fprintf (fp, " --ro-fish");
408 fprintf (fp, " --fish");
410 if (fclose (fp) == -1) {
417 "%s -i: running: %s\n", program_name, cmd);
419 FILE *pp = popen (cmd, "r");
426 fp = open_memstream (&cmd2, &cmdlen);
428 perror ("open_memstream");
432 fprintf (fp, "%s", real_argv0);
434 if (guestfs_get_verbose (g))
436 if (!guestfs_get_autosync (g))
438 if (guestfs_get_trace (g))
443 if (getline (&insp, &insplen, pp) == -1) {
447 fprintf (fp, " %s", insp);
449 if (pclose (pp) == -1) {
454 if (fclose (fp) == -1) {
461 "%s -i: running: %s\n", program_name, cmd2);
463 int r = system (cmd2);
473 exit (WEXITSTATUS (r));
476 /* If we've got drives to add, add them now. */
479 /* If we've got mountpoints or prepared drives, we must launch the
480 * guest and mount them.
482 if (next_prepared_drive > 1 || mps != NULL) {
483 /* RHBZ#612178: If --listen flag is given, then we will fork into
484 * the background in rc_listen(). However you can't do this while
485 * holding a libguestfs handle open because the recovery process
486 * will think the main program has died and kill qemu. Therefore
487 * don't use the recovery process for this case. (A better
488 * solution would be to call launch () etc after the fork, but
489 * that greatly complicates the code here).
491 if (remote_control_listen)
492 guestfs_set_recovery_proc (g, 0);
494 if (launch () == -1) exit (EXIT_FAILURE);
495 prepare_drives (drvs);
499 /* Remote control? */
500 if (remote_control_listen && remote_control) {
502 _("%s: cannot use --listen and --remote options at the same time\n"),
507 if (remote_control_listen) {
510 _("%s: extra parameters on the command line with --listen flag\n"),
516 _("%s: cannot use --listen and --file options at the same time\n"),
523 /* -f (file) parameter? */
526 if (open (file, O_RDONLY) == -1) {
532 /* Interactive, shell script, or command(s) on the command line? */
533 if (optind >= argc) {
540 cmdline (argv, optind, argc);
548 pod2text (const char *name, const char *shortdesc, const char *str)
552 fp = popen ("pod2text", "w");
554 /* pod2text failed, maybe not found, so let's just print the
555 * source instead, since that's better than doing nothing.
557 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
560 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
565 /* List is built in reverse order, so mount them in reverse order. */
567 mount_mps (struct mp *mp)
572 mount_mps (mp->next);
574 /* Don't use guestfs_mount here because that will default to mount
575 * options -o sync,noatime. For more information, see guestfs(3)
576 * section "LIBGUESTFS GOTCHAS".
578 const char *options = read_only ? "ro" : "";
579 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
586 add_drives (struct drv *drv)
591 add_drives (drv->next);
593 if (drv->data /* -N option is not affected by --ro */ || !read_only)
594 r = guestfs_add_drive (g, drv->filename);
596 r = guestfs_add_drive_ro (g, drv->filename);
603 prepare_drives (struct drv *drv)
606 prepare_drives (drv->next);
608 prepare_drive (drv->filename, drv->data, drv->device);
615 if (guestfs_is_config (g)) {
616 if (guestfs_launch (g) == -1)
634 #define FISH "><fs> "
636 static char *line_read = NULL;
641 #ifdef HAVE_LIBREADLINE
649 line_read = readline (prompt ? FISH : "");
651 if (line_read && *line_read)
652 add_history_line (line_read);
657 #endif /* HAVE_LIBREADLINE */
659 static char buf[8192];
662 if (prompt) printf (FISH);
663 line_read = fgets (buf, sizeof buf, stdin);
666 len = strlen (line_read);
667 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
681 int global_exit_on_error = !prompt;
686 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
687 "editing virtual machine filesystems.\n"
689 "Type: 'help' for a list of commands\n"
690 " 'man' to read the manual\n"
691 " 'quit' to quit the shell\n"
697 exit_on_error = global_exit_on_error;
699 buf = rl_gets (prompt);
705 /* Skip any initial whitespace before the command. */
707 while (*buf && c_isspace (*buf))
712 /* If the next character is '#' then this is a comment. */
713 if (*buf == '#') continue;
715 /* If the next character is '!' then pass the whole lot to system(3). */
723 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
724 WEXITSTATUS (r) != 0)
730 /* If the next character is '-' allow the command to fail without
731 * exiting on error (just for this one command though).
739 /* Get the command (cannot be quoted). */
740 len = strcspn (buf, " \t");
742 if (len == 0) continue;
746 if (buf[len] == '\0') {
753 p += strspn (p, " \t");
755 /* Get the parameters. */
756 while (*p && i < sizeof argv / sizeof argv[0]) {
759 /* Parameters which start with quotes or pipes are treated
760 * specially. Bare parameters are delimited by whitespace.
764 len = strcspn (p, "\"");
765 if (p[len] == '\0') {
766 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
767 if (exit_on_error) exit (EXIT_FAILURE);
770 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
772 _("%s: command arguments not separated by whitespace\n"),
774 if (exit_on_error) exit (EXIT_FAILURE);
778 pend = p[len+1] ? &p[len+2] : &p[len+1];
779 } else if (*p == '\'') {
781 len = strcspn (p, "'");
782 if (p[len] == '\0') {
783 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
784 if (exit_on_error) exit (EXIT_FAILURE);
787 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
789 _("%s: command arguments not separated by whitespace\n"),
791 if (exit_on_error) exit (EXIT_FAILURE);
795 pend = p[len+1] ? &p[len+2] : &p[len+1];
796 } else if (*p == '|') {
801 } else if (*p == '[') {
805 while (*pend && c != 0) {
806 if (*pend == '[') c++;
807 else if (*pend == ']') c--;
812 _("%s: unterminated \"[...]\" sequence\n"), program_name);
813 if (exit_on_error) exit (EXIT_FAILURE);
816 if (*pend && (*pend != ' ' && *pend != '\t')) {
818 _("%s: command arguments not separated by whitespace\n"),
820 if (exit_on_error) exit (EXIT_FAILURE);
825 } else if (*p != ' ' && *p != '\t') {
826 /* If the first character is a ~ then note that this parameter
827 * is a candidate for ~username expansion. NB this does not
828 * apply to quoted parameters.
830 tilde_candidate = *p == '~';
831 len = strcspn (p, " \t");
838 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
843 if (!tilde_candidate)
846 argv[i] = try_tilde_expansion (p);
851 p += strspn (p, " \t");
854 if (i == sizeof argv / sizeof argv[0]) {
855 fprintf (stderr, _("%s: too many arguments\n"), program_name);
856 if (exit_on_error) exit (EXIT_FAILURE);
863 if (issue_command (cmd, argv, pipe) == -1) {
864 if (exit_on_error) exit (EXIT_FAILURE);
869 if (prompt) printf ("\n");
873 cmdline (char *argv[], int optind, int argc)
880 if (optind >= argc) return;
882 cmd = argv[optind++];
883 if (STREQ (cmd, ":")) {
884 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
888 /* Allow -cmd on the command line to mean (temporarily) override
889 * the normal exit on error (RHBZ#578407).
896 params = &argv[optind];
898 /* Search for end of command list or ":" ... */
899 while (optind < argc && STRNEQ (argv[optind], ":"))
902 if (optind == argc) {
903 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
907 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
909 cmdline (argv, optind+1, argc);
914 issue_command (const char *cmd, char *argv[], const char *pipecmd)
917 int stdout_saved_fd = -1;
921 /* This counts the commands issued, starting at 1. */
924 /* For | ... commands. Annoyingly we can't use popen(3) here. */
928 if (fflush (stdout) == EOF) {
929 perror ("failed to flush standard output");
933 perror ("pipe failed");
942 if (pid == 0) { /* Child process. */
944 if (dup2 (fd[0], 0) < 0) {
945 perror ("dup2 of stdin failed");
949 r = system (pipecmd);
954 _exit (WEXITSTATUS (r));
957 if ((stdout_saved_fd = dup (1)) < 0) {
958 perror ("failed to dup stdout");
962 if (dup2 (fd[1], 1) < 0) {
963 perror ("failed to dup stdout");
964 close (stdout_saved_fd);
970 for (argc = 0; argv[argc] != NULL; ++argc)
973 /* If --remote was set, then send this command to a remote process. */
975 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
977 /* Otherwise execute it locally. */
978 else if (STRCASEEQ (cmd, "help")) {
983 r = display_command (argv[0]);
985 else if (STRCASEEQ (cmd, "quit") ||
986 STRCASEEQ (cmd, "exit") ||
987 STRCASEEQ (cmd, "q")) {
991 else if (STRCASEEQ (cmd, "alloc") ||
992 STRCASEEQ (cmd, "allocate"))
993 r = do_alloc (cmd, argc, argv);
994 else if (STRCASEEQ (cmd, "echo"))
995 r = do_echo (cmd, argc, argv);
996 else if (STRCASEEQ (cmd, "edit") ||
997 STRCASEEQ (cmd, "vi") ||
998 STRCASEEQ (cmd, "emacs"))
999 r = do_edit (cmd, argc, argv);
1000 else if (STRCASEEQ (cmd, "lcd"))
1001 r = do_lcd (cmd, argc, argv);
1002 else if (STRCASEEQ (cmd, "glob"))
1003 r = do_glob (cmd, argc, argv);
1004 else if (STRCASEEQ (cmd, "man") ||
1005 STRCASEEQ (cmd, "manual"))
1006 r = do_man (cmd, argc, argv);
1007 else if (STRCASEEQ (cmd, "more") ||
1008 STRCASEEQ (cmd, "less"))
1009 r = do_more (cmd, argc, argv);
1010 else if (STRCASEEQ (cmd, "reopen"))
1011 r = do_reopen (cmd, argc, argv);
1012 else if (STRCASEEQ (cmd, "sparse"))
1013 r = do_sparse (cmd, argc, argv);
1014 else if (STRCASEEQ (cmd, "supported"))
1015 r = do_supported (cmd, argc, argv);
1016 else if (STRCASEEQ (cmd, "time"))
1017 r = do_time (cmd, argc, argv);
1019 r = run_action (cmd, argc, argv);
1021 /* Always flush stdout after every command, so that messages, results
1022 * etc appear immediately.
1024 if (fflush (stdout) == EOF) {
1025 perror ("failed to flush standard output");
1031 if (dup2 (stdout_saved_fd, 1) < 0) {
1032 perror ("failed to dup2 standard output");
1035 close (stdout_saved_fd);
1036 if (waitpid (pid, NULL, 0) < 0) {
1037 perror ("waiting for command to complete");
1046 list_builtin_commands (void)
1048 /* help, man and quit should appear at the top */
1049 printf ("%-20s %s\n",
1050 "help", _("display a list of commands or help on a command"));
1051 printf ("%-20s %s\n",
1052 "man", _("read the manual"));
1053 printf ("%-20s %s\n",
1054 "quit", _("quit guestfish"));
1056 printf ("%-20s %s\n",
1057 "alloc", _("allocate an image"));
1058 printf ("%-20s %s\n",
1059 "echo", _("display a line of text"));
1060 printf ("%-20s %s\n",
1061 "edit", _("edit a file in the image"));
1062 printf ("%-20s %s\n",
1063 "lcd", _("local change directory"));
1064 printf ("%-20s %s\n",
1065 "glob", _("expand wildcards in command"));
1066 printf ("%-20s %s\n",
1067 "more", _("view a file in the pager"));
1068 printf ("%-20s %s\n",
1069 "reopen", _("close and reopen libguestfs handle"));
1070 printf ("%-20s %s\n",
1071 "sparse", _("allocate a sparse image file"));
1072 printf ("%-20s %s\n",
1073 "supported", _("list supported groups of commands"));
1074 printf ("%-20s %s\n",
1075 "time", _("measure time taken to run command"));
1077 /* actions are printed after this (see list_commands) */
1081 display_builtin_command (const char *cmd)
1083 /* help for actions is auto-generated, see display_command */
1085 if (STRCASEEQ (cmd, "alloc") ||
1086 STRCASEEQ (cmd, "allocate")) {
1087 printf (_("alloc - allocate an image\n"
1088 " alloc <filename> <size>\n"
1090 " This creates an empty (zeroed) file of the given size,\n"
1091 " and then adds so it can be further examined.\n"
1093 " For more advanced image creation, see qemu-img utility.\n"
1095 " Size can be specified using standard suffixes, eg. '1M'.\n"
1099 else if (STRCASEEQ (cmd, "echo")) {
1100 printf (_("echo - display a line of text\n"
1101 " echo [<params> ...]\n"
1103 " This echos the parameters to the terminal.\n"));
1106 else if (STRCASEEQ (cmd, "edit") ||
1107 STRCASEEQ (cmd, "vi") ||
1108 STRCASEEQ (cmd, "emacs")) {
1109 printf (_("edit - edit a file in the image\n"
1110 " edit <filename>\n"
1112 " This is used to edit a file.\n"
1114 " It is the equivalent of (and is implemented by)\n"
1115 " running \"cat\", editing locally, and then \"write\".\n"
1117 " Normally it uses $EDITOR, but if you use the aliases\n"
1118 " \"vi\" or \"emacs\" you will get those editors.\n"
1120 " NOTE: This will not work reliably for large files\n"
1121 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1124 else if (STRCASEEQ (cmd, "lcd")) {
1125 printf (_("lcd - local change directory\n"
1126 " lcd <directory>\n"
1128 " Change guestfish's current directory. This command is\n"
1129 " useful if you want to download files to a particular\n"
1133 else if (STRCASEEQ (cmd, "glob")) {
1134 printf (_("glob - expand wildcards in command\n"
1135 " glob <command> [<args> ...]\n"
1137 " Glob runs <command> with wildcards expanded in any\n"
1138 " command args. Note that the command is run repeatedly\n"
1139 " once for each expanded argument.\n"));
1142 else if (STRCASEEQ (cmd, "man") ||
1143 STRCASEEQ (cmd, "manual")) {
1144 printf (_("man - read the manual\n"
1147 " Opens the manual page for guestfish.\n"));
1150 else if (STRCASEEQ (cmd, "help")) {
1151 printf (_("help - display a list of commands or help on a command\n"
1156 else if (STRCASEEQ (cmd, "more") ||
1157 STRCASEEQ (cmd, "less")) {
1158 printf (_("more - view a file in the pager\n"
1159 " more <filename>\n"
1161 " This is used to view a file in the pager.\n"
1163 " It is the equivalent of (and is implemented by)\n"
1164 " running \"cat\" and using the pager.\n"
1166 " Normally it uses $PAGER, but if you use the alias\n"
1167 " \"less\" then it always uses \"less\".\n"
1169 " NOTE: This will not work reliably for large files\n"
1170 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1173 else if (STRCASEEQ (cmd, "quit") ||
1174 STRCASEEQ (cmd, "exit") ||
1175 STRCASEEQ (cmd, "q")) {
1176 printf (_("quit - quit guestfish\n"
1180 else if (STRCASEEQ (cmd, "reopen")) {
1181 printf (_("reopen - close and reopen the libguestfs handle\n"
1184 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1185 "this normally, because the handle is closed properly when guestfish\n"
1186 "exits. However this is occasionally useful for testing.\n"));
1189 else if (STRCASEEQ (cmd, "sparse")) {
1190 printf (_("sparse - allocate a sparse image file\n"
1191 " sparse <filename> <size>\n"
1193 " This creates an empty sparse file of the given size,\n"
1194 " and then adds so it can be further examined.\n"
1196 " In all respects it works the same as the 'alloc'\n"
1197 " command, except that the image file is allocated\n"
1198 " sparsely, which means that disk blocks are not assigned\n"
1199 " to the file until they are needed. Sparse disk files\n"
1200 " only use space when written to, but they are slower\n"
1201 " and there is a danger you could run out of real disk\n"
1202 " space during a write operation.\n"
1204 " For more advanced image creation, see qemu-img utility.\n"
1206 " Size can be specified using standard suffixes, eg. '1M'.\n"
1210 else if (STRCASEEQ (cmd, "supported")) {
1211 printf (_("supported - list supported groups of commands\n"
1214 " This command returns a list of the optional groups\n"
1215 " known to the daemon, and indicates which ones are\n"
1216 " supported by this build of the libguestfs appliance.\n"
1218 " See also guestfs(3) section AVAILABILITY.\n"
1222 else if (STRCASEEQ (cmd, "time")) {
1223 printf (_("time - measure time taken to run command\n"
1224 " time <command> [<args> ...]\n"
1226 " This runs <command> as usual, and prints the elapsed\n"
1227 " time afterwards.\n"));
1231 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1237 /* This is printed when the user types in an unknown command for the
1238 * first command issued. A common case is the user doing:
1239 * guestfish disk.img
1240 * expecting guestfish to open 'disk.img' (in fact, this tried to
1241 * run a command 'disk.img').
1244 extended_help_message (void)
1247 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1248 "For a list of commands: guestfish -h\n"
1249 "For complete documentation: man guestfish\n"));
1253 free_strings (char **argv)
1257 for (argc = 0; argv[argc] != NULL; ++argc)
1263 count_strings (char *const *argv)
1267 for (c = 0; argv[c]; ++c)
1273 print_strings (char *const *argv)
1277 for (argc = 0; argv[argc] != NULL; ++argc)
1278 printf ("%s\n", argv[argc]);
1282 print_table (char *const *argv)
1286 for (i = 0; argv[i] != NULL; i += 2)
1287 printf ("%s: %s\n", argv[i], argv[i+1]);
1291 is_true (const char *str)
1294 STRCASENEQ (str, "0") &&
1295 STRCASENEQ (str, "f") &&
1296 STRCASENEQ (str, "false") &&
1297 STRCASENEQ (str, "n") &&
1298 STRCASENEQ (str, "no");
1301 /* Free strings from a non-NULL terminated char** */
1303 free_n_strings (char **str, size_t len)
1307 for (i = 0; i < len; i++) {
1314 parse_string_list (const char *str)
1317 size_t argv_len = 0;
1319 /* Current position pointer */
1320 const char *p = str;
1322 /* Token might be simple:
1325 * 'This is a single token'
1326 * or contain embedded single-quoted sections:
1327 * This' is a sing'l'e to'ken
1329 * The latter may seem over-complicated, but it's what a normal shell does.
1330 * Not doing it risks surprising somebody.
1332 * This outer loop is over complete tokens.
1338 /* Skip leading whitespace */
1339 p += strspn (p, " \t");
1343 /* This loop is over token 'fragments'. A token can be in multiple bits if
1344 * it contains single quotes. We also treat both sides of an escaped quote
1345 * as separate fragments because we can't just copy it: we have to remove
1348 while (*p && (!c_isblank (*p) || in_quote)) {
1349 const char *end = p;
1351 /* Check if the fragment starts with a quote */
1353 /* Toggle in_quote */
1354 in_quote = !in_quote;
1356 /* Skip the quote */
1360 /* If we're in a quote, look for an end quote */
1362 end += strcspn (end, "'");
1365 /* Otherwise, look for whitespace or a quote */
1367 end += strcspn (end, " \t'");
1370 /* Grow the token to accommodate the fragment */
1371 size_t tok_end = tok_len;
1373 char *tok_new = realloc (tok, tok_len + 1);
1374 if (NULL == tok_new) {
1376 free_n_strings (argv, argv_len);
1378 exit (EXIT_FAILURE);
1382 /* Check if we stopped on an escaped quote */
1383 if ('\'' == *end && end != p && *(end-1) == '\\') {
1384 /* Add everything before \' to the token */
1385 memcpy (&tok[tok_end], p, end - p - 1);
1388 tok[tok_len-1] = '\'';
1390 /* Already processed the quote */
1395 /* Add the whole fragment */
1396 memcpy (&tok[tok_end], p, end - p);
1402 /* We've reached the end of a token. We shouldn't still be in quotes. */
1404 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1406 free_n_strings (argv, argv_len);
1411 /* Add this token if there is one. There might not be if there was
1412 * whitespace at the end of the input string */
1414 /* Add the NULL terminator */
1415 tok[tok_len] = '\0';
1417 /* Add the argument to 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);
1424 exit (EXIT_FAILURE);
1428 argv[argv_len-1] = tok;
1432 /* NULL terminate the argument list */
1434 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1435 if (NULL == argv_new) {
1437 free_n_strings (argv, argv_len-1);
1438 exit (EXIT_FAILURE);
1442 argv[argv_len-1] = NULL;
1447 #ifdef HAVE_LIBREADLINE
1448 static char histfile[1024];
1449 static int nr_history_lines = 0;
1453 initialize_readline (void)
1455 #ifdef HAVE_LIBREADLINE
1458 home = getenv ("HOME");
1460 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1462 (void) read_history (histfile);
1465 rl_readline_name = "guestfish";
1466 rl_attempted_completion_function = do_completion;
1468 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1469 * call the readline(), which happens later. Therefore, these
1470 * provide default values which can be overridden by the user if
1473 (void) rl_variable_bind ("completion-ignore-case", "on");
1478 cleanup_readline (void)
1480 #ifdef HAVE_LIBREADLINE
1483 if (histfile[0] != '\0') {
1484 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1491 #ifdef HAVE_APPEND_HISTORY
1492 (void) append_history (nr_history_lines, histfile);
1494 (void) write_history (histfile);
1500 #ifdef HAVE_LIBREADLINE
1502 add_history_line (const char *line)
1510 xwrite (int fd, const void *v_buf, size_t len)
1513 const char *buf = v_buf;
1516 r = write (fd, buf, len);
1528 /* Resolve the special "win:..." form for Windows-specific paths.
1529 * This always returns a newly allocated string which is freed by the
1530 * caller function in "cmds.c".
1533 resolve_win_path (const char *path)
1538 if (STRCASENEQLEN (path, "win:", 4)) {
1539 ret = strdup (path);
1547 /* Drop drive letter, if it's "C:". */
1548 if (STRCASEEQLEN (path, "c:", 2))
1558 ret = strdup (path);
1564 /* Blindly convert any backslashes into forward slashes. Is this good? */
1565 for (i = 0; i < strlen (ret); ++i)
1569 char *t = guestfs_case_sensitive_path (g, ret);
1576 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1577 * The caller (cmds.c) will call free_file_in after the command has
1578 * run which should clean up resources.
1580 static char *file_in_heredoc (const char *endmarker);
1581 static char *file_in_tmpfile = NULL;
1584 file_in (const char *arg)
1588 if (STREQ (arg, "-")) {
1589 ret = strdup ("/dev/stdin");
1595 else if (STRPREFIX (arg, "-<<")) {
1596 const char *endmarker = &arg[3];
1597 if (*endmarker == '\0') {
1598 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1602 ret = file_in_heredoc (endmarker);
1618 file_in_heredoc (const char *endmarker)
1620 static const char template[] = "/tmp/heredocXXXXXX";
1621 file_in_tmpfile = strdup (template);
1622 if (file_in_tmpfile == NULL) {
1627 int fd = mkstemp (file_in_tmpfile);
1633 size_t markerlen = strlen (endmarker);
1635 char buffer[BUFSIZ];
1636 int write_error = 0;
1637 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1638 /* Look for "END"<EOF> or "END\n" in input. */
1639 size_t blen = strlen (buffer);
1640 if (STREQLEN (buffer, endmarker, markerlen) &&
1641 (blen == markerlen ||
1642 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1645 if (xwrite (fd, buffer, blen) == -1) {
1646 if (!write_error) perror ("write");
1648 /* continue reading up to the end marker */
1652 /* Reached EOF of stdin without finding the end marker, which
1653 * is likely to be an error.
1655 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1656 program_name, endmarker);
1665 if (close (fd) == -1) {
1670 return file_in_tmpfile;
1673 unlink (file_in_tmpfile);
1676 free (file_in_tmpfile);
1677 file_in_tmpfile = NULL;
1682 free_file_in (char *s)
1684 if (file_in_tmpfile) {
1685 if (unlink (file_in_tmpfile) == -1)
1686 perror (file_in_tmpfile);
1687 file_in_tmpfile = NULL;
1690 /* Free the device or file name which was strdup'd in file_in().
1691 * Note it's not immediately clear, but for -<< heredocs,
1692 * s == file_in_tmpfile, so this frees up that buffer.
1697 /* Resolve the special FileOut paths ("-" or filename).
1698 * The caller (cmds.c) will call free (str) after the command has run.
1701 file_out (const char *arg)
1705 if (STREQ (arg, "-"))
1706 ret = strdup ("/dev/stdout");
1718 print_shell_quote (FILE *stream, const char *str)
1720 #define SAFE(c) (c_isalnum((c)) || \
1721 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
1724 for (i = 0; str[i]; ++i) {
1726 putc ('\\', stream);
1727 putc (str[i], stream);