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, "echo"))
1065 r = do_echo (cmd, argc, argv);
1066 else if (STRCASEEQ (cmd, "edit") ||
1067 STRCASEEQ (cmd, "vi") ||
1068 STRCASEEQ (cmd, "emacs"))
1069 r = do_edit (cmd, argc, argv);
1070 else if (STRCASEEQ (cmd, "lcd"))
1071 r = do_lcd (cmd, argc, argv);
1072 else if (STRCASEEQ (cmd, "glob"))
1073 r = do_glob (cmd, argc, argv);
1074 else if (STRCASEEQ (cmd, "man") ||
1075 STRCASEEQ (cmd, "manual"))
1076 r = do_man (cmd, argc, argv);
1077 else if (STRCASEEQ (cmd, "more") ||
1078 STRCASEEQ (cmd, "less"))
1079 r = do_more (cmd, argc, argv);
1080 else if (STRCASEEQ (cmd, "reopen"))
1081 r = do_reopen (cmd, argc, argv);
1082 else if (STRCASEEQ (cmd, "sparse"))
1083 r = do_sparse (cmd, argc, argv);
1084 else if (STRCASEEQ (cmd, "supported"))
1085 r = do_supported (cmd, argc, argv);
1086 else if (STRCASEEQ (cmd, "time"))
1087 r = do_time (cmd, argc, argv);
1089 r = run_action (cmd, argc, argv);
1091 /* Always flush stdout after every command, so that messages, results
1092 * etc appear immediately.
1094 if (fflush (stdout) == EOF) {
1095 perror ("failed to flush standard output");
1101 if (dup2 (stdout_saved_fd, 1) < 0) {
1102 perror ("failed to dup2 standard output");
1105 close (stdout_saved_fd);
1106 if (waitpid (pid, NULL, 0) < 0) {
1107 perror ("waiting for command to complete");
1116 list_builtin_commands (void)
1118 /* help, man and quit should appear at the top */
1119 printf ("%-20s %s\n",
1120 "help", _("display a list of commands or help on a command"));
1121 printf ("%-20s %s\n",
1122 "man", _("read the manual"));
1123 printf ("%-20s %s\n",
1124 "quit", _("quit guestfish"));
1126 printf ("%-20s %s\n",
1127 "alloc", _("allocate an image"));
1128 printf ("%-20s %s\n",
1129 "echo", _("display a line of text"));
1130 printf ("%-20s %s\n",
1131 "edit", _("edit a file in the image"));
1132 printf ("%-20s %s\n",
1133 "lcd", _("local change directory"));
1134 printf ("%-20s %s\n",
1135 "glob", _("expand wildcards in command"));
1136 printf ("%-20s %s\n",
1137 "more", _("view a file in the pager"));
1138 printf ("%-20s %s\n",
1139 "reopen", _("close and reopen libguestfs handle"));
1140 printf ("%-20s %s\n",
1141 "sparse", _("allocate a sparse image file"));
1142 printf ("%-20s %s\n",
1143 "supported", _("list supported groups of commands"));
1144 printf ("%-20s %s\n",
1145 "time", _("measure time taken to run command"));
1147 /* actions are printed after this (see list_commands) */
1151 display_builtin_command (const char *cmd)
1153 /* help for actions is auto-generated, see display_command */
1155 if (STRCASEEQ (cmd, "alloc") ||
1156 STRCASEEQ (cmd, "allocate")) {
1157 printf (_("alloc - allocate an image\n"
1158 " alloc <filename> <size>\n"
1160 " This creates an empty (zeroed) file of the given size,\n"
1161 " and then adds so it can be further examined.\n"
1163 " For more advanced image creation, see qemu-img utility.\n"
1165 " Size can be specified using standard suffixes, eg. '1M'.\n"
1169 else if (STRCASEEQ (cmd, "echo")) {
1170 printf (_("echo - display a line of text\n"
1171 " echo [<params> ...]\n"
1173 " This echos the parameters to the terminal.\n"));
1176 else if (STRCASEEQ (cmd, "edit") ||
1177 STRCASEEQ (cmd, "vi") ||
1178 STRCASEEQ (cmd, "emacs")) {
1179 printf (_("edit - edit a file in the image\n"
1180 " edit <filename>\n"
1182 " This is used to edit a file.\n"
1184 " It is the equivalent of (and is implemented by)\n"
1185 " running \"cat\", editing locally, and then \"write\".\n"
1187 " Normally it uses $EDITOR, but if you use the aliases\n"
1188 " \"vi\" or \"emacs\" you will get those editors.\n"
1190 " NOTE: This will not work reliably for large files\n"
1191 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1194 else if (STRCASEEQ (cmd, "lcd")) {
1195 printf (_("lcd - local change directory\n"
1196 " lcd <directory>\n"
1198 " Change guestfish's current directory. This command is\n"
1199 " useful if you want to download files to a particular\n"
1203 else if (STRCASEEQ (cmd, "glob")) {
1204 printf (_("glob - expand wildcards in command\n"
1205 " glob <command> [<args> ...]\n"
1207 " Glob runs <command> with wildcards expanded in any\n"
1208 " command args. Note that the command is run repeatedly\n"
1209 " once for each expanded argument.\n"));
1212 else if (STRCASEEQ (cmd, "man") ||
1213 STRCASEEQ (cmd, "manual")) {
1214 printf (_("man - read the manual\n"
1217 " Opens the manual page for guestfish.\n"));
1220 else if (STRCASEEQ (cmd, "help")) {
1221 printf (_("help - display a list of commands or help on a command\n"
1226 else if (STRCASEEQ (cmd, "more") ||
1227 STRCASEEQ (cmd, "less")) {
1228 printf (_("more - view a file in the pager\n"
1229 " more <filename>\n"
1231 " This is used to view a file in the pager.\n"
1233 " It is the equivalent of (and is implemented by)\n"
1234 " running \"cat\" and using the pager.\n"
1236 " Normally it uses $PAGER, but if you use the alias\n"
1237 " \"less\" then it always uses \"less\".\n"
1239 " NOTE: This will not work reliably for large files\n"
1240 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1243 else if (STRCASEEQ (cmd, "quit") ||
1244 STRCASEEQ (cmd, "exit") ||
1245 STRCASEEQ (cmd, "q")) {
1246 printf (_("quit - quit guestfish\n"
1250 else if (STRCASEEQ (cmd, "reopen")) {
1251 printf (_("reopen - close and reopen the libguestfs handle\n"
1254 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1255 "this normally, because the handle is closed properly when guestfish\n"
1256 "exits. However this is occasionally useful for testing.\n"));
1259 else if (STRCASEEQ (cmd, "sparse")) {
1260 printf (_("sparse - allocate a sparse image file\n"
1261 " sparse <filename> <size>\n"
1263 " This creates an empty sparse file of the given size,\n"
1264 " and then adds so it can be further examined.\n"
1266 " In all respects it works the same as the 'alloc'\n"
1267 " command, except that the image file is allocated\n"
1268 " sparsely, which means that disk blocks are not assigned\n"
1269 " to the file until they are needed. Sparse disk files\n"
1270 " only use space when written to, but they are slower\n"
1271 " and there is a danger you could run out of real disk\n"
1272 " space during a write operation.\n"
1274 " For more advanced image creation, see qemu-img utility.\n"
1276 " Size can be specified using standard suffixes, eg. '1M'.\n"
1280 else if (STRCASEEQ (cmd, "supported")) {
1281 printf (_("supported - list supported groups of commands\n"
1284 " This command returns a list of the optional groups\n"
1285 " known to the daemon, and indicates which ones are\n"
1286 " supported by this build of the libguestfs appliance.\n"
1288 " See also guestfs(3) section AVAILABILITY.\n"
1292 else if (STRCASEEQ (cmd, "time")) {
1293 printf (_("time - measure time taken to run command\n"
1294 " time <command> [<args> ...]\n"
1296 " This runs <command> as usual, and prints the elapsed\n"
1297 " time afterwards.\n"));
1301 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1307 /* This is printed when the user types in an unknown command for the
1308 * first command issued. A common case is the user doing:
1309 * guestfish disk.img
1310 * expecting guestfish to open 'disk.img' (in fact, this tried to
1311 * run a command 'disk.img').
1314 extended_help_message (void)
1317 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1318 "For a list of commands: guestfish -h\n"
1319 "For complete documentation: man guestfish\n"));
1323 free_strings (char **argv)
1327 for (argc = 0; argv[argc] != NULL; ++argc)
1333 count_strings (char *const *argv)
1337 for (c = 0; argv[c]; ++c)
1343 print_strings (char *const *argv)
1347 for (argc = 0; argv[argc] != NULL; ++argc)
1348 printf ("%s\n", argv[argc]);
1352 print_table (char *const *argv)
1356 for (i = 0; argv[i] != NULL; i += 2)
1357 printf ("%s: %s\n", argv[i], argv[i+1]);
1361 is_true (const char *str)
1364 STRCASENEQ (str, "0") &&
1365 STRCASENEQ (str, "f") &&
1366 STRCASENEQ (str, "false") &&
1367 STRCASENEQ (str, "n") &&
1368 STRCASENEQ (str, "no");
1371 /* Free strings from a non-NULL terminated char** */
1373 free_n_strings (char **str, size_t len)
1377 for (i = 0; i < len; i++) {
1384 parse_string_list (const char *str)
1387 size_t argv_len = 0;
1389 /* Current position pointer */
1390 const char *p = str;
1392 /* Token might be simple:
1395 * 'This is a single token'
1396 * or contain embedded single-quoted sections:
1397 * This' is a sing'l'e to'ken
1399 * The latter may seem over-complicated, but it's what a normal shell does.
1400 * Not doing it risks surprising somebody.
1402 * This outer loop is over complete tokens.
1408 /* Skip leading whitespace */
1409 p += strspn (p, " \t");
1413 /* This loop is over token 'fragments'. A token can be in multiple bits if
1414 * it contains single quotes. We also treat both sides of an escaped quote
1415 * as separate fragments because we can't just copy it: we have to remove
1418 while (*p && (!c_isblank (*p) || in_quote)) {
1419 const char *end = p;
1421 /* Check if the fragment starts with a quote */
1423 /* Toggle in_quote */
1424 in_quote = !in_quote;
1426 /* Skip the quote */
1430 /* If we're in a quote, look for an end quote */
1432 end += strcspn (end, "'");
1435 /* Otherwise, look for whitespace or a quote */
1437 end += strcspn (end, " \t'");
1440 /* Grow the token to accommodate the fragment */
1441 size_t tok_end = tok_len;
1443 char *tok_new = realloc (tok, tok_len + 1);
1444 if (NULL == tok_new) {
1446 free_n_strings (argv, argv_len);
1448 exit (EXIT_FAILURE);
1452 /* Check if we stopped on an escaped quote */
1453 if ('\'' == *end && end != p && *(end-1) == '\\') {
1454 /* Add everything before \' to the token */
1455 memcpy (&tok[tok_end], p, end - p - 1);
1458 tok[tok_len-1] = '\'';
1460 /* Already processed the quote */
1465 /* Add the whole fragment */
1466 memcpy (&tok[tok_end], p, end - p);
1472 /* We've reached the end of a token. We shouldn't still be in quotes. */
1474 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1476 free_n_strings (argv, argv_len);
1481 /* Add this token if there is one. There might not be if there was
1482 * whitespace at the end of the input string */
1484 /* Add the NULL terminator */
1485 tok[tok_len] = '\0';
1487 /* Add the argument to the argument list */
1489 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1490 if (NULL == argv_new) {
1492 free_n_strings (argv, argv_len-1);
1494 exit (EXIT_FAILURE);
1498 argv[argv_len-1] = tok;
1502 /* NULL terminate the argument list */
1504 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1505 if (NULL == argv_new) {
1507 free_n_strings (argv, argv_len-1);
1508 exit (EXIT_FAILURE);
1512 argv[argv_len-1] = NULL;
1517 #ifdef HAVE_LIBREADLINE
1518 static char histfile[1024];
1519 static int nr_history_lines = 0;
1523 initialize_readline (void)
1525 #ifdef HAVE_LIBREADLINE
1528 home = getenv ("HOME");
1530 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1532 (void) read_history (histfile);
1535 rl_readline_name = "guestfish";
1536 rl_attempted_completion_function = do_completion;
1538 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1539 * call the readline(), which happens later. Therefore, these
1540 * provide default values which can be overridden by the user if
1543 (void) rl_variable_bind ("completion-ignore-case", "on");
1548 cleanup_readline (void)
1550 #ifdef HAVE_LIBREADLINE
1553 if (histfile[0] != '\0') {
1554 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1561 #ifdef HAVE_APPEND_HISTORY
1562 (void) append_history (nr_history_lines, histfile);
1564 (void) write_history (histfile);
1570 #ifdef HAVE_LIBREADLINE
1572 add_history_line (const char *line)
1580 xwrite (int fd, const void *v_buf, size_t len)
1583 const char *buf = v_buf;
1586 r = write (fd, buf, len);
1598 /* Resolve the special "win:..." form for Windows-specific paths.
1599 * This always returns a newly allocated string which is freed by the
1600 * caller function in "cmds.c".
1603 resolve_win_path (const char *path)
1608 if (STRCASENEQLEN (path, "win:", 4)) {
1609 ret = strdup (path);
1617 /* Drop drive letter, if it's "C:". */
1618 if (STRCASEEQLEN (path, "c:", 2))
1628 ret = strdup (path);
1634 /* Blindly convert any backslashes into forward slashes. Is this good? */
1635 for (i = 0; i < strlen (ret); ++i)
1639 char *t = guestfs_case_sensitive_path (g, ret);
1646 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1647 * The caller (cmds.c) will call free_file_in after the command has
1648 * run which should clean up resources.
1650 static char *file_in_heredoc (const char *endmarker);
1651 static char *file_in_tmpfile = NULL;
1654 file_in (const char *arg)
1658 if (STREQ (arg, "-")) {
1659 ret = strdup ("/dev/stdin");
1665 else if (STRPREFIX (arg, "-<<")) {
1666 const char *endmarker = &arg[3];
1667 if (*endmarker == '\0') {
1668 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1672 ret = file_in_heredoc (endmarker);
1688 file_in_heredoc (const char *endmarker)
1690 static const char template[] = "/tmp/heredocXXXXXX";
1691 file_in_tmpfile = strdup (template);
1692 if (file_in_tmpfile == NULL) {
1697 int fd = mkstemp (file_in_tmpfile);
1703 size_t markerlen = strlen (endmarker);
1705 char buffer[BUFSIZ];
1706 int write_error = 0;
1707 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1708 /* Look for "END"<EOF> or "END\n" in input. */
1709 size_t blen = strlen (buffer);
1710 if (STREQLEN (buffer, endmarker, markerlen) &&
1711 (blen == markerlen ||
1712 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1715 if (xwrite (fd, buffer, blen) == -1) {
1716 if (!write_error) perror ("write");
1718 /* continue reading up to the end marker */
1722 /* Reached EOF of stdin without finding the end marker, which
1723 * is likely to be an error.
1725 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1726 program_name, endmarker);
1735 if (close (fd) == -1) {
1740 return file_in_tmpfile;
1743 unlink (file_in_tmpfile);
1746 free (file_in_tmpfile);
1747 file_in_tmpfile = NULL;
1752 free_file_in (char *s)
1754 if (file_in_tmpfile) {
1755 if (unlink (file_in_tmpfile) == -1)
1756 perror (file_in_tmpfile);
1757 file_in_tmpfile = NULL;
1760 /* Free the device or file name which was strdup'd in file_in().
1761 * Note it's not immediately clear, but for -<< heredocs,
1762 * s == file_in_tmpfile, so this frees up that buffer.
1767 /* Resolve the special FileOut paths ("-" or filename).
1768 * The caller (cmds.c) will call free (str) after the command has run.
1771 file_out (const char *arg)
1775 if (STREQ (arg, "-"))
1776 ret = strdup ("/dev/stdout");
1787 /* Read a passphrase ('Key') from /dev/tty with echo off.
1788 * The caller (cmds.c) will call free on the string afterwards.
1789 * Based on the code in cryptsetup file lib/utils.c.
1792 read_key (const char *param)
1795 struct termios orig, temp;
1798 /* Read and write to /dev/tty if available. */
1799 if (keys_from_stdin ||
1800 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1805 /* Print the prompt and set no echo. */
1806 int tty = isatty (fileno (infp));
1809 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1811 if (tcgetattr (fileno (infp), &orig) == -1) {
1812 perror ("tcgetattr");
1815 memcpy (&temp, &orig, sizeof temp);
1816 temp.c_lflag &= ~ECHO;
1818 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1824 len = getline (&ret, &n, infp);
1831 /* Remove the terminating \n if there is one. */
1832 if (len > 0 && ret[len-1] == '\n')
1836 /* Restore echo, close file descriptor. */
1839 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1843 fclose (infp); /* outfp == infp, so this is closed also */