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>
35 #ifdef HAVE_LIBREADLINE
36 #include <readline/readline.h>
37 #include <readline/history.h>
47 /* List of drives added via -a, -d or -N options. */
50 enum { drv_a, drv_d, drv_N } type;
53 char *filename; /* disk filename */
56 char *guest; /* guest name */
59 char *filename; /* disk filename (testX.img) */
60 prep_data *data; /* prepared type */
61 char *device; /* device inside the appliance */
72 static void set_up_terminal (void);
73 static char add_drives (struct drv *drv, char next_drive);
74 static void prepare_drives (struct drv *drv);
75 static void mount_mps (struct mp *mp);
76 static int launch (void);
77 static void interactive (void);
78 static void shell_script (void);
79 static void script (int prompt);
80 static void cmdline (char *argv[], int optind, int argc);
81 static void initialize_readline (void);
82 static void cleanup_readline (void);
83 #ifdef HAVE_LIBREADLINE
84 static void add_history_line (const char *);
87 static int override_progress_bars = -1;
89 /* Currently open libguestfs handle. */
95 int remote_control_listen = 0;
96 int remote_control = 0;
97 int exit_on_error = 1;
99 int keys_from_stdin = 0;
100 const char *libvirt_uri = NULL;
103 int have_terminfo = 0;
104 int progress_bars = 0;
106 static void __attribute__((noreturn))
109 if (status != EXIT_SUCCESS)
110 fprintf (stderr, _("Try `%s --help' for more information.\n"),
114 _("%s: guest filesystem shell\n"
115 "%s lets you edit virtual machine filesystems\n"
116 "Copyright (C) 2009-2010 Red Hat Inc.\n"
118 " %s [--options] cmd [: cmd : cmd ...]\n"
119 " %s [--ro] -i -a disk-image\n"
120 " %s [--ro] -i -d libvirt-domain\n"
121 "or for interactive use:\n"
123 "or from a shell script:\n"
129 " -h|--cmd-help List available commands\n"
130 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
131 " -a|--add image Add image\n"
132 " -c|--connect uri Specify libvirt URI for -d option\n"
133 " -d|--domain guest Add disks from libvirt guest\n"
134 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
135 " -f|--file file Read commands from file\n"
136 " -i|--inspector Automatically mount filesystems\n"
137 " --keys-from-stdin Read passphrases from stdin\n"
138 " --listen Listen for remote commands\n"
139 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
140 " -n|--no-sync Don't autosync\n"
141 " -N|--new type Create prepared disk (test1.img, ...)\n"
142 " --progress-bars Enable progress bars even when not interactive\n"
143 " --no-progress-bars Disable progress bars\n"
144 " --remote[=pid] Send commands to remote %s\n"
145 " -r|--ro Mount read-only\n"
146 " --selinux Enable SELinux support\n"
147 " -v|--verbose Verbose messages\n"
148 " -x Echo each command before executing it\n"
149 " -V|--version Display version and exit\n"
150 "For more information, see the manpage %s(1).\n"),
151 program_name, program_name, program_name,
152 program_name, program_name, program_name,
153 program_name, program_name, program_name);
159 main (int argc, char *argv[])
161 /* Set global program name that is not polluted with libtool artifacts. */
162 set_program_name (argv[0]);
164 atexit (close_stdout);
166 setlocale (LC_ALL, "");
167 bindtextdomain (PACKAGE, LOCALEBASEDIR);
168 textdomain (PACKAGE);
172 enum { HELP_OPTION = CHAR_MAX + 1 };
174 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
175 static const struct option long_options[] = {
176 { "add", 1, 0, 'a' },
177 { "cmd-help", 2, 0, 'h' },
178 { "connect", 1, 0, 'c' },
179 { "domain", 1, 0, 'd' },
180 { "file", 1, 0, 'f' },
181 { "help", 0, 0, HELP_OPTION },
182 { "inspector", 0, 0, 'i' },
183 { "keys-from-stdin", 0, 0, 0 },
184 { "listen", 0, 0, 0 },
185 { "mount", 1, 0, 'm' },
186 { "new", 1, 0, 'N' },
187 { "no-dest-paths", 0, 0, 'D' },
188 { "no-sync", 0, 0, 'n' },
189 { "progress-bars", 0, 0, 0 },
190 { "no-progress-bars", 0, 0, 0 },
191 { "remote", 2, 0, 0 },
193 { "selinux", 0, 0, 0 },
194 { "verbose", 0, 0, 'v' },
195 { "version", 0, 0, 'V' },
198 struct drv *drvs = NULL;
200 struct mp *mps = NULL;
202 char *p, *file = NULL;
206 int next_prepared_drive = 1;
208 initialize_readline ();
210 memset (&sa, 0, sizeof sa);
211 sa.sa_handler = SIG_IGN;
212 sa.sa_flags = SA_RESTART;
213 sigaction (SIGPIPE, &sa, NULL);
215 /* guestfs_create is meant to be a lightweight operation, so
216 * it's OK to do it early here.
218 g = guestfs_create ();
220 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
224 guestfs_set_autosync (g, 1);
226 /* If developing, add ./appliance to the path. Note that libtools
227 * interferes with this because uninstalled guestfish is a shell
228 * script that runs the real program with an absolute path. Detect
231 * BUT if LIBGUESTFS_PATH environment variable is already set by
232 * the user, then don't override it.
234 if (getenv ("LIBGUESTFS_PATH") == NULL &&
236 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
237 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
239 /* CAUTION: we are careful to modify argv[0] here, only after
240 * using it just above.
242 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
243 * of the original, in case it's needed below.
245 char *real_argv0 = argv[0];
246 argv[0] = bad_cast (program_name);
249 c = getopt_long (argc, argv, options, long_options, &option_index);
253 case 0: /* options which are long only */
254 if (STREQ (long_options[option_index].name, "listen"))
255 remote_control_listen = 1;
256 else if (STREQ (long_options[option_index].name, "remote")) {
258 if (sscanf (optarg, "%d", &remote_control) != 1) {
259 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
260 program_name, optarg);
264 p = getenv ("GUESTFISH_PID");
265 if (!p || sscanf (p, "%d", &remote_control) != 1) {
266 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
267 " to the PID of the remote process\n"),
272 } else if (STREQ (long_options[option_index].name, "selinux")) {
273 guestfs_set_selinux (g, 1);
274 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
276 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
277 override_progress_bars = 1;
278 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
279 override_progress_bars = 0;
281 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
282 program_name, long_options[option_index].name, option_index);
288 if (access (optarg, R_OK) != 0) {
292 drv = malloc (sizeof (struct drv));
298 drv->a.filename = optarg;
304 libvirt_uri = optarg;
308 drv = malloc (sizeof (struct drv));
314 drv->d.guest = optarg;
320 if (STRCASEEQ (optarg, "list") ||
321 STRCASEEQ (optarg, "help") ||
322 STRCASEEQ (optarg, "h") ||
323 STRCASEEQ (optarg, "?")) {
324 list_prepared_drives ();
327 drv = malloc (sizeof (struct drv));
333 if (asprintf (&drv->N.filename, "test%d.img",
334 next_prepared_drive++) == -1) {
338 drv->N.data = create_prepared_file (optarg, drv->N.filename);
339 drv->N.device = NULL; /* filled in by add_drives */
345 complete_dest_paths = 0;
350 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
361 r = display_command (optarg);
362 else if (argv[optind] && argv[optind][0] != '-')
363 r = display_command (argv[optind++]);
367 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
375 mp = malloc (sizeof (struct mp));
380 p = strchr (optarg, ':');
383 mp->mountpoint = p+1;
385 mp->mountpoint = bad_cast ("/");
392 guestfs_set_autosync (g, 0);
401 guestfs_set_verbose (g, verbose);
405 struct guestfs_version *v = guestfs_version (g);
406 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
407 v->major, v->minor, v->release, v->extra);
412 guestfs_set_trace (g, 1);
416 usage (EXIT_SUCCESS);
419 usage (EXIT_FAILURE);
423 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
424 * previously, if we have -i without any drives but with something
425 * on the command line, it must be old-style syntax.
427 if (inspector && drvs == NULL && optind < argc) {
428 while (optind < argc) {
429 if (strchr (argv[optind], '/') ||
430 access (argv[optind], F_OK) == 0) { /* simulate -a option */
431 drv = malloc (sizeof (struct drv));
437 drv->a.filename = argv[optind];
440 } else { /* simulate -d option */
441 drv = malloc (sizeof (struct drv));
447 drv->d.guest = argv[optind];
456 /* If we've got drives to add, add them now. */
457 add_drives (drvs, 'a');
459 /* If we've got mountpoints or prepared drives or -i option, we must
460 * launch the guest and mount them.
462 if (next_prepared_drive > 1 || mps != NULL || inspector) {
463 /* RHBZ#612178: If --listen flag is given, then we will fork into
464 * the background in rc_listen(). However you can't do this while
465 * holding a libguestfs handle open because the recovery process
466 * will think the main program has died and kill qemu. Therefore
467 * don't use the recovery process for this case. (A better
468 * solution would be to call launch () etc after the fork, but
469 * that greatly complicates the code here).
471 if (remote_control_listen)
472 guestfs_set_recovery_proc (g, 0);
474 if (launch () == -1) exit (EXIT_FAILURE);
479 prepare_drives (drvs);
483 /* Remote control? */
484 if (remote_control_listen && remote_control) {
486 _("%s: cannot use --listen and --remote options at the same time\n"),
491 if (remote_control_listen) {
494 _("%s: extra parameters on the command line with --listen flag\n"),
500 _("%s: cannot use --listen and --file options at the same time\n"),
507 /* -f (file) parameter? */
510 if (open (file, O_RDONLY) == -1) {
516 /* Decide if we display progress bars. */
518 override_progress_bars >= 0
519 ? override_progress_bars
520 : (optind >= argc && isatty (0));
523 guestfs_set_progress_callback (g, progress_callback, NULL);
525 /* Interactive, shell script, or command(s) on the command line? */
526 if (optind >= argc) {
533 cmdline (argv, optind, argc);
540 /* The <term.h> header file which defines this has "issues". */
541 extern int tgetent (char *, const char *);
544 set_up_terminal (void)
546 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
547 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
549 char *term = getenv ("TERM");
551 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
555 int r = tgetent (NULL, term);
557 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
561 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
570 pod2text (const char *name, const char *shortdesc, const char *str)
574 fp = popen ("pod2text", "w");
576 /* pod2text failed, maybe not found, so let's just print the
577 * source instead, since that's better than doing nothing.
579 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
582 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
587 /* List is built in reverse order, so mount them in reverse order. */
589 mount_mps (struct mp *mp)
594 mount_mps (mp->next);
596 /* Don't use guestfs_mount here because that will default to mount
597 * options -o sync,noatime. For more information, see guestfs(3)
598 * section "LIBGUESTFS GOTCHAS".
600 const char *options = read_only ? "ro" : "";
601 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
603 /* Display possible mountpoints before exiting. */
604 char **fses = guestfs_list_filesystems (g);
605 if (fses == NULL || fses[0] == NULL)
608 _("guestfish: '%s' could not be mounted. Did you mean one of these?\n"),
611 for (i = 0; fses[i] != NULL; i += 2)
612 fprintf (stderr, "\t%s (%s)\n", fses[i], fses[i+1]);
621 add_drives (struct drv *drv, char next_drive)
625 if (next_drive > 'z') {
627 _("guestfish: too many drives added on the command line\n"));
632 next_drive = add_drives (drv->next, next_drive);
637 r = guestfs_add_drive (g, drv->a.filename);
639 r = guestfs_add_drive_ro (g, drv->a.filename);
647 r = add_libvirt_drives (drv->d.guest);
655 /* -N option is not affected by --ro */
656 r = guestfs_add_drive (g, drv->N.filename);
660 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
668 default: /* keep GCC happy */
677 prepare_drives (struct drv *drv)
680 prepare_drives (drv->next);
681 if (drv->type == drv_N)
682 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
689 if (guestfs_is_config (g)) {
690 if (guestfs_launch (g) == -1)
708 #define FISH "><fs> "
710 static char *line_read = NULL;
715 #ifdef HAVE_LIBREADLINE
723 line_read = readline (prompt ? FISH : "");
725 if (line_read && *line_read)
726 add_history_line (line_read);
731 #endif /* HAVE_LIBREADLINE */
733 static char buf[8192];
736 if (prompt) printf (FISH);
737 line_read = fgets (buf, sizeof buf, stdin);
740 len = strlen (line_read);
741 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
755 int global_exit_on_error = !prompt;
760 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
761 "editing virtual machine filesystems.\n"
763 "Type: 'help' for a list of commands\n"
764 " 'man' to read the manual\n"
765 " 'quit' to quit the shell\n"
769 print_inspect_prompt ();
777 exit_on_error = global_exit_on_error;
779 buf = rl_gets (prompt);
785 /* Skip any initial whitespace before the command. */
787 while (*buf && c_isspace (*buf))
792 /* If the next character is '#' then this is a comment. */
793 if (*buf == '#') continue;
795 /* If the next character is '!' then pass the whole lot to system(3). */
803 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
804 WEXITSTATUS (r) != 0)
810 /* If the next character is '-' allow the command to fail without
811 * exiting on error (just for this one command though).
819 /* Get the command (cannot be quoted). */
820 len = strcspn (buf, " \t");
822 if (len == 0) continue;
826 if (buf[len] == '\0') {
833 p += strspn (p, " \t");
835 /* Get the parameters. */
836 while (*p && i < sizeof argv / sizeof argv[0]) {
839 /* Parameters which start with quotes or pipes are treated
840 * specially. Bare parameters are delimited by whitespace.
844 len = strcspn (p, "\"");
845 if (p[len] == '\0') {
846 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
847 if (exit_on_error) exit (EXIT_FAILURE);
850 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
852 _("%s: command arguments not separated by whitespace\n"),
854 if (exit_on_error) exit (EXIT_FAILURE);
858 pend = p[len+1] ? &p[len+2] : &p[len+1];
859 } else if (*p == '\'') {
861 len = strcspn (p, "'");
862 if (p[len] == '\0') {
863 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
864 if (exit_on_error) exit (EXIT_FAILURE);
867 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
869 _("%s: command arguments not separated by whitespace\n"),
871 if (exit_on_error) exit (EXIT_FAILURE);
875 pend = p[len+1] ? &p[len+2] : &p[len+1];
876 } else if (*p == '|') {
881 } else if (*p == '[') {
885 while (*pend && c != 0) {
886 if (*pend == '[') c++;
887 else if (*pend == ']') c--;
892 _("%s: unterminated \"[...]\" sequence\n"), program_name);
893 if (exit_on_error) exit (EXIT_FAILURE);
896 if (*pend && (*pend != ' ' && *pend != '\t')) {
898 _("%s: command arguments not separated by whitespace\n"),
900 if (exit_on_error) exit (EXIT_FAILURE);
905 } else if (*p != ' ' && *p != '\t') {
906 /* If the first character is a ~ then note that this parameter
907 * is a candidate for ~username expansion. NB this does not
908 * apply to quoted parameters.
910 tilde_candidate = *p == '~';
911 len = strcspn (p, " \t");
918 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
923 if (!tilde_candidate)
926 argv[i] = try_tilde_expansion (p);
931 p += strspn (p, " \t");
934 if (i == sizeof argv / sizeof argv[0]) {
935 fprintf (stderr, _("%s: too many arguments\n"), program_name);
936 if (exit_on_error) exit (EXIT_FAILURE);
943 if (issue_command (cmd, argv, pipe) == -1) {
944 if (exit_on_error) exit (EXIT_FAILURE);
949 if (prompt) printf ("\n");
953 cmdline (char *argv[], int optind, int argc)
960 if (optind >= argc) return;
962 cmd = argv[optind++];
963 if (STREQ (cmd, ":")) {
964 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
968 /* Allow -cmd on the command line to mean (temporarily) override
969 * the normal exit on error (RHBZ#578407).
976 params = &argv[optind];
978 /* Search for end of command list or ":" ... */
979 while (optind < argc && STRNEQ (argv[optind], ":"))
982 if (optind == argc) {
983 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
987 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
989 cmdline (argv, optind+1, argc);
994 issue_command (const char *cmd, char *argv[], const char *pipecmd)
997 int stdout_saved_fd = -1;
1001 reset_progress_bar ();
1003 /* This counts the commands issued, starting at 1. */
1006 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1010 if (fflush (stdout) == EOF) {
1011 perror ("failed to flush standard output");
1014 if (pipe (fd) < 0) {
1015 perror ("pipe failed");
1024 if (pid == 0) { /* Child process. */
1026 if (dup2 (fd[0], 0) < 0) {
1027 perror ("dup2 of stdin failed");
1031 r = system (pipecmd);
1036 _exit (WEXITSTATUS (r));
1039 if ((stdout_saved_fd = dup (1)) < 0) {
1040 perror ("failed to dup stdout");
1044 if (dup2 (fd[1], 1) < 0) {
1045 perror ("failed to dup stdout");
1046 close (stdout_saved_fd);
1052 for (argc = 0; argv[argc] != NULL; ++argc)
1055 /* If --remote was set, then send this command to a remote process. */
1057 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1059 /* Otherwise execute it locally. */
1060 else if (STRCASEEQ (cmd, "help")) {
1065 r = display_command (argv[0]);
1067 else if (STRCASEEQ (cmd, "quit") ||
1068 STRCASEEQ (cmd, "exit") ||
1069 STRCASEEQ (cmd, "q")) {
1073 else if (STRCASEEQ (cmd, "alloc") ||
1074 STRCASEEQ (cmd, "allocate"))
1075 r = do_alloc (cmd, argc, argv);
1076 else if (STRCASEEQ (cmd, "copy-in") ||
1077 STRCASEEQ (cmd, "copy_in"))
1078 r = do_copy_in (cmd, argc, argv);
1079 else if (STRCASEEQ (cmd, "copy-out") ||
1080 STRCASEEQ (cmd, "copy_out"))
1081 r = do_copy_out (cmd, argc, argv);
1082 else if (STRCASEEQ (cmd, "echo"))
1083 r = do_echo (cmd, argc, argv);
1084 else if (STRCASEEQ (cmd, "edit") ||
1085 STRCASEEQ (cmd, "vi") ||
1086 STRCASEEQ (cmd, "emacs"))
1087 r = do_edit (cmd, argc, argv);
1088 else if (STRCASEEQ (cmd, "lcd"))
1089 r = do_lcd (cmd, argc, argv);
1090 else if (STRCASEEQ (cmd, "glob"))
1091 r = do_glob (cmd, argc, argv);
1092 else if (STRCASEEQ (cmd, "man") ||
1093 STRCASEEQ (cmd, "manual"))
1094 r = do_man (cmd, argc, argv);
1095 else if (STRCASEEQ (cmd, "more") ||
1096 STRCASEEQ (cmd, "less"))
1097 r = do_more (cmd, argc, argv);
1098 else if (STRCASEEQ (cmd, "reopen"))
1099 r = do_reopen (cmd, argc, argv);
1100 else if (STRCASEEQ (cmd, "sparse"))
1101 r = do_sparse (cmd, argc, argv);
1102 else if (STRCASEEQ (cmd, "supported"))
1103 r = do_supported (cmd, argc, argv);
1104 else if (STRCASEEQ (cmd, "time"))
1105 r = do_time (cmd, argc, argv);
1107 r = run_action (cmd, argc, argv);
1109 /* Always flush stdout after every command, so that messages, results
1110 * etc appear immediately.
1112 if (fflush (stdout) == EOF) {
1113 perror ("failed to flush standard output");
1119 if (dup2 (stdout_saved_fd, 1) < 0) {
1120 perror ("failed to dup2 standard output");
1123 close (stdout_saved_fd);
1124 if (waitpid (pid, NULL, 0) < 0) {
1125 perror ("waiting for command to complete");
1134 list_builtin_commands (void)
1136 /* help, man and quit should appear at the top */
1137 printf ("%-20s %s\n",
1138 "help", _("display a list of commands or help on a command"));
1139 printf ("%-20s %s\n",
1140 "man", _("read the manual"));
1141 printf ("%-20s %s\n",
1142 "quit", _("quit guestfish"));
1144 printf ("%-20s %s\n",
1145 "alloc", _("allocate an image"));
1146 printf ("%-20s %s\n",
1147 "copy-in", _("copy files into an image"));
1148 printf ("%-20s %s\n",
1149 "copy-out", _("copy files out of an image"));
1150 printf ("%-20s %s\n",
1151 "echo", _("display a line of text"));
1152 printf ("%-20s %s\n",
1153 "edit", _("edit a file in the image"));
1154 printf ("%-20s %s\n",
1155 "lcd", _("local change directory"));
1156 printf ("%-20s %s\n",
1157 "glob", _("expand wildcards in command"));
1158 printf ("%-20s %s\n",
1159 "more", _("view a file in the pager"));
1160 printf ("%-20s %s\n",
1161 "reopen", _("close and reopen libguestfs handle"));
1162 printf ("%-20s %s\n",
1163 "sparse", _("allocate a sparse image file"));
1164 printf ("%-20s %s\n",
1165 "supported", _("list supported groups of commands"));
1166 printf ("%-20s %s\n",
1167 "time", _("measure time taken to run command"));
1169 /* actions are printed after this (see list_commands) */
1173 display_builtin_command (const char *cmd)
1175 /* help for actions is auto-generated, see display_command */
1177 if (STRCASEEQ (cmd, "alloc") ||
1178 STRCASEEQ (cmd, "allocate")) {
1179 printf (_("alloc - allocate an image\n"
1180 " alloc <filename> <size>\n"
1182 " This creates an empty (zeroed) file of the given size,\n"
1183 " and then adds so it can be further examined.\n"
1185 " For more advanced image creation, see qemu-img utility.\n"
1187 " Size can be specified using standard suffixes, eg. '1M'.\n"
1191 else if (STRCASEEQ (cmd, "copy-in") ||
1192 STRCASEEQ (cmd, "copy_in")) {
1193 printf (_("copy-in - copy files into an image\n"
1194 " copy-in <local> [<local> ...] <remotedir>\n"
1196 " Copy local files or directories recursively into the\n"
1197 " image, placing them on a remote directory.\n"
1201 else if (STRCASEEQ (cmd, "copy-out") ||
1202 STRCASEEQ (cmd, "copy_out")) {
1203 printf (_("copy-out - copy files out of an image\n"
1204 " copy-out <remote> [<remote> ...] <localdir>\n"
1206 " Copy remote files or directories recursively out of the\n"
1207 " image, placing them in a local directory.\n"
1211 else if (STRCASEEQ (cmd, "echo")) {
1212 printf (_("echo - display a line of text\n"
1213 " echo [<params> ...]\n"
1215 " This echos the parameters to the terminal.\n"));
1218 else if (STRCASEEQ (cmd, "edit") ||
1219 STRCASEEQ (cmd, "vi") ||
1220 STRCASEEQ (cmd, "emacs")) {
1221 printf (_("edit - edit a file in the image\n"
1222 " edit <filename>\n"
1224 " This is used to edit a file.\n"
1226 " It is the equivalent of (and is implemented by)\n"
1227 " running \"cat\", editing locally, and then \"write\".\n"
1229 " Normally it uses $EDITOR, but if you use the aliases\n"
1230 " \"vi\" or \"emacs\" you will get those editors.\n"));
1233 else if (STRCASEEQ (cmd, "lcd")) {
1234 printf (_("lcd - local change directory\n"
1235 " lcd <directory>\n"
1237 " Change guestfish's current directory. This command is\n"
1238 " useful if you want to download files to a particular\n"
1242 else if (STRCASEEQ (cmd, "glob")) {
1243 printf (_("glob - expand wildcards in command\n"
1244 " glob <command> [<args> ...]\n"
1246 " Glob runs <command> with wildcards expanded in any\n"
1247 " command args. Note that the command is run repeatedly\n"
1248 " once for each expanded argument.\n"));
1251 else if (STRCASEEQ (cmd, "man") ||
1252 STRCASEEQ (cmd, "manual")) {
1253 printf (_("man - read the manual\n"
1256 " Opens the manual page for guestfish.\n"));
1259 else if (STRCASEEQ (cmd, "help")) {
1260 printf (_("help - display a list of commands or help on a command\n"
1265 else if (STRCASEEQ (cmd, "more") ||
1266 STRCASEEQ (cmd, "less")) {
1267 printf (_("more - view a file in the pager\n"
1268 " more <filename>\n"
1270 " This is used to view a file in the pager.\n"
1272 " It is the equivalent of (and is implemented by)\n"
1273 " running \"cat\" and using the pager.\n"
1275 " Normally it uses $PAGER, but if you use the alias\n"
1276 " \"less\" then it always uses \"less\".\n"));
1279 else if (STRCASEEQ (cmd, "quit") ||
1280 STRCASEEQ (cmd, "exit") ||
1281 STRCASEEQ (cmd, "q")) {
1282 printf (_("quit - quit guestfish\n"
1286 else if (STRCASEEQ (cmd, "reopen")) {
1287 printf (_("reopen - close and reopen the libguestfs handle\n"
1290 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1291 "this normally, because the handle is closed properly when guestfish\n"
1292 "exits. However this is occasionally useful for testing.\n"));
1295 else if (STRCASEEQ (cmd, "sparse")) {
1296 printf (_("sparse - allocate a sparse image file\n"
1297 " sparse <filename> <size>\n"
1299 " This creates an empty sparse file of the given size,\n"
1300 " and then adds so it can be further examined.\n"
1302 " In all respects it works the same as the 'alloc'\n"
1303 " command, except that the image file is allocated\n"
1304 " sparsely, which means that disk blocks are not assigned\n"
1305 " to the file until they are needed. Sparse disk files\n"
1306 " only use space when written to, but they are slower\n"
1307 " and there is a danger you could run out of real disk\n"
1308 " space during a write operation.\n"
1310 " For more advanced image creation, see qemu-img utility.\n"
1312 " Size can be specified using standard suffixes, eg. '1M'.\n"
1316 else if (STRCASEEQ (cmd, "supported")) {
1317 printf (_("supported - list supported groups of commands\n"
1320 " This command returns a list of the optional groups\n"
1321 " known to the daemon, and indicates which ones are\n"
1322 " supported by this build of the libguestfs appliance.\n"
1324 " See also guestfs(3) section AVAILABILITY.\n"
1328 else if (STRCASEEQ (cmd, "time")) {
1329 printf (_("time - measure time taken to run command\n"
1330 " time <command> [<args> ...]\n"
1332 " This runs <command> as usual, and prints the elapsed\n"
1333 " time afterwards.\n"));
1337 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1343 /* This is printed when the user types in an unknown command for the
1344 * first command issued. A common case is the user doing:
1345 * guestfish disk.img
1346 * expecting guestfish to open 'disk.img' (in fact, this tried to
1347 * run a command 'disk.img').
1350 extended_help_message (void)
1353 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1354 "For a list of commands: guestfish -h\n"
1355 "For complete documentation: man guestfish\n"));
1359 free_strings (char **argv)
1363 for (argc = 0; argv[argc] != NULL; ++argc)
1369 count_strings (char *const *argv)
1373 for (c = 0; argv[c]; ++c)
1379 print_strings (char *const *argv)
1383 for (argc = 0; argv[argc] != NULL; ++argc)
1384 printf ("%s\n", argv[argc]);
1388 print_table (char *const *argv)
1392 for (i = 0; argv[i] != NULL; i += 2)
1393 printf ("%s: %s\n", argv[i], argv[i+1]);
1397 is_true (const char *str)
1400 STRCASENEQ (str, "0") &&
1401 STRCASENEQ (str, "f") &&
1402 STRCASENEQ (str, "false") &&
1403 STRCASENEQ (str, "n") &&
1404 STRCASENEQ (str, "no");
1407 /* Free strings from a non-NULL terminated char** */
1409 free_n_strings (char **str, size_t len)
1413 for (i = 0; i < len; i++) {
1420 parse_string_list (const char *str)
1423 size_t argv_len = 0;
1425 /* Current position pointer */
1426 const char *p = str;
1428 /* Token might be simple:
1431 * 'This is a single token'
1432 * or contain embedded single-quoted sections:
1433 * This' is a sing'l'e to'ken
1435 * The latter may seem over-complicated, but it's what a normal shell does.
1436 * Not doing it risks surprising somebody.
1438 * This outer loop is over complete tokens.
1444 /* Skip leading whitespace */
1445 p += strspn (p, " \t");
1449 /* This loop is over token 'fragments'. A token can be in multiple bits if
1450 * it contains single quotes. We also treat both sides of an escaped quote
1451 * as separate fragments because we can't just copy it: we have to remove
1454 while (*p && (!c_isblank (*p) || in_quote)) {
1455 const char *end = p;
1457 /* Check if the fragment starts with a quote */
1459 /* Toggle in_quote */
1460 in_quote = !in_quote;
1462 /* Skip the quote */
1466 /* If we're in a quote, look for an end quote */
1468 end += strcspn (end, "'");
1471 /* Otherwise, look for whitespace or a quote */
1473 end += strcspn (end, " \t'");
1476 /* Grow the token to accommodate the fragment */
1477 size_t tok_end = tok_len;
1479 char *tok_new = realloc (tok, tok_len + 1);
1480 if (NULL == tok_new) {
1482 free_n_strings (argv, argv_len);
1484 exit (EXIT_FAILURE);
1488 /* Check if we stopped on an escaped quote */
1489 if ('\'' == *end && end != p && *(end-1) == '\\') {
1490 /* Add everything before \' to the token */
1491 memcpy (&tok[tok_end], p, end - p - 1);
1494 tok[tok_len-1] = '\'';
1496 /* Already processed the quote */
1501 /* Add the whole fragment */
1502 memcpy (&tok[tok_end], p, end - p);
1508 /* We've reached the end of a token. We shouldn't still be in quotes. */
1510 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1512 free_n_strings (argv, argv_len);
1517 /* Add this token if there is one. There might not be if there was
1518 * whitespace at the end of the input string */
1520 /* Add the NULL terminator */
1521 tok[tok_len] = '\0';
1523 /* Add the argument to the argument list */
1525 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1526 if (NULL == argv_new) {
1528 free_n_strings (argv, argv_len-1);
1530 exit (EXIT_FAILURE);
1534 argv[argv_len-1] = tok;
1538 /* NULL terminate the argument list */
1540 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1541 if (NULL == argv_new) {
1543 free_n_strings (argv, argv_len-1);
1544 exit (EXIT_FAILURE);
1548 argv[argv_len-1] = NULL;
1553 #ifdef HAVE_LIBREADLINE
1554 static char histfile[1024];
1555 static int nr_history_lines = 0;
1559 initialize_readline (void)
1561 #ifdef HAVE_LIBREADLINE
1564 home = getenv ("HOME");
1566 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1568 (void) read_history (histfile);
1571 rl_readline_name = "guestfish";
1572 rl_attempted_completion_function = do_completion;
1574 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1575 * call the readline(), which happens later. Therefore, these
1576 * provide default values which can be overridden by the user if
1579 (void) rl_variable_bind ("completion-ignore-case", "on");
1584 cleanup_readline (void)
1586 #ifdef HAVE_LIBREADLINE
1589 if (histfile[0] != '\0') {
1590 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1597 #ifdef HAVE_APPEND_HISTORY
1598 (void) append_history (nr_history_lines, histfile);
1600 (void) write_history (histfile);
1606 #ifdef HAVE_LIBREADLINE
1608 add_history_line (const char *line)
1616 xwrite (int fd, const void *v_buf, size_t len)
1619 const char *buf = v_buf;
1622 r = write (fd, buf, len);
1634 /* Resolve the special "win:..." form for Windows-specific paths.
1635 * This always returns a newly allocated string which is freed by the
1636 * caller function in "cmds.c".
1639 resolve_win_path (const char *path)
1644 if (STRCASENEQLEN (path, "win:", 4)) {
1645 ret = strdup (path);
1653 /* Drop drive letter, if it's "C:". */
1654 if (STRCASEEQLEN (path, "c:", 2))
1664 ret = strdup (path);
1670 /* Blindly convert any backslashes into forward slashes. Is this good? */
1671 for (i = 0; i < strlen (ret); ++i)
1675 char *t = guestfs_case_sensitive_path (g, ret);
1682 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1683 * The caller (cmds.c) will call free_file_in after the command has
1684 * run which should clean up resources.
1686 static char *file_in_heredoc (const char *endmarker);
1687 static char *file_in_tmpfile = NULL;
1690 file_in (const char *arg)
1694 if (STREQ (arg, "-")) {
1695 ret = strdup ("/dev/stdin");
1701 else if (STRPREFIX (arg, "-<<")) {
1702 const char *endmarker = &arg[3];
1703 if (*endmarker == '\0') {
1704 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1708 ret = file_in_heredoc (endmarker);
1724 file_in_heredoc (const char *endmarker)
1726 static const char template[] = "/tmp/heredocXXXXXX";
1727 file_in_tmpfile = strdup (template);
1728 if (file_in_tmpfile == NULL) {
1733 int fd = mkstemp (file_in_tmpfile);
1739 size_t markerlen = strlen (endmarker);
1741 char buffer[BUFSIZ];
1742 int write_error = 0;
1743 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1744 /* Look for "END"<EOF> or "END\n" in input. */
1745 size_t blen = strlen (buffer);
1746 if (STREQLEN (buffer, endmarker, markerlen) &&
1747 (blen == markerlen ||
1748 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1751 if (xwrite (fd, buffer, blen) == -1) {
1752 if (!write_error) perror ("write");
1754 /* continue reading up to the end marker */
1758 /* Reached EOF of stdin without finding the end marker, which
1759 * is likely to be an error.
1761 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1762 program_name, endmarker);
1771 if (close (fd) == -1) {
1776 return file_in_tmpfile;
1779 unlink (file_in_tmpfile);
1782 free (file_in_tmpfile);
1783 file_in_tmpfile = NULL;
1788 free_file_in (char *s)
1790 if (file_in_tmpfile) {
1791 if (unlink (file_in_tmpfile) == -1)
1792 perror (file_in_tmpfile);
1793 file_in_tmpfile = NULL;
1796 /* Free the device or file name which was strdup'd in file_in().
1797 * Note it's not immediately clear, but for -<< heredocs,
1798 * s == file_in_tmpfile, so this frees up that buffer.
1803 /* Resolve the special FileOut paths ("-" or filename).
1804 * The caller (cmds.c) will call free (str) after the command has run.
1807 file_out (const char *arg)
1811 if (STREQ (arg, "-"))
1812 ret = strdup ("/dev/stdout");
1823 /* Read a passphrase ('Key') from /dev/tty with echo off.
1824 * The caller (cmds.c) will call free on the string afterwards.
1825 * Based on the code in cryptsetup file lib/utils.c.
1828 read_key (const char *param)
1831 struct termios orig, temp;
1834 /* Read and write to /dev/tty if available. */
1835 if (keys_from_stdin ||
1836 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1841 /* Print the prompt and set no echo. */
1842 int tty = isatty (fileno (infp));
1845 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1847 if (tcgetattr (fileno (infp), &orig) == -1) {
1848 perror ("tcgetattr");
1851 memcpy (&temp, &orig, sizeof temp);
1852 temp.c_lflag &= ~ECHO;
1854 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1860 len = getline (&ret, &n, infp);
1867 /* Remove the terminating \n if there is one. */
1868 if (len > 0 && ret[len-1] == '\n')
1872 /* Restore echo, close file descriptor. */
1875 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1879 fclose (infp); /* outfp == infp, so this is closed also */