1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2010 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #include <sys/types.h>
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
46 /* List of drives added via -a, -d or -N options. */
49 enum { drv_a, drv_d, drv_N } type;
52 char *filename; /* disk filename */
55 char *guest; /* guest name */
58 char *filename; /* disk filename (testX.img) */
59 prep_data *data; /* prepared type */
60 char *device; /* device inside the appliance */
71 static char add_drives (struct drv *drv, char next_drive);
72 static void prepare_drives (struct drv *drv);
73 static void mount_mps (struct mp *mp);
74 static int launch (void);
75 static void interactive (void);
76 static void shell_script (void);
77 static void script (int prompt);
78 static void cmdline (char *argv[], int optind, int argc);
79 static void initialize_readline (void);
80 static void cleanup_readline (void);
81 #ifdef HAVE_LIBREADLINE
82 static void add_history_line (const char *);
84 static void print_shell_quote (FILE *stream, const char *str);
86 /* Currently open libguestfs handle. */
92 int remote_control_listen = 0;
93 int remote_control = 0;
94 int exit_on_error = 1;
96 int keys_from_stdin = 0;
97 const char *libvirt_uri = NULL;
99 static void __attribute__((noreturn))
102 if (status != EXIT_SUCCESS)
103 fprintf (stderr, _("Try `%s --help' for more information.\n"),
107 _("%s: guest filesystem shell\n"
108 "%s lets you edit virtual machine filesystems\n"
109 "Copyright (C) 2009 Red Hat Inc.\n"
111 " %s [--options] cmd [: cmd : cmd ...]\n"
112 " %s -i libvirt-domain\n"
113 " %s -i disk-image(s)\n"
114 "or for interactive use:\n"
116 "or from a shell script:\n"
122 " -h|--cmd-help List available commands\n"
123 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
124 " -a|--add image Add image\n"
125 " -c|--connect uri Specify libvirt URI for -d option\n"
126 " -d|--domain guest Add disks from libvirt guest\n"
127 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
128 " -f|--file file Read commands from file\n"
129 " -i|--inspector Run virt-inspector to get disk mountpoints\n"
130 " --keys-from-stdin Read passphrases from stdin\n"
131 " --listen Listen for remote commands\n"
132 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
133 " -n|--no-sync Don't autosync\n"
134 " -N|--new type Create prepared disk (test1.img, ...)\n"
135 " --remote[=pid] Send commands to remote %s\n"
136 " -r|--ro Mount read-only\n"
137 " --selinux Enable SELinux support\n"
138 " -v|--verbose Verbose messages\n"
139 " -x Echo each command before executing it\n"
140 " -V|--version Display version and exit\n"
141 "For more information, see the manpage %s(1).\n"),
142 program_name, program_name, program_name,
143 program_name, program_name, program_name,
144 program_name, program_name, program_name);
150 main (int argc, char *argv[])
152 /* Set global program name that is not polluted with libtool artifacts. */
153 set_program_name (argv[0]);
155 atexit (close_stdout);
157 setlocale (LC_ALL, "");
158 bindtextdomain (PACKAGE, LOCALEBASEDIR);
159 textdomain (PACKAGE);
161 enum { HELP_OPTION = CHAR_MAX + 1 };
163 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
164 static const struct option long_options[] = {
165 { "add", 1, 0, 'a' },
166 { "cmd-help", 2, 0, 'h' },
167 { "connect", 1, 0, 'c' },
168 { "domain", 1, 0, 'd' },
169 { "file", 1, 0, 'f' },
170 { "help", 0, 0, HELP_OPTION },
171 { "inspector", 0, 0, 'i' },
172 { "keys-from-stdin", 0, 0, 0 },
173 { "listen", 0, 0, 0 },
174 { "mount", 1, 0, 'm' },
175 { "new", 1, 0, 'N' },
176 { "no-dest-paths", 0, 0, 'D' },
177 { "no-sync", 0, 0, 'n' },
178 { "remote", 2, 0, 0 },
180 { "selinux", 0, 0, 0 },
181 { "verbose", 0, 0, 'v' },
182 { "version", 0, 0, 'V' },
185 struct drv *drvs = NULL;
187 struct mp *mps = NULL;
189 char *p, *file = NULL;
194 int next_prepared_drive = 1;
196 initialize_readline ();
198 memset (&sa, 0, sizeof sa);
199 sa.sa_handler = SIG_IGN;
200 sa.sa_flags = SA_RESTART;
201 sigaction (SIGPIPE, &sa, NULL);
203 /* guestfs_create is meant to be a lightweight operation, so
204 * it's OK to do it early here.
206 g = guestfs_create ();
208 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
212 guestfs_set_autosync (g, 1);
214 /* If developing, add ./appliance to the path. Note that libtools
215 * interferes with this because uninstalled guestfish is a shell
216 * script that runs the real program with an absolute path. Detect
219 * BUT if LIBGUESTFS_PATH environment variable is already set by
220 * the user, then don't override it.
222 if (getenv ("LIBGUESTFS_PATH") == NULL &&
224 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
225 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
227 /* CAUTION: we are careful to modify argv[0] here, only after
228 * using it just above.
230 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
231 * of the original, in case it's needed in virt-inspector mode, below.
233 char *real_argv0 = argv[0];
234 argv[0] = bad_cast (program_name);
237 c = getopt_long (argc, argv, options, long_options, &option_index);
241 case 0: /* options which are long only */
242 if (STREQ (long_options[option_index].name, "listen"))
243 remote_control_listen = 1;
244 else if (STREQ (long_options[option_index].name, "remote")) {
246 if (sscanf (optarg, "%d", &remote_control) != 1) {
247 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
248 program_name, optarg);
252 p = getenv ("GUESTFISH_PID");
253 if (!p || sscanf (p, "%d", &remote_control) != 1) {
254 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
255 " to the PID of the remote process\n"),
260 } else if (STREQ (long_options[option_index].name, "selinux")) {
261 guestfs_set_selinux (g, 1);
262 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
265 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
266 program_name, long_options[option_index].name, option_index);
272 if (access (optarg, R_OK) != 0) {
276 drv = malloc (sizeof (struct drv));
282 drv->a.filename = optarg;
288 libvirt_uri = optarg;
292 drv = malloc (sizeof (struct drv));
298 drv->d.guest = optarg;
304 if (STRCASEEQ (optarg, "list")) {
305 list_prepared_drives ();
308 drv = malloc (sizeof (struct drv));
314 if (asprintf (&drv->N.filename, "test%d.img",
315 next_prepared_drive++) == -1) {
319 drv->N.data = create_prepared_file (optarg, drv->N.filename);
320 drv->N.device = NULL; /* filled in by add_drives */
326 complete_dest_paths = 0;
331 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
342 r = display_command (optarg);
343 else if (argv[optind] && argv[optind][0] != '-')
344 r = display_command (argv[optind++]);
348 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
356 mp = malloc (sizeof (struct mp));
361 p = strchr (optarg, ':');
364 mp->mountpoint = p+1;
366 mp->mountpoint = bad_cast ("/");
373 guestfs_set_autosync (g, 0);
382 guestfs_set_verbose (g, verbose);
386 printf ("%s %s\n", program_name, PACKAGE_VERSION);
390 guestfs_set_trace (g, 1);
394 usage (EXIT_SUCCESS);
397 usage (EXIT_FAILURE);
401 /* Inspector mode invalidates most of the other arguments. */
403 if (drvs || mps || remote_control_listen || remote_control ||
404 guestfs_get_selinux (g)) {
405 fprintf (stderr, _("%s: cannot use -i option with -a, -m, -N, "
406 "--listen, --remote or --selinux\n"),
410 if (optind >= argc) {
412 _("%s: -i requires a libvirt domain or path(s) to disk image(s)\n"),
419 FILE *fp = open_memstream (&cmd, &cmdlen);
421 perror ("open_memstream");
425 fprintf (fp, "virt-inspector");
426 while (optind < argc) {
428 print_shell_quote (fp, argv[optind]);
433 fprintf (fp, " --ro-fish");
435 fprintf (fp, " --fish");
437 if (fclose (fp) == -1) {
444 "%s -i: running: %s\n", program_name, cmd);
446 FILE *pp = popen (cmd, "r");
453 fp = open_memstream (&cmd2, &cmdlen);
455 perror ("open_memstream");
459 fprintf (fp, "%s", real_argv0);
461 if (guestfs_get_verbose (g))
463 if (!guestfs_get_autosync (g))
465 if (guestfs_get_trace (g))
470 if (getline (&insp, &insplen, pp) == -1) {
474 fprintf (fp, " %s", insp);
476 if (pclose (pp) == -1) {
481 if (fclose (fp) == -1) {
488 "%s -i: running: %s\n", program_name, cmd2);
490 int r = system (cmd2);
500 exit (WEXITSTATUS (r));
503 /* If we've got drives to add, add them now. */
504 add_drives (drvs, 'a');
506 /* If we've got mountpoints or prepared drives, we must launch the
507 * guest and mount them.
509 if (next_prepared_drive > 1 || mps != NULL) {
510 /* RHBZ#612178: If --listen flag is given, then we will fork into
511 * the background in rc_listen(). However you can't do this while
512 * holding a libguestfs handle open because the recovery process
513 * will think the main program has died and kill qemu. Therefore
514 * don't use the recovery process for this case. (A better
515 * solution would be to call launch () etc after the fork, but
516 * that greatly complicates the code here).
518 if (remote_control_listen)
519 guestfs_set_recovery_proc (g, 0);
521 if (launch () == -1) exit (EXIT_FAILURE);
522 prepare_drives (drvs);
526 /* Remote control? */
527 if (remote_control_listen && remote_control) {
529 _("%s: cannot use --listen and --remote options at the same time\n"),
534 if (remote_control_listen) {
537 _("%s: extra parameters on the command line with --listen flag\n"),
543 _("%s: cannot use --listen and --file options at the same time\n"),
550 /* -f (file) parameter? */
553 if (open (file, O_RDONLY) == -1) {
559 /* Interactive, shell script, or command(s) on the command line? */
560 if (optind >= argc) {
567 cmdline (argv, optind, argc);
575 pod2text (const char *name, const char *shortdesc, const char *str)
579 fp = popen ("pod2text", "w");
581 /* pod2text failed, maybe not found, so let's just print the
582 * source instead, since that's better than doing nothing.
584 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
587 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
592 /* List is built in reverse order, so mount them in reverse order. */
594 mount_mps (struct mp *mp)
599 mount_mps (mp->next);
601 /* Don't use guestfs_mount here because that will default to mount
602 * options -o sync,noatime. For more information, see guestfs(3)
603 * section "LIBGUESTFS GOTCHAS".
605 const char *options = read_only ? "ro" : "";
606 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
613 add_drives (struct drv *drv, char next_drive)
617 if (next_drive > 'z') {
619 _("guestfish: too many drives added on the command line\n"));
624 next_drive = add_drives (drv->next, next_drive);
629 r = guestfs_add_drive (g, drv->a.filename);
631 r = guestfs_add_drive_ro (g, drv->a.filename);
639 r = add_libvirt_drives (drv->d.guest);
647 /* -N option is not affected by --ro */
648 r = guestfs_add_drive (g, drv->N.filename);
652 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
660 default: /* keep GCC happy */
669 prepare_drives (struct drv *drv)
672 prepare_drives (drv->next);
673 if (drv->type == drv_N)
674 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
681 if (guestfs_is_config (g)) {
682 if (guestfs_launch (g) == -1)
700 #define FISH "><fs> "
702 static char *line_read = NULL;
707 #ifdef HAVE_LIBREADLINE
715 line_read = readline (prompt ? FISH : "");
717 if (line_read && *line_read)
718 add_history_line (line_read);
723 #endif /* HAVE_LIBREADLINE */
725 static char buf[8192];
728 if (prompt) printf (FISH);
729 line_read = fgets (buf, sizeof buf, stdin);
732 len = strlen (line_read);
733 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
747 int global_exit_on_error = !prompt;
752 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
753 "editing virtual machine filesystems.\n"
755 "Type: 'help' for a list of commands\n"
756 " 'man' to read the manual\n"
757 " 'quit' to quit the shell\n"
763 exit_on_error = global_exit_on_error;
765 buf = rl_gets (prompt);
771 /* Skip any initial whitespace before the command. */
773 while (*buf && c_isspace (*buf))
778 /* If the next character is '#' then this is a comment. */
779 if (*buf == '#') continue;
781 /* If the next character is '!' then pass the whole lot to system(3). */
789 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
790 WEXITSTATUS (r) != 0)
796 /* If the next character is '-' allow the command to fail without
797 * exiting on error (just for this one command though).
805 /* Get the command (cannot be quoted). */
806 len = strcspn (buf, " \t");
808 if (len == 0) continue;
812 if (buf[len] == '\0') {
819 p += strspn (p, " \t");
821 /* Get the parameters. */
822 while (*p && i < sizeof argv / sizeof argv[0]) {
825 /* Parameters which start with quotes or pipes are treated
826 * specially. Bare parameters are delimited by whitespace.
830 len = strcspn (p, "\"");
831 if (p[len] == '\0') {
832 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
833 if (exit_on_error) exit (EXIT_FAILURE);
836 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
838 _("%s: command arguments not separated by whitespace\n"),
840 if (exit_on_error) exit (EXIT_FAILURE);
844 pend = p[len+1] ? &p[len+2] : &p[len+1];
845 } else if (*p == '\'') {
847 len = strcspn (p, "'");
848 if (p[len] == '\0') {
849 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
850 if (exit_on_error) exit (EXIT_FAILURE);
853 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
855 _("%s: command arguments not separated by whitespace\n"),
857 if (exit_on_error) exit (EXIT_FAILURE);
861 pend = p[len+1] ? &p[len+2] : &p[len+1];
862 } else if (*p == '|') {
867 } else if (*p == '[') {
871 while (*pend && c != 0) {
872 if (*pend == '[') c++;
873 else if (*pend == ']') c--;
878 _("%s: unterminated \"[...]\" sequence\n"), program_name);
879 if (exit_on_error) exit (EXIT_FAILURE);
882 if (*pend && (*pend != ' ' && *pend != '\t')) {
884 _("%s: command arguments not separated by whitespace\n"),
886 if (exit_on_error) exit (EXIT_FAILURE);
891 } else if (*p != ' ' && *p != '\t') {
892 /* If the first character is a ~ then note that this parameter
893 * is a candidate for ~username expansion. NB this does not
894 * apply to quoted parameters.
896 tilde_candidate = *p == '~';
897 len = strcspn (p, " \t");
904 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
909 if (!tilde_candidate)
912 argv[i] = try_tilde_expansion (p);
917 p += strspn (p, " \t");
920 if (i == sizeof argv / sizeof argv[0]) {
921 fprintf (stderr, _("%s: too many arguments\n"), program_name);
922 if (exit_on_error) exit (EXIT_FAILURE);
929 if (issue_command (cmd, argv, pipe) == -1) {
930 if (exit_on_error) exit (EXIT_FAILURE);
935 if (prompt) printf ("\n");
939 cmdline (char *argv[], int optind, int argc)
946 if (optind >= argc) return;
948 cmd = argv[optind++];
949 if (STREQ (cmd, ":")) {
950 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
954 /* Allow -cmd on the command line to mean (temporarily) override
955 * the normal exit on error (RHBZ#578407).
962 params = &argv[optind];
964 /* Search for end of command list or ":" ... */
965 while (optind < argc && STRNEQ (argv[optind], ":"))
968 if (optind == argc) {
969 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
973 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
975 cmdline (argv, optind+1, argc);
980 issue_command (const char *cmd, char *argv[], const char *pipecmd)
983 int stdout_saved_fd = -1;
987 /* This counts the commands issued, starting at 1. */
990 /* For | ... commands. Annoyingly we can't use popen(3) here. */
994 if (fflush (stdout) == EOF) {
995 perror ("failed to flush standard output");
999 perror ("pipe failed");
1008 if (pid == 0) { /* Child process. */
1010 if (dup2 (fd[0], 0) < 0) {
1011 perror ("dup2 of stdin failed");
1015 r = system (pipecmd);
1020 _exit (WEXITSTATUS (r));
1023 if ((stdout_saved_fd = dup (1)) < 0) {
1024 perror ("failed to dup stdout");
1028 if (dup2 (fd[1], 1) < 0) {
1029 perror ("failed to dup stdout");
1030 close (stdout_saved_fd);
1036 for (argc = 0; argv[argc] != NULL; ++argc)
1039 /* If --remote was set, then send this command to a remote process. */
1041 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1043 /* Otherwise execute it locally. */
1044 else if (STRCASEEQ (cmd, "help")) {
1049 r = display_command (argv[0]);
1051 else if (STRCASEEQ (cmd, "quit") ||
1052 STRCASEEQ (cmd, "exit") ||
1053 STRCASEEQ (cmd, "q")) {
1057 else if (STRCASEEQ (cmd, "alloc") ||
1058 STRCASEEQ (cmd, "allocate"))
1059 r = do_alloc (cmd, argc, argv);
1060 else if (STRCASEEQ (cmd, "echo"))
1061 r = do_echo (cmd, argc, argv);
1062 else if (STRCASEEQ (cmd, "edit") ||
1063 STRCASEEQ (cmd, "vi") ||
1064 STRCASEEQ (cmd, "emacs"))
1065 r = do_edit (cmd, argc, argv);
1066 else if (STRCASEEQ (cmd, "lcd"))
1067 r = do_lcd (cmd, argc, argv);
1068 else if (STRCASEEQ (cmd, "glob"))
1069 r = do_glob (cmd, argc, argv);
1070 else if (STRCASEEQ (cmd, "man") ||
1071 STRCASEEQ (cmd, "manual"))
1072 r = do_man (cmd, argc, argv);
1073 else if (STRCASEEQ (cmd, "more") ||
1074 STRCASEEQ (cmd, "less"))
1075 r = do_more (cmd, argc, argv);
1076 else if (STRCASEEQ (cmd, "reopen"))
1077 r = do_reopen (cmd, argc, argv);
1078 else if (STRCASEEQ (cmd, "sparse"))
1079 r = do_sparse (cmd, argc, argv);
1080 else if (STRCASEEQ (cmd, "supported"))
1081 r = do_supported (cmd, argc, argv);
1082 else if (STRCASEEQ (cmd, "time"))
1083 r = do_time (cmd, argc, argv);
1085 r = run_action (cmd, argc, argv);
1087 /* Always flush stdout after every command, so that messages, results
1088 * etc appear immediately.
1090 if (fflush (stdout) == EOF) {
1091 perror ("failed to flush standard output");
1097 if (dup2 (stdout_saved_fd, 1) < 0) {
1098 perror ("failed to dup2 standard output");
1101 close (stdout_saved_fd);
1102 if (waitpid (pid, NULL, 0) < 0) {
1103 perror ("waiting for command to complete");
1112 list_builtin_commands (void)
1114 /* help, man and quit should appear at the top */
1115 printf ("%-20s %s\n",
1116 "help", _("display a list of commands or help on a command"));
1117 printf ("%-20s %s\n",
1118 "man", _("read the manual"));
1119 printf ("%-20s %s\n",
1120 "quit", _("quit guestfish"));
1122 printf ("%-20s %s\n",
1123 "alloc", _("allocate an image"));
1124 printf ("%-20s %s\n",
1125 "echo", _("display a line of text"));
1126 printf ("%-20s %s\n",
1127 "edit", _("edit a file in the image"));
1128 printf ("%-20s %s\n",
1129 "lcd", _("local change directory"));
1130 printf ("%-20s %s\n",
1131 "glob", _("expand wildcards in command"));
1132 printf ("%-20s %s\n",
1133 "more", _("view a file in the pager"));
1134 printf ("%-20s %s\n",
1135 "reopen", _("close and reopen libguestfs handle"));
1136 printf ("%-20s %s\n",
1137 "sparse", _("allocate a sparse image file"));
1138 printf ("%-20s %s\n",
1139 "supported", _("list supported groups of commands"));
1140 printf ("%-20s %s\n",
1141 "time", _("measure time taken to run command"));
1143 /* actions are printed after this (see list_commands) */
1147 display_builtin_command (const char *cmd)
1149 /* help for actions is auto-generated, see display_command */
1151 if (STRCASEEQ (cmd, "alloc") ||
1152 STRCASEEQ (cmd, "allocate")) {
1153 printf (_("alloc - allocate an image\n"
1154 " alloc <filename> <size>\n"
1156 " This creates an empty (zeroed) file of the given size,\n"
1157 " and then adds so it can be further examined.\n"
1159 " For more advanced image creation, see qemu-img utility.\n"
1161 " Size can be specified using standard suffixes, eg. '1M'.\n"
1165 else if (STRCASEEQ (cmd, "echo")) {
1166 printf (_("echo - display a line of text\n"
1167 " echo [<params> ...]\n"
1169 " This echos the parameters to the terminal.\n"));
1172 else if (STRCASEEQ (cmd, "edit") ||
1173 STRCASEEQ (cmd, "vi") ||
1174 STRCASEEQ (cmd, "emacs")) {
1175 printf (_("edit - edit a file in the image\n"
1176 " edit <filename>\n"
1178 " This is used to edit a file.\n"
1180 " It is the equivalent of (and is implemented by)\n"
1181 " running \"cat\", editing locally, and then \"write\".\n"
1183 " Normally it uses $EDITOR, but if you use the aliases\n"
1184 " \"vi\" or \"emacs\" you will get those editors.\n"
1186 " NOTE: This will not work reliably for large files\n"
1187 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1190 else if (STRCASEEQ (cmd, "lcd")) {
1191 printf (_("lcd - local change directory\n"
1192 " lcd <directory>\n"
1194 " Change guestfish's current directory. This command is\n"
1195 " useful if you want to download files to a particular\n"
1199 else if (STRCASEEQ (cmd, "glob")) {
1200 printf (_("glob - expand wildcards in command\n"
1201 " glob <command> [<args> ...]\n"
1203 " Glob runs <command> with wildcards expanded in any\n"
1204 " command args. Note that the command is run repeatedly\n"
1205 " once for each expanded argument.\n"));
1208 else if (STRCASEEQ (cmd, "man") ||
1209 STRCASEEQ (cmd, "manual")) {
1210 printf (_("man - read the manual\n"
1213 " Opens the manual page for guestfish.\n"));
1216 else if (STRCASEEQ (cmd, "help")) {
1217 printf (_("help - display a list of commands or help on a command\n"
1222 else if (STRCASEEQ (cmd, "more") ||
1223 STRCASEEQ (cmd, "less")) {
1224 printf (_("more - view a file in the pager\n"
1225 " more <filename>\n"
1227 " This is used to view a file in the pager.\n"
1229 " It is the equivalent of (and is implemented by)\n"
1230 " running \"cat\" and using the pager.\n"
1232 " Normally it uses $PAGER, but if you use the alias\n"
1233 " \"less\" then it always uses \"less\".\n"
1235 " NOTE: This will not work reliably for large files\n"
1236 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1239 else if (STRCASEEQ (cmd, "quit") ||
1240 STRCASEEQ (cmd, "exit") ||
1241 STRCASEEQ (cmd, "q")) {
1242 printf (_("quit - quit guestfish\n"
1246 else if (STRCASEEQ (cmd, "reopen")) {
1247 printf (_("reopen - close and reopen the libguestfs handle\n"
1250 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1251 "this normally, because the handle is closed properly when guestfish\n"
1252 "exits. However this is occasionally useful for testing.\n"));
1255 else if (STRCASEEQ (cmd, "sparse")) {
1256 printf (_("sparse - allocate a sparse image file\n"
1257 " sparse <filename> <size>\n"
1259 " This creates an empty sparse file of the given size,\n"
1260 " and then adds so it can be further examined.\n"
1262 " In all respects it works the same as the 'alloc'\n"
1263 " command, except that the image file is allocated\n"
1264 " sparsely, which means that disk blocks are not assigned\n"
1265 " to the file until they are needed. Sparse disk files\n"
1266 " only use space when written to, but they are slower\n"
1267 " and there is a danger you could run out of real disk\n"
1268 " space during a write operation.\n"
1270 " For more advanced image creation, see qemu-img utility.\n"
1272 " Size can be specified using standard suffixes, eg. '1M'.\n"
1276 else if (STRCASEEQ (cmd, "supported")) {
1277 printf (_("supported - list supported groups of commands\n"
1280 " This command returns a list of the optional groups\n"
1281 " known to the daemon, and indicates which ones are\n"
1282 " supported by this build of the libguestfs appliance.\n"
1284 " See also guestfs(3) section AVAILABILITY.\n"
1288 else if (STRCASEEQ (cmd, "time")) {
1289 printf (_("time - measure time taken to run command\n"
1290 " time <command> [<args> ...]\n"
1292 " This runs <command> as usual, and prints the elapsed\n"
1293 " time afterwards.\n"));
1297 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1303 /* This is printed when the user types in an unknown command for the
1304 * first command issued. A common case is the user doing:
1305 * guestfish disk.img
1306 * expecting guestfish to open 'disk.img' (in fact, this tried to
1307 * run a command 'disk.img').
1310 extended_help_message (void)
1313 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1314 "For a list of commands: guestfish -h\n"
1315 "For complete documentation: man guestfish\n"));
1319 free_strings (char **argv)
1323 for (argc = 0; argv[argc] != NULL; ++argc)
1329 count_strings (char *const *argv)
1333 for (c = 0; argv[c]; ++c)
1339 print_strings (char *const *argv)
1343 for (argc = 0; argv[argc] != NULL; ++argc)
1344 printf ("%s\n", argv[argc]);
1348 print_table (char *const *argv)
1352 for (i = 0; argv[i] != NULL; i += 2)
1353 printf ("%s: %s\n", argv[i], argv[i+1]);
1357 is_true (const char *str)
1360 STRCASENEQ (str, "0") &&
1361 STRCASENEQ (str, "f") &&
1362 STRCASENEQ (str, "false") &&
1363 STRCASENEQ (str, "n") &&
1364 STRCASENEQ (str, "no");
1367 /* Free strings from a non-NULL terminated char** */
1369 free_n_strings (char **str, size_t len)
1373 for (i = 0; i < len; i++) {
1380 parse_string_list (const char *str)
1383 size_t argv_len = 0;
1385 /* Current position pointer */
1386 const char *p = str;
1388 /* Token might be simple:
1391 * 'This is a single token'
1392 * or contain embedded single-quoted sections:
1393 * This' is a sing'l'e to'ken
1395 * The latter may seem over-complicated, but it's what a normal shell does.
1396 * Not doing it risks surprising somebody.
1398 * This outer loop is over complete tokens.
1404 /* Skip leading whitespace */
1405 p += strspn (p, " \t");
1409 /* This loop is over token 'fragments'. A token can be in multiple bits if
1410 * it contains single quotes. We also treat both sides of an escaped quote
1411 * as separate fragments because we can't just copy it: we have to remove
1414 while (*p && (!c_isblank (*p) || in_quote)) {
1415 const char *end = p;
1417 /* Check if the fragment starts with a quote */
1419 /* Toggle in_quote */
1420 in_quote = !in_quote;
1422 /* Skip the quote */
1426 /* If we're in a quote, look for an end quote */
1428 end += strcspn (end, "'");
1431 /* Otherwise, look for whitespace or a quote */
1433 end += strcspn (end, " \t'");
1436 /* Grow the token to accommodate the fragment */
1437 size_t tok_end = tok_len;
1439 char *tok_new = realloc (tok, tok_len + 1);
1440 if (NULL == tok_new) {
1442 free_n_strings (argv, argv_len);
1444 exit (EXIT_FAILURE);
1448 /* Check if we stopped on an escaped quote */
1449 if ('\'' == *end && end != p && *(end-1) == '\\') {
1450 /* Add everything before \' to the token */
1451 memcpy (&tok[tok_end], p, end - p - 1);
1454 tok[tok_len-1] = '\'';
1456 /* Already processed the quote */
1461 /* Add the whole fragment */
1462 memcpy (&tok[tok_end], p, end - p);
1468 /* We've reached the end of a token. We shouldn't still be in quotes. */
1470 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1472 free_n_strings (argv, argv_len);
1477 /* Add this token if there is one. There might not be if there was
1478 * whitespace at the end of the input string */
1480 /* Add the NULL terminator */
1481 tok[tok_len] = '\0';
1483 /* Add the argument to the argument list */
1485 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1486 if (NULL == argv_new) {
1488 free_n_strings (argv, argv_len-1);
1490 exit (EXIT_FAILURE);
1494 argv[argv_len-1] = tok;
1498 /* NULL terminate the argument list */
1500 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1501 if (NULL == argv_new) {
1503 free_n_strings (argv, argv_len-1);
1504 exit (EXIT_FAILURE);
1508 argv[argv_len-1] = NULL;
1513 #ifdef HAVE_LIBREADLINE
1514 static char histfile[1024];
1515 static int nr_history_lines = 0;
1519 initialize_readline (void)
1521 #ifdef HAVE_LIBREADLINE
1524 home = getenv ("HOME");
1526 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1528 (void) read_history (histfile);
1531 rl_readline_name = "guestfish";
1532 rl_attempted_completion_function = do_completion;
1534 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1535 * call the readline(), which happens later. Therefore, these
1536 * provide default values which can be overridden by the user if
1539 (void) rl_variable_bind ("completion-ignore-case", "on");
1544 cleanup_readline (void)
1546 #ifdef HAVE_LIBREADLINE
1549 if (histfile[0] != '\0') {
1550 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1557 #ifdef HAVE_APPEND_HISTORY
1558 (void) append_history (nr_history_lines, histfile);
1560 (void) write_history (histfile);
1566 #ifdef HAVE_LIBREADLINE
1568 add_history_line (const char *line)
1576 xwrite (int fd, const void *v_buf, size_t len)
1579 const char *buf = v_buf;
1582 r = write (fd, buf, len);
1594 /* Resolve the special "win:..." form for Windows-specific paths.
1595 * This always returns a newly allocated string which is freed by the
1596 * caller function in "cmds.c".
1599 resolve_win_path (const char *path)
1604 if (STRCASENEQLEN (path, "win:", 4)) {
1605 ret = strdup (path);
1613 /* Drop drive letter, if it's "C:". */
1614 if (STRCASEEQLEN (path, "c:", 2))
1624 ret = strdup (path);
1630 /* Blindly convert any backslashes into forward slashes. Is this good? */
1631 for (i = 0; i < strlen (ret); ++i)
1635 char *t = guestfs_case_sensitive_path (g, ret);
1642 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1643 * The caller (cmds.c) will call free_file_in after the command has
1644 * run which should clean up resources.
1646 static char *file_in_heredoc (const char *endmarker);
1647 static char *file_in_tmpfile = NULL;
1650 file_in (const char *arg)
1654 if (STREQ (arg, "-")) {
1655 ret = strdup ("/dev/stdin");
1661 else if (STRPREFIX (arg, "-<<")) {
1662 const char *endmarker = &arg[3];
1663 if (*endmarker == '\0') {
1664 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1668 ret = file_in_heredoc (endmarker);
1684 file_in_heredoc (const char *endmarker)
1686 static const char template[] = "/tmp/heredocXXXXXX";
1687 file_in_tmpfile = strdup (template);
1688 if (file_in_tmpfile == NULL) {
1693 int fd = mkstemp (file_in_tmpfile);
1699 size_t markerlen = strlen (endmarker);
1701 char buffer[BUFSIZ];
1702 int write_error = 0;
1703 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1704 /* Look for "END"<EOF> or "END\n" in input. */
1705 size_t blen = strlen (buffer);
1706 if (STREQLEN (buffer, endmarker, markerlen) &&
1707 (blen == markerlen ||
1708 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1711 if (xwrite (fd, buffer, blen) == -1) {
1712 if (!write_error) perror ("write");
1714 /* continue reading up to the end marker */
1718 /* Reached EOF of stdin without finding the end marker, which
1719 * is likely to be an error.
1721 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1722 program_name, endmarker);
1731 if (close (fd) == -1) {
1736 return file_in_tmpfile;
1739 unlink (file_in_tmpfile);
1742 free (file_in_tmpfile);
1743 file_in_tmpfile = NULL;
1748 free_file_in (char *s)
1750 if (file_in_tmpfile) {
1751 if (unlink (file_in_tmpfile) == -1)
1752 perror (file_in_tmpfile);
1753 file_in_tmpfile = NULL;
1756 /* Free the device or file name which was strdup'd in file_in().
1757 * Note it's not immediately clear, but for -<< heredocs,
1758 * s == file_in_tmpfile, so this frees up that buffer.
1763 /* Resolve the special FileOut paths ("-" or filename).
1764 * The caller (cmds.c) will call free (str) after the command has run.
1767 file_out (const char *arg)
1771 if (STREQ (arg, "-"))
1772 ret = strdup ("/dev/stdout");
1783 /* Read a passphrase ('Key') from /dev/tty with echo off.
1784 * The caller (cmds.c) will call free on the string afterwards.
1785 * Based on the code in cryptsetup file lib/utils.c.
1788 read_key (const char *param)
1791 struct termios orig, temp;
1794 /* Read and write to /dev/tty if available. */
1795 if (keys_from_stdin ||
1796 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1801 /* Print the prompt and set no echo. */
1802 int tty = isatty (fileno (infp));
1805 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1807 if (tcgetattr (fileno (infp), &orig) == -1) {
1808 perror ("tcgetattr");
1811 memcpy (&temp, &orig, sizeof temp);
1812 temp.c_lflag &= ~ECHO;
1814 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1820 len = getline (&ret, &n, infp);
1827 /* Remove the terminating \n if there is one. */
1828 if (len > 0 && ret[len-1] == '\n')
1832 /* Restore echo, close file descriptor. */
1835 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1839 fclose (infp); /* outfp == infp, so this is closed also */
1845 print_shell_quote (FILE *stream, const char *str)
1847 #define SAFE(c) (c_isalnum((c)) || \
1848 (c) == '/' || (c) == '-' || (c) == '_' || (c) == '.')
1851 for (i = 0; str[i]; ++i) {
1853 putc ('\\', stream);
1854 putc (str[i], stream);