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>
36 #ifdef HAVE_LIBREADLINE
37 #include <readline/readline.h>
38 #include <readline/history.h>
48 /* List of drives added via -a, -d or -N options. */
51 enum { drv_a, drv_d, drv_N } type;
54 char *filename; /* disk filename */
57 char *guest; /* guest name */
60 char *filename; /* disk filename (testX.img) */
61 prep_data *data; /* prepared type */
62 char *device; /* device inside the appliance */
73 static void set_up_terminal (void);
74 static char add_drives (struct drv *drv, char next_drive);
75 static void prepare_drives (struct drv *drv);
76 static void mount_mps (struct mp *mp);
77 static int launch (void);
78 static void interactive (void);
79 static void shell_script (void);
80 static void script (int prompt);
81 static void cmdline (char *argv[], int optind, int argc);
82 static void initialize_readline (void);
83 static void cleanup_readline (void);
84 #ifdef HAVE_LIBREADLINE
85 static void add_history_line (const char *);
88 static int override_progress_bars = -1;
90 /* Currently open libguestfs handle. */
96 int remote_control_listen = 0;
97 int remote_control = 0;
98 int exit_on_error = 1;
100 int keys_from_stdin = 0;
101 const char *libvirt_uri = NULL;
104 int have_terminfo = 0;
105 int progress_bars = 0;
107 static void __attribute__((noreturn))
110 if (status != EXIT_SUCCESS)
111 fprintf (stderr, _("Try `%s --help' for more information.\n"),
115 _("%s: guest filesystem shell\n"
116 "%s lets you edit virtual machine filesystems\n"
117 "Copyright (C) 2009 Red Hat Inc.\n"
119 " %s [--options] cmd [: cmd : cmd ...]\n"
120 " %s -i libvirt-domain\n"
121 " %s -i disk-image(s)\n"
122 "or for interactive use:\n"
124 "or from a shell script:\n"
130 " -h|--cmd-help List available commands\n"
131 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
132 " -a|--add image Add image\n"
133 " -c|--connect uri Specify libvirt URI for -d option\n"
134 " -d|--domain guest Add disks from libvirt guest\n"
135 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
136 " -f|--file file Read commands from file\n"
137 " -i|--inspector Automatically mount filesystems\n"
138 " --keys-from-stdin Read passphrases from stdin\n"
139 " --listen Listen for remote commands\n"
140 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
141 " -n|--no-sync Don't autosync\n"
142 " -N|--new type Create prepared disk (test1.img, ...)\n"
143 " --progress-bars Enable progress bars even when not interactive\n"
144 " --no-progress-bars Disable progress bars\n"
145 " --remote[=pid] Send commands to remote %s\n"
146 " -r|--ro Mount read-only\n"
147 " --selinux Enable SELinux support\n"
148 " -v|--verbose Verbose messages\n"
149 " -x Echo each command before executing it\n"
150 " -V|--version Display version and exit\n"
151 "For more information, see the manpage %s(1).\n"),
152 program_name, program_name, program_name,
153 program_name, program_name, program_name,
154 program_name, program_name, program_name);
160 main (int argc, char *argv[])
162 /* Set global program name that is not polluted with libtool artifacts. */
163 set_program_name (argv[0]);
165 atexit (close_stdout);
167 setlocale (LC_ALL, "");
168 bindtextdomain (PACKAGE, LOCALEBASEDIR);
169 textdomain (PACKAGE);
173 enum { HELP_OPTION = CHAR_MAX + 1 };
175 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
176 static const struct option long_options[] = {
177 { "add", 1, 0, 'a' },
178 { "cmd-help", 2, 0, 'h' },
179 { "connect", 1, 0, 'c' },
180 { "domain", 1, 0, 'd' },
181 { "file", 1, 0, 'f' },
182 { "help", 0, 0, HELP_OPTION },
183 { "inspector", 0, 0, 'i' },
184 { "keys-from-stdin", 0, 0, 0 },
185 { "listen", 0, 0, 0 },
186 { "mount", 1, 0, 'm' },
187 { "new", 1, 0, 'N' },
188 { "no-dest-paths", 0, 0, 'D' },
189 { "no-sync", 0, 0, 'n' },
190 { "progress-bars", 0, 0, 0 },
191 { "no-progress-bars", 0, 0, 0 },
192 { "remote", 2, 0, 0 },
194 { "selinux", 0, 0, 0 },
195 { "verbose", 0, 0, 'v' },
196 { "version", 0, 0, 'V' },
199 struct drv *drvs = NULL;
201 struct mp *mps = NULL;
203 char *p, *file = NULL;
207 int next_prepared_drive = 1;
209 initialize_readline ();
211 memset (&sa, 0, sizeof sa);
212 sa.sa_handler = SIG_IGN;
213 sa.sa_flags = SA_RESTART;
214 sigaction (SIGPIPE, &sa, NULL);
216 /* guestfs_create is meant to be a lightweight operation, so
217 * it's OK to do it early here.
219 g = guestfs_create ();
221 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
225 guestfs_set_autosync (g, 1);
227 /* If developing, add ./appliance to the path. Note that libtools
228 * interferes with this because uninstalled guestfish is a shell
229 * script that runs the real program with an absolute path. Detect
232 * BUT if LIBGUESTFS_PATH environment variable is already set by
233 * the user, then don't override it.
235 if (getenv ("LIBGUESTFS_PATH") == NULL &&
237 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
238 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
240 /* CAUTION: we are careful to modify argv[0] here, only after
241 * using it just above.
243 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
244 * of the original, in case it's needed below.
246 char *real_argv0 = argv[0];
247 argv[0] = bad_cast (program_name);
250 c = getopt_long (argc, argv, options, long_options, &option_index);
254 case 0: /* options which are long only */
255 if (STREQ (long_options[option_index].name, "listen"))
256 remote_control_listen = 1;
257 else if (STREQ (long_options[option_index].name, "remote")) {
259 if (sscanf (optarg, "%d", &remote_control) != 1) {
260 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
261 program_name, optarg);
265 p = getenv ("GUESTFISH_PID");
266 if (!p || sscanf (p, "%d", &remote_control) != 1) {
267 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
268 " to the PID of the remote process\n"),
273 } else if (STREQ (long_options[option_index].name, "selinux")) {
274 guestfs_set_selinux (g, 1);
275 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
277 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
278 override_progress_bars = 1;
279 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
280 override_progress_bars = 0;
282 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
283 program_name, long_options[option_index].name, option_index);
289 if (access (optarg, R_OK) != 0) {
293 drv = malloc (sizeof (struct drv));
299 drv->a.filename = optarg;
305 libvirt_uri = optarg;
309 drv = malloc (sizeof (struct drv));
315 drv->d.guest = optarg;
321 if (STRCASEEQ (optarg, "list") ||
322 STRCASEEQ (optarg, "help") ||
323 STRCASEEQ (optarg, "h") ||
324 STRCASEEQ (optarg, "?")) {
325 list_prepared_drives ();
328 drv = malloc (sizeof (struct drv));
334 if (asprintf (&drv->N.filename, "test%d.img",
335 next_prepared_drive++) == -1) {
339 drv->N.data = create_prepared_file (optarg, drv->N.filename);
340 drv->N.device = NULL; /* filled in by add_drives */
346 complete_dest_paths = 0;
351 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
362 r = display_command (optarg);
363 else if (argv[optind] && argv[optind][0] != '-')
364 r = display_command (argv[optind++]);
368 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
376 mp = malloc (sizeof (struct mp));
381 p = strchr (optarg, ':');
384 mp->mountpoint = p+1;
386 mp->mountpoint = bad_cast ("/");
393 guestfs_set_autosync (g, 0);
402 guestfs_set_verbose (g, verbose);
406 struct guestfs_version *v = guestfs_version (g);
407 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
408 v->major, v->minor, v->release, v->extra);
413 guestfs_set_trace (g, 1);
417 usage (EXIT_SUCCESS);
420 usage (EXIT_FAILURE);
424 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
425 * previously, if we have -i without any drives but with something
426 * on the command line, it must be old-style syntax.
428 if (inspector && drvs == NULL && optind < argc) {
429 while (optind < argc) {
430 if (strchr (argv[optind], '/') ||
431 access (argv[optind], F_OK) == 0) { /* simulate -a option */
432 drv = malloc (sizeof (struct drv));
438 drv->a.filename = argv[optind];
441 } else { /* simulate -d option */
442 drv = malloc (sizeof (struct drv));
448 drv->d.guest = argv[optind];
457 /* If we've got drives to add, add them now. */
458 add_drives (drvs, 'a');
460 /* If we've got mountpoints or prepared drives or -i option, we must
461 * launch the guest and mount them.
463 if (next_prepared_drive > 1 || mps != NULL || inspector) {
464 /* RHBZ#612178: If --listen flag is given, then we will fork into
465 * the background in rc_listen(). However you can't do this while
466 * holding a libguestfs handle open because the recovery process
467 * will think the main program has died and kill qemu. Therefore
468 * don't use the recovery process for this case. (A better
469 * solution would be to call launch () etc after the fork, but
470 * that greatly complicates the code here).
472 if (remote_control_listen)
473 guestfs_set_recovery_proc (g, 0);
475 if (launch () == -1) exit (EXIT_FAILURE);
480 prepare_drives (drvs);
484 /* Remote control? */
485 if (remote_control_listen && remote_control) {
487 _("%s: cannot use --listen and --remote options at the same time\n"),
492 if (remote_control_listen) {
495 _("%s: extra parameters on the command line with --listen flag\n"),
501 _("%s: cannot use --listen and --file options at the same time\n"),
508 /* -f (file) parameter? */
511 if (open (file, O_RDONLY) == -1) {
517 /* Decide if we display progress bars. */
519 override_progress_bars >= 0
520 ? override_progress_bars
521 : (optind >= argc && isatty (0));
524 guestfs_set_progress_callback (g, progress_callback, NULL);
526 /* Interactive, shell script, or command(s) on the command line? */
527 if (optind >= argc) {
534 cmdline (argv, optind, argc);
541 /* The <term.h> header file which defines this has "issues". */
542 extern int tgetent (char *, const char *);
545 set_up_terminal (void)
547 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
548 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
550 char *term = getenv ("TERM");
552 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
556 int r = tgetent (NULL, term);
558 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
562 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
571 pod2text (const char *name, const char *shortdesc, const char *str)
575 fp = popen ("pod2text", "w");
577 /* pod2text failed, maybe not found, so let's just print the
578 * source instead, since that's better than doing nothing.
580 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
583 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
588 /* List is built in reverse order, so mount them in reverse order. */
590 mount_mps (struct mp *mp)
595 mount_mps (mp->next);
597 /* Don't use guestfs_mount here because that will default to mount
598 * options -o sync,noatime. For more information, see guestfs(3)
599 * section "LIBGUESTFS GOTCHAS".
601 const char *options = read_only ? "ro" : "";
602 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
609 add_drives (struct drv *drv, char next_drive)
613 if (next_drive > 'z') {
615 _("guestfish: too many drives added on the command line\n"));
620 next_drive = add_drives (drv->next, next_drive);
625 r = guestfs_add_drive (g, drv->a.filename);
627 r = guestfs_add_drive_ro (g, drv->a.filename);
635 r = add_libvirt_drives (drv->d.guest);
643 /* -N option is not affected by --ro */
644 r = guestfs_add_drive (g, drv->N.filename);
648 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
656 default: /* keep GCC happy */
665 prepare_drives (struct drv *drv)
668 prepare_drives (drv->next);
669 if (drv->type == drv_N)
670 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
677 if (guestfs_is_config (g)) {
678 if (guestfs_launch (g) == -1)
696 #define FISH "><fs> "
698 static char *line_read = NULL;
703 #ifdef HAVE_LIBREADLINE
711 line_read = readline (prompt ? FISH : "");
713 if (line_read && *line_read)
714 add_history_line (line_read);
719 #endif /* HAVE_LIBREADLINE */
721 static char buf[8192];
724 if (prompt) printf (FISH);
725 line_read = fgets (buf, sizeof buf, stdin);
728 len = strlen (line_read);
729 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
743 int global_exit_on_error = !prompt;
748 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
749 "editing virtual machine filesystems.\n"
751 "Type: 'help' for a list of commands\n"
752 " 'man' to read the manual\n"
753 " 'quit' to quit the shell\n"
757 print_inspect_prompt ();
765 exit_on_error = global_exit_on_error;
767 buf = rl_gets (prompt);
773 /* Skip any initial whitespace before the command. */
775 while (*buf && c_isspace (*buf))
780 /* If the next character is '#' then this is a comment. */
781 if (*buf == '#') continue;
783 /* If the next character is '!' then pass the whole lot to system(3). */
791 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
792 WEXITSTATUS (r) != 0)
798 /* If the next character is '-' allow the command to fail without
799 * exiting on error (just for this one command though).
807 /* Get the command (cannot be quoted). */
808 len = strcspn (buf, " \t");
810 if (len == 0) continue;
814 if (buf[len] == '\0') {
821 p += strspn (p, " \t");
823 /* Get the parameters. */
824 while (*p && i < sizeof argv / sizeof argv[0]) {
827 /* Parameters which start with quotes or pipes are treated
828 * specially. Bare parameters are delimited by whitespace.
832 len = strcspn (p, "\"");
833 if (p[len] == '\0') {
834 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
835 if (exit_on_error) exit (EXIT_FAILURE);
838 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
840 _("%s: command arguments not separated by whitespace\n"),
842 if (exit_on_error) exit (EXIT_FAILURE);
846 pend = p[len+1] ? &p[len+2] : &p[len+1];
847 } else if (*p == '\'') {
849 len = strcspn (p, "'");
850 if (p[len] == '\0') {
851 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
852 if (exit_on_error) exit (EXIT_FAILURE);
855 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
857 _("%s: command arguments not separated by whitespace\n"),
859 if (exit_on_error) exit (EXIT_FAILURE);
863 pend = p[len+1] ? &p[len+2] : &p[len+1];
864 } else if (*p == '|') {
869 } else if (*p == '[') {
873 while (*pend && c != 0) {
874 if (*pend == '[') c++;
875 else if (*pend == ']') c--;
880 _("%s: unterminated \"[...]\" sequence\n"), program_name);
881 if (exit_on_error) exit (EXIT_FAILURE);
884 if (*pend && (*pend != ' ' && *pend != '\t')) {
886 _("%s: command arguments not separated by whitespace\n"),
888 if (exit_on_error) exit (EXIT_FAILURE);
893 } else if (*p != ' ' && *p != '\t') {
894 /* If the first character is a ~ then note that this parameter
895 * is a candidate for ~username expansion. NB this does not
896 * apply to quoted parameters.
898 tilde_candidate = *p == '~';
899 len = strcspn (p, " \t");
906 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
911 if (!tilde_candidate)
914 argv[i] = try_tilde_expansion (p);
919 p += strspn (p, " \t");
922 if (i == sizeof argv / sizeof argv[0]) {
923 fprintf (stderr, _("%s: too many arguments\n"), program_name);
924 if (exit_on_error) exit (EXIT_FAILURE);
931 if (issue_command (cmd, argv, pipe) == -1) {
932 if (exit_on_error) exit (EXIT_FAILURE);
937 if (prompt) printf ("\n");
941 cmdline (char *argv[], int optind, int argc)
948 if (optind >= argc) return;
950 cmd = argv[optind++];
951 if (STREQ (cmd, ":")) {
952 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
956 /* Allow -cmd on the command line to mean (temporarily) override
957 * the normal exit on error (RHBZ#578407).
964 params = &argv[optind];
966 /* Search for end of command list or ":" ... */
967 while (optind < argc && STRNEQ (argv[optind], ":"))
970 if (optind == argc) {
971 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
975 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
977 cmdline (argv, optind+1, argc);
982 issue_command (const char *cmd, char *argv[], const char *pipecmd)
985 int stdout_saved_fd = -1;
989 reset_progress_bar ();
991 /* This counts the commands issued, starting at 1. */
994 /* For | ... commands. Annoyingly we can't use popen(3) here. */
998 if (fflush (stdout) == EOF) {
999 perror ("failed to flush standard output");
1002 if (pipe (fd) < 0) {
1003 perror ("pipe failed");
1012 if (pid == 0) { /* Child process. */
1014 if (dup2 (fd[0], 0) < 0) {
1015 perror ("dup2 of stdin failed");
1019 r = system (pipecmd);
1024 _exit (WEXITSTATUS (r));
1027 if ((stdout_saved_fd = dup (1)) < 0) {
1028 perror ("failed to dup stdout");
1032 if (dup2 (fd[1], 1) < 0) {
1033 perror ("failed to dup stdout");
1034 close (stdout_saved_fd);
1040 for (argc = 0; argv[argc] != NULL; ++argc)
1043 /* If --remote was set, then send this command to a remote process. */
1045 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1047 /* Otherwise execute it locally. */
1048 else if (STRCASEEQ (cmd, "help")) {
1053 r = display_command (argv[0]);
1055 else if (STRCASEEQ (cmd, "quit") ||
1056 STRCASEEQ (cmd, "exit") ||
1057 STRCASEEQ (cmd, "q")) {
1061 else if (STRCASEEQ (cmd, "alloc") ||
1062 STRCASEEQ (cmd, "allocate"))
1063 r = do_alloc (cmd, argc, argv);
1064 else if (STRCASEEQ (cmd, "copy-in") ||
1065 STRCASEEQ (cmd, "copy_in"))
1066 r = do_copy_in (cmd, argc, argv);
1067 else if (STRCASEEQ (cmd, "copy-out") ||
1068 STRCASEEQ (cmd, "copy_out"))
1069 r = do_copy_out (cmd, argc, argv);
1070 else if (STRCASEEQ (cmd, "echo"))
1071 r = do_echo (cmd, argc, argv);
1072 else if (STRCASEEQ (cmd, "edit") ||
1073 STRCASEEQ (cmd, "vi") ||
1074 STRCASEEQ (cmd, "emacs"))
1075 r = do_edit (cmd, argc, argv);
1076 else if (STRCASEEQ (cmd, "lcd"))
1077 r = do_lcd (cmd, argc, argv);
1078 else if (STRCASEEQ (cmd, "glob"))
1079 r = do_glob (cmd, argc, argv);
1080 else if (STRCASEEQ (cmd, "man") ||
1081 STRCASEEQ (cmd, "manual"))
1082 r = do_man (cmd, argc, argv);
1083 else if (STRCASEEQ (cmd, "more") ||
1084 STRCASEEQ (cmd, "less"))
1085 r = do_more (cmd, argc, argv);
1086 else if (STRCASEEQ (cmd, "reopen"))
1087 r = do_reopen (cmd, argc, argv);
1088 else if (STRCASEEQ (cmd, "sparse"))
1089 r = do_sparse (cmd, argc, argv);
1090 else if (STRCASEEQ (cmd, "supported"))
1091 r = do_supported (cmd, argc, argv);
1092 else if (STRCASEEQ (cmd, "time"))
1093 r = do_time (cmd, argc, argv);
1095 r = run_action (cmd, argc, argv);
1097 /* Always flush stdout after every command, so that messages, results
1098 * etc appear immediately.
1100 if (fflush (stdout) == EOF) {
1101 perror ("failed to flush standard output");
1107 if (dup2 (stdout_saved_fd, 1) < 0) {
1108 perror ("failed to dup2 standard output");
1111 close (stdout_saved_fd);
1112 if (waitpid (pid, NULL, 0) < 0) {
1113 perror ("waiting for command to complete");
1122 list_builtin_commands (void)
1124 /* help, man and quit should appear at the top */
1125 printf ("%-20s %s\n",
1126 "help", _("display a list of commands or help on a command"));
1127 printf ("%-20s %s\n",
1128 "man", _("read the manual"));
1129 printf ("%-20s %s\n",
1130 "quit", _("quit guestfish"));
1132 printf ("%-20s %s\n",
1133 "alloc", _("allocate an image"));
1134 printf ("%-20s %s\n",
1135 "copy-in", _("copy files into an image"));
1136 printf ("%-20s %s\n",
1137 "copy-out", _("copy files out of an image"));
1138 printf ("%-20s %s\n",
1139 "echo", _("display a line of text"));
1140 printf ("%-20s %s\n",
1141 "edit", _("edit a file in the image"));
1142 printf ("%-20s %s\n",
1143 "lcd", _("local change directory"));
1144 printf ("%-20s %s\n",
1145 "glob", _("expand wildcards in command"));
1146 printf ("%-20s %s\n",
1147 "more", _("view a file in the pager"));
1148 printf ("%-20s %s\n",
1149 "reopen", _("close and reopen libguestfs handle"));
1150 printf ("%-20s %s\n",
1151 "sparse", _("allocate a sparse image file"));
1152 printf ("%-20s %s\n",
1153 "supported", _("list supported groups of commands"));
1154 printf ("%-20s %s\n",
1155 "time", _("measure time taken to run command"));
1157 /* actions are printed after this (see list_commands) */
1161 display_builtin_command (const char *cmd)
1163 /* help for actions is auto-generated, see display_command */
1165 if (STRCASEEQ (cmd, "alloc") ||
1166 STRCASEEQ (cmd, "allocate")) {
1167 printf (_("alloc - allocate an image\n"
1168 " alloc <filename> <size>\n"
1170 " This creates an empty (zeroed) file of the given size,\n"
1171 " and then adds so it can be further examined.\n"
1173 " For more advanced image creation, see qemu-img utility.\n"
1175 " Size can be specified using standard suffixes, eg. '1M'.\n"
1179 else if (STRCASEEQ (cmd, "copy-in") ||
1180 STRCASEEQ (cmd, "copy_in")) {
1181 printf (_("copy-in - copy files into an image\n"
1182 " copy-in <local> [<local> ...] <remotedir>\n"
1184 " Copy local files or directories recursively into the\n"
1185 " image, placing them on a remote directory.\n"
1189 else if (STRCASEEQ (cmd, "copy-out") ||
1190 STRCASEEQ (cmd, "copy_out")) {
1191 printf (_("copy-out - copy files out of an image\n"
1192 " copy-out <remote> [<remote> ...] <localdir>\n"
1194 " Copy remote files or directories recursively out of the\n"
1195 " image, placing them in a local directory.\n"
1199 else if (STRCASEEQ (cmd, "echo")) {
1200 printf (_("echo - display a line of text\n"
1201 " echo [<params> ...]\n"
1203 " This echos the parameters to the terminal.\n"));
1206 else if (STRCASEEQ (cmd, "edit") ||
1207 STRCASEEQ (cmd, "vi") ||
1208 STRCASEEQ (cmd, "emacs")) {
1209 printf (_("edit - edit a file in the image\n"
1210 " edit <filename>\n"
1212 " This is used to edit a file.\n"
1214 " It is the equivalent of (and is implemented by)\n"
1215 " running \"cat\", editing locally, and then \"write\".\n"
1217 " Normally it uses $EDITOR, but if you use the aliases\n"
1218 " \"vi\" or \"emacs\" you will get those editors.\n"
1220 " NOTE: This will not work reliably for large files\n"
1221 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1224 else if (STRCASEEQ (cmd, "lcd")) {
1225 printf (_("lcd - local change directory\n"
1226 " lcd <directory>\n"
1228 " Change guestfish's current directory. This command is\n"
1229 " useful if you want to download files to a particular\n"
1233 else if (STRCASEEQ (cmd, "glob")) {
1234 printf (_("glob - expand wildcards in command\n"
1235 " glob <command> [<args> ...]\n"
1237 " Glob runs <command> with wildcards expanded in any\n"
1238 " command args. Note that the command is run repeatedly\n"
1239 " once for each expanded argument.\n"));
1242 else if (STRCASEEQ (cmd, "man") ||
1243 STRCASEEQ (cmd, "manual")) {
1244 printf (_("man - read the manual\n"
1247 " Opens the manual page for guestfish.\n"));
1250 else if (STRCASEEQ (cmd, "help")) {
1251 printf (_("help - display a list of commands or help on a command\n"
1256 else if (STRCASEEQ (cmd, "more") ||
1257 STRCASEEQ (cmd, "less")) {
1258 printf (_("more - view a file in the pager\n"
1259 " more <filename>\n"
1261 " This is used to view a file in the pager.\n"
1263 " It is the equivalent of (and is implemented by)\n"
1264 " running \"cat\" and using the pager.\n"
1266 " Normally it uses $PAGER, but if you use the alias\n"
1267 " \"less\" then it always uses \"less\".\n"
1269 " NOTE: This will not work reliably for large files\n"
1270 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1273 else if (STRCASEEQ (cmd, "quit") ||
1274 STRCASEEQ (cmd, "exit") ||
1275 STRCASEEQ (cmd, "q")) {
1276 printf (_("quit - quit guestfish\n"
1280 else if (STRCASEEQ (cmd, "reopen")) {
1281 printf (_("reopen - close and reopen the libguestfs handle\n"
1284 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1285 "this normally, because the handle is closed properly when guestfish\n"
1286 "exits. However this is occasionally useful for testing.\n"));
1289 else if (STRCASEEQ (cmd, "sparse")) {
1290 printf (_("sparse - allocate a sparse image file\n"
1291 " sparse <filename> <size>\n"
1293 " This creates an empty sparse file of the given size,\n"
1294 " and then adds so it can be further examined.\n"
1296 " In all respects it works the same as the 'alloc'\n"
1297 " command, except that the image file is allocated\n"
1298 " sparsely, which means that disk blocks are not assigned\n"
1299 " to the file until they are needed. Sparse disk files\n"
1300 " only use space when written to, but they are slower\n"
1301 " and there is a danger you could run out of real disk\n"
1302 " space during a write operation.\n"
1304 " For more advanced image creation, see qemu-img utility.\n"
1306 " Size can be specified using standard suffixes, eg. '1M'.\n"
1310 else if (STRCASEEQ (cmd, "supported")) {
1311 printf (_("supported - list supported groups of commands\n"
1314 " This command returns a list of the optional groups\n"
1315 " known to the daemon, and indicates which ones are\n"
1316 " supported by this build of the libguestfs appliance.\n"
1318 " See also guestfs(3) section AVAILABILITY.\n"
1322 else if (STRCASEEQ (cmd, "time")) {
1323 printf (_("time - measure time taken to run command\n"
1324 " time <command> [<args> ...]\n"
1326 " This runs <command> as usual, and prints the elapsed\n"
1327 " time afterwards.\n"));
1331 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1337 /* This is printed when the user types in an unknown command for the
1338 * first command issued. A common case is the user doing:
1339 * guestfish disk.img
1340 * expecting guestfish to open 'disk.img' (in fact, this tried to
1341 * run a command 'disk.img').
1344 extended_help_message (void)
1347 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1348 "For a list of commands: guestfish -h\n"
1349 "For complete documentation: man guestfish\n"));
1353 free_strings (char **argv)
1357 for (argc = 0; argv[argc] != NULL; ++argc)
1363 count_strings (char *const *argv)
1367 for (c = 0; argv[c]; ++c)
1373 print_strings (char *const *argv)
1377 for (argc = 0; argv[argc] != NULL; ++argc)
1378 printf ("%s\n", argv[argc]);
1382 print_table (char *const *argv)
1386 for (i = 0; argv[i] != NULL; i += 2)
1387 printf ("%s: %s\n", argv[i], argv[i+1]);
1391 is_true (const char *str)
1394 STRCASENEQ (str, "0") &&
1395 STRCASENEQ (str, "f") &&
1396 STRCASENEQ (str, "false") &&
1397 STRCASENEQ (str, "n") &&
1398 STRCASENEQ (str, "no");
1401 /* Free strings from a non-NULL terminated char** */
1403 free_n_strings (char **str, size_t len)
1407 for (i = 0; i < len; i++) {
1414 parse_string_list (const char *str)
1417 size_t argv_len = 0;
1419 /* Current position pointer */
1420 const char *p = str;
1422 /* Token might be simple:
1425 * 'This is a single token'
1426 * or contain embedded single-quoted sections:
1427 * This' is a sing'l'e to'ken
1429 * The latter may seem over-complicated, but it's what a normal shell does.
1430 * Not doing it risks surprising somebody.
1432 * This outer loop is over complete tokens.
1438 /* Skip leading whitespace */
1439 p += strspn (p, " \t");
1443 /* This loop is over token 'fragments'. A token can be in multiple bits if
1444 * it contains single quotes. We also treat both sides of an escaped quote
1445 * as separate fragments because we can't just copy it: we have to remove
1448 while (*p && (!c_isblank (*p) || in_quote)) {
1449 const char *end = p;
1451 /* Check if the fragment starts with a quote */
1453 /* Toggle in_quote */
1454 in_quote = !in_quote;
1456 /* Skip the quote */
1460 /* If we're in a quote, look for an end quote */
1462 end += strcspn (end, "'");
1465 /* Otherwise, look for whitespace or a quote */
1467 end += strcspn (end, " \t'");
1470 /* Grow the token to accommodate the fragment */
1471 size_t tok_end = tok_len;
1473 char *tok_new = realloc (tok, tok_len + 1);
1474 if (NULL == tok_new) {
1476 free_n_strings (argv, argv_len);
1478 exit (EXIT_FAILURE);
1482 /* Check if we stopped on an escaped quote */
1483 if ('\'' == *end && end != p && *(end-1) == '\\') {
1484 /* Add everything before \' to the token */
1485 memcpy (&tok[tok_end], p, end - p - 1);
1488 tok[tok_len-1] = '\'';
1490 /* Already processed the quote */
1495 /* Add the whole fragment */
1496 memcpy (&tok[tok_end], p, end - p);
1502 /* We've reached the end of a token. We shouldn't still be in quotes. */
1504 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1506 free_n_strings (argv, argv_len);
1511 /* Add this token if there is one. There might not be if there was
1512 * whitespace at the end of the input string */
1514 /* Add the NULL terminator */
1515 tok[tok_len] = '\0';
1517 /* Add the argument to the argument list */
1519 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1520 if (NULL == argv_new) {
1522 free_n_strings (argv, argv_len-1);
1524 exit (EXIT_FAILURE);
1528 argv[argv_len-1] = tok;
1532 /* NULL terminate the argument list */
1534 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1535 if (NULL == argv_new) {
1537 free_n_strings (argv, argv_len-1);
1538 exit (EXIT_FAILURE);
1542 argv[argv_len-1] = NULL;
1547 #ifdef HAVE_LIBREADLINE
1548 static char histfile[1024];
1549 static int nr_history_lines = 0;
1553 initialize_readline (void)
1555 #ifdef HAVE_LIBREADLINE
1558 home = getenv ("HOME");
1560 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1562 (void) read_history (histfile);
1565 rl_readline_name = "guestfish";
1566 rl_attempted_completion_function = do_completion;
1568 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1569 * call the readline(), which happens later. Therefore, these
1570 * provide default values which can be overridden by the user if
1573 (void) rl_variable_bind ("completion-ignore-case", "on");
1578 cleanup_readline (void)
1580 #ifdef HAVE_LIBREADLINE
1583 if (histfile[0] != '\0') {
1584 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1591 #ifdef HAVE_APPEND_HISTORY
1592 (void) append_history (nr_history_lines, histfile);
1594 (void) write_history (histfile);
1600 #ifdef HAVE_LIBREADLINE
1602 add_history_line (const char *line)
1610 xwrite (int fd, const void *v_buf, size_t len)
1613 const char *buf = v_buf;
1616 r = write (fd, buf, len);
1628 /* Resolve the special "win:..." form for Windows-specific paths.
1629 * This always returns a newly allocated string which is freed by the
1630 * caller function in "cmds.c".
1633 resolve_win_path (const char *path)
1638 if (STRCASENEQLEN (path, "win:", 4)) {
1639 ret = strdup (path);
1647 /* Drop drive letter, if it's "C:". */
1648 if (STRCASEEQLEN (path, "c:", 2))
1658 ret = strdup (path);
1664 /* Blindly convert any backslashes into forward slashes. Is this good? */
1665 for (i = 0; i < strlen (ret); ++i)
1669 char *t = guestfs_case_sensitive_path (g, ret);
1676 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1677 * The caller (cmds.c) will call free_file_in after the command has
1678 * run which should clean up resources.
1680 static char *file_in_heredoc (const char *endmarker);
1681 static char *file_in_tmpfile = NULL;
1684 file_in (const char *arg)
1688 if (STREQ (arg, "-")) {
1689 ret = strdup ("/dev/stdin");
1695 else if (STRPREFIX (arg, "-<<")) {
1696 const char *endmarker = &arg[3];
1697 if (*endmarker == '\0') {
1698 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1702 ret = file_in_heredoc (endmarker);
1718 file_in_heredoc (const char *endmarker)
1720 static const char template[] = "/tmp/heredocXXXXXX";
1721 file_in_tmpfile = strdup (template);
1722 if (file_in_tmpfile == NULL) {
1727 int fd = mkstemp (file_in_tmpfile);
1733 size_t markerlen = strlen (endmarker);
1735 char buffer[BUFSIZ];
1736 int write_error = 0;
1737 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1738 /* Look for "END"<EOF> or "END\n" in input. */
1739 size_t blen = strlen (buffer);
1740 if (STREQLEN (buffer, endmarker, markerlen) &&
1741 (blen == markerlen ||
1742 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1745 if (xwrite (fd, buffer, blen) == -1) {
1746 if (!write_error) perror ("write");
1748 /* continue reading up to the end marker */
1752 /* Reached EOF of stdin without finding the end marker, which
1753 * is likely to be an error.
1755 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1756 program_name, endmarker);
1765 if (close (fd) == -1) {
1770 return file_in_tmpfile;
1773 unlink (file_in_tmpfile);
1776 free (file_in_tmpfile);
1777 file_in_tmpfile = NULL;
1782 free_file_in (char *s)
1784 if (file_in_tmpfile) {
1785 if (unlink (file_in_tmpfile) == -1)
1786 perror (file_in_tmpfile);
1787 file_in_tmpfile = NULL;
1790 /* Free the device or file name which was strdup'd in file_in().
1791 * Note it's not immediately clear, but for -<< heredocs,
1792 * s == file_in_tmpfile, so this frees up that buffer.
1797 /* Resolve the special FileOut paths ("-" or filename).
1798 * The caller (cmds.c) will call free (str) after the command has run.
1801 file_out (const char *arg)
1805 if (STREQ (arg, "-"))
1806 ret = strdup ("/dev/stdout");
1817 /* Read a passphrase ('Key') from /dev/tty with echo off.
1818 * The caller (cmds.c) will call free on the string afterwards.
1819 * Based on the code in cryptsetup file lib/utils.c.
1822 read_key (const char *param)
1825 struct termios orig, temp;
1828 /* Read and write to /dev/tty if available. */
1829 if (keys_from_stdin ||
1830 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1835 /* Print the prompt and set no echo. */
1836 int tty = isatty (fileno (infp));
1839 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1841 if (tcgetattr (fileno (infp), &orig) == -1) {
1842 perror ("tcgetattr");
1845 memcpy (&temp, &orig, sizeof temp);
1846 temp.c_lflag &= ~ECHO;
1848 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1854 len = getline (&ret, &n, infp);
1861 /* Remove the terminating \n if there is one. */
1862 if (len > 0 && ret[len-1] == '\n')
1866 /* Restore echo, close file descriptor. */
1869 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1873 fclose (infp); /* outfp == infp, so this is closed also */