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 list_prepared_drives ();
325 drv = malloc (sizeof (struct drv));
331 if (asprintf (&drv->N.filename, "test%d.img",
332 next_prepared_drive++) == -1) {
336 drv->N.data = create_prepared_file (optarg, drv->N.filename);
337 drv->N.device = NULL; /* filled in by add_drives */
343 complete_dest_paths = 0;
348 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
359 r = display_command (optarg);
360 else if (argv[optind] && argv[optind][0] != '-')
361 r = display_command (argv[optind++]);
365 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
373 mp = malloc (sizeof (struct mp));
378 p = strchr (optarg, ':');
381 mp->mountpoint = p+1;
383 mp->mountpoint = bad_cast ("/");
390 guestfs_set_autosync (g, 0);
399 guestfs_set_verbose (g, verbose);
403 struct guestfs_version *v = guestfs_version (g);
404 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
405 v->major, v->minor, v->release, v->extra);
410 guestfs_set_trace (g, 1);
414 usage (EXIT_SUCCESS);
417 usage (EXIT_FAILURE);
421 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
422 * previously, if we have -i without any drives but with something
423 * on the command line, it must be old-style syntax.
425 if (inspector && drvs == NULL && optind < argc) {
426 while (optind < argc) {
427 if (strchr (argv[optind], '/') ||
428 access (argv[optind], F_OK) == 0) { /* simulate -a option */
429 drv = malloc (sizeof (struct drv));
435 drv->a.filename = argv[optind];
438 } else { /* simulate -d option */
439 drv = malloc (sizeof (struct drv));
445 drv->d.guest = argv[optind];
454 /* If we've got drives to add, add them now. */
455 add_drives (drvs, 'a');
457 /* If we've got mountpoints or prepared drives or -i option, we must
458 * launch the guest and mount them.
460 if (next_prepared_drive > 1 || mps != NULL || inspector) {
461 /* RHBZ#612178: If --listen flag is given, then we will fork into
462 * the background in rc_listen(). However you can't do this while
463 * holding a libguestfs handle open because the recovery process
464 * will think the main program has died and kill qemu. Therefore
465 * don't use the recovery process for this case. (A better
466 * solution would be to call launch () etc after the fork, but
467 * that greatly complicates the code here).
469 if (remote_control_listen)
470 guestfs_set_recovery_proc (g, 0);
472 if (launch () == -1) exit (EXIT_FAILURE);
477 prepare_drives (drvs);
481 /* Remote control? */
482 if (remote_control_listen && remote_control) {
484 _("%s: cannot use --listen and --remote options at the same time\n"),
489 if (remote_control_listen) {
492 _("%s: extra parameters on the command line with --listen flag\n"),
498 _("%s: cannot use --listen and --file options at the same time\n"),
505 /* -f (file) parameter? */
508 if (open (file, O_RDONLY) == -1) {
514 /* Decide if we display progress bars. */
516 override_progress_bars >= 0
517 ? override_progress_bars
518 : (optind >= argc && isatty (0));
521 guestfs_set_progress_callback (g, progress_callback, NULL);
523 /* Interactive, shell script, or command(s) on the command line? */
524 if (optind >= argc) {
531 cmdline (argv, optind, argc);
538 /* The <term.h> header file which defines this has "issues". */
539 extern int tgetent (char *, const char *);
542 set_up_terminal (void)
544 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
545 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
547 char *term = getenv ("TERM");
549 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
553 int r = tgetent (NULL, term);
555 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
559 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
568 pod2text (const char *name, const char *shortdesc, const char *str)
572 fp = popen ("pod2text", "w");
574 /* pod2text failed, maybe not found, so let's just print the
575 * source instead, since that's better than doing nothing.
577 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
580 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
585 /* List is built in reverse order, so mount them in reverse order. */
587 mount_mps (struct mp *mp)
592 mount_mps (mp->next);
594 /* Don't use guestfs_mount here because that will default to mount
595 * options -o sync,noatime. For more information, see guestfs(3)
596 * section "LIBGUESTFS GOTCHAS".
598 const char *options = read_only ? "ro" : "";
599 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
606 add_drives (struct drv *drv, char next_drive)
610 if (next_drive > 'z') {
612 _("guestfish: too many drives added on the command line\n"));
617 next_drive = add_drives (drv->next, next_drive);
622 r = guestfs_add_drive (g, drv->a.filename);
624 r = guestfs_add_drive_ro (g, drv->a.filename);
632 r = add_libvirt_drives (drv->d.guest);
640 /* -N option is not affected by --ro */
641 r = guestfs_add_drive (g, drv->N.filename);
645 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
653 default: /* keep GCC happy */
662 prepare_drives (struct drv *drv)
665 prepare_drives (drv->next);
666 if (drv->type == drv_N)
667 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
674 if (guestfs_is_config (g)) {
675 if (guestfs_launch (g) == -1)
693 #define FISH "><fs> "
695 static char *line_read = NULL;
700 #ifdef HAVE_LIBREADLINE
708 line_read = readline (prompt ? FISH : "");
710 if (line_read && *line_read)
711 add_history_line (line_read);
716 #endif /* HAVE_LIBREADLINE */
718 static char buf[8192];
721 if (prompt) printf (FISH);
722 line_read = fgets (buf, sizeof buf, stdin);
725 len = strlen (line_read);
726 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
740 int global_exit_on_error = !prompt;
745 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
746 "editing virtual machine filesystems.\n"
748 "Type: 'help' for a list of commands\n"
749 " 'man' to read the manual\n"
750 " 'quit' to quit the shell\n"
754 print_inspect_prompt ();
762 exit_on_error = global_exit_on_error;
764 buf = rl_gets (prompt);
770 /* Skip any initial whitespace before the command. */
772 while (*buf && c_isspace (*buf))
777 /* If the next character is '#' then this is a comment. */
778 if (*buf == '#') continue;
780 /* If the next character is '!' then pass the whole lot to system(3). */
788 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
789 WEXITSTATUS (r) != 0)
795 /* If the next character is '-' allow the command to fail without
796 * exiting on error (just for this one command though).
804 /* Get the command (cannot be quoted). */
805 len = strcspn (buf, " \t");
807 if (len == 0) continue;
811 if (buf[len] == '\0') {
818 p += strspn (p, " \t");
820 /* Get the parameters. */
821 while (*p && i < sizeof argv / sizeof argv[0]) {
824 /* Parameters which start with quotes or pipes are treated
825 * specially. Bare parameters are delimited by whitespace.
829 len = strcspn (p, "\"");
830 if (p[len] == '\0') {
831 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
832 if (exit_on_error) exit (EXIT_FAILURE);
835 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
837 _("%s: command arguments not separated by whitespace\n"),
839 if (exit_on_error) exit (EXIT_FAILURE);
843 pend = p[len+1] ? &p[len+2] : &p[len+1];
844 } else if (*p == '\'') {
846 len = strcspn (p, "'");
847 if (p[len] == '\0') {
848 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
849 if (exit_on_error) exit (EXIT_FAILURE);
852 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
854 _("%s: command arguments not separated by whitespace\n"),
856 if (exit_on_error) exit (EXIT_FAILURE);
860 pend = p[len+1] ? &p[len+2] : &p[len+1];
861 } else if (*p == '|') {
866 } else if (*p == '[') {
870 while (*pend && c != 0) {
871 if (*pend == '[') c++;
872 else if (*pend == ']') c--;
877 _("%s: unterminated \"[...]\" sequence\n"), program_name);
878 if (exit_on_error) exit (EXIT_FAILURE);
881 if (*pend && (*pend != ' ' && *pend != '\t')) {
883 _("%s: command arguments not separated by whitespace\n"),
885 if (exit_on_error) exit (EXIT_FAILURE);
890 } else if (*p != ' ' && *p != '\t') {
891 /* If the first character is a ~ then note that this parameter
892 * is a candidate for ~username expansion. NB this does not
893 * apply to quoted parameters.
895 tilde_candidate = *p == '~';
896 len = strcspn (p, " \t");
903 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
908 if (!tilde_candidate)
911 argv[i] = try_tilde_expansion (p);
916 p += strspn (p, " \t");
919 if (i == sizeof argv / sizeof argv[0]) {
920 fprintf (stderr, _("%s: too many arguments\n"), program_name);
921 if (exit_on_error) exit (EXIT_FAILURE);
928 if (issue_command (cmd, argv, pipe) == -1) {
929 if (exit_on_error) exit (EXIT_FAILURE);
934 if (prompt) printf ("\n");
938 cmdline (char *argv[], int optind, int argc)
945 if (optind >= argc) return;
947 cmd = argv[optind++];
948 if (STREQ (cmd, ":")) {
949 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
953 /* Allow -cmd on the command line to mean (temporarily) override
954 * the normal exit on error (RHBZ#578407).
961 params = &argv[optind];
963 /* Search for end of command list or ":" ... */
964 while (optind < argc && STRNEQ (argv[optind], ":"))
967 if (optind == argc) {
968 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
972 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
974 cmdline (argv, optind+1, argc);
979 issue_command (const char *cmd, char *argv[], const char *pipecmd)
982 int stdout_saved_fd = -1;
986 reset_progress_bar ();
988 /* This counts the commands issued, starting at 1. */
991 /* For | ... commands. Annoyingly we can't use popen(3) here. */
995 if (fflush (stdout) == EOF) {
996 perror ("failed to flush standard output");
1000 perror ("pipe failed");
1009 if (pid == 0) { /* Child process. */
1011 if (dup2 (fd[0], 0) < 0) {
1012 perror ("dup2 of stdin failed");
1016 r = system (pipecmd);
1021 _exit (WEXITSTATUS (r));
1024 if ((stdout_saved_fd = dup (1)) < 0) {
1025 perror ("failed to dup stdout");
1029 if (dup2 (fd[1], 1) < 0) {
1030 perror ("failed to dup stdout");
1031 close (stdout_saved_fd);
1037 for (argc = 0; argv[argc] != NULL; ++argc)
1040 /* If --remote was set, then send this command to a remote process. */
1042 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1044 /* Otherwise execute it locally. */
1045 else if (STRCASEEQ (cmd, "help")) {
1050 r = display_command (argv[0]);
1052 else if (STRCASEEQ (cmd, "quit") ||
1053 STRCASEEQ (cmd, "exit") ||
1054 STRCASEEQ (cmd, "q")) {
1058 else if (STRCASEEQ (cmd, "alloc") ||
1059 STRCASEEQ (cmd, "allocate"))
1060 r = do_alloc (cmd, argc, argv);
1061 else if (STRCASEEQ (cmd, "echo"))
1062 r = do_echo (cmd, argc, argv);
1063 else if (STRCASEEQ (cmd, "edit") ||
1064 STRCASEEQ (cmd, "vi") ||
1065 STRCASEEQ (cmd, "emacs"))
1066 r = do_edit (cmd, argc, argv);
1067 else if (STRCASEEQ (cmd, "lcd"))
1068 r = do_lcd (cmd, argc, argv);
1069 else if (STRCASEEQ (cmd, "glob"))
1070 r = do_glob (cmd, argc, argv);
1071 else if (STRCASEEQ (cmd, "man") ||
1072 STRCASEEQ (cmd, "manual"))
1073 r = do_man (cmd, argc, argv);
1074 else if (STRCASEEQ (cmd, "more") ||
1075 STRCASEEQ (cmd, "less"))
1076 r = do_more (cmd, argc, argv);
1077 else if (STRCASEEQ (cmd, "reopen"))
1078 r = do_reopen (cmd, argc, argv);
1079 else if (STRCASEEQ (cmd, "sparse"))
1080 r = do_sparse (cmd, argc, argv);
1081 else if (STRCASEEQ (cmd, "supported"))
1082 r = do_supported (cmd, argc, argv);
1083 else if (STRCASEEQ (cmd, "time"))
1084 r = do_time (cmd, argc, argv);
1086 r = run_action (cmd, argc, argv);
1088 /* Always flush stdout after every command, so that messages, results
1089 * etc appear immediately.
1091 if (fflush (stdout) == EOF) {
1092 perror ("failed to flush standard output");
1098 if (dup2 (stdout_saved_fd, 1) < 0) {
1099 perror ("failed to dup2 standard output");
1102 close (stdout_saved_fd);
1103 if (waitpid (pid, NULL, 0) < 0) {
1104 perror ("waiting for command to complete");
1113 list_builtin_commands (void)
1115 /* help, man and quit should appear at the top */
1116 printf ("%-20s %s\n",
1117 "help", _("display a list of commands or help on a command"));
1118 printf ("%-20s %s\n",
1119 "man", _("read the manual"));
1120 printf ("%-20s %s\n",
1121 "quit", _("quit guestfish"));
1123 printf ("%-20s %s\n",
1124 "alloc", _("allocate an image"));
1125 printf ("%-20s %s\n",
1126 "echo", _("display a line of text"));
1127 printf ("%-20s %s\n",
1128 "edit", _("edit a file in the image"));
1129 printf ("%-20s %s\n",
1130 "lcd", _("local change directory"));
1131 printf ("%-20s %s\n",
1132 "glob", _("expand wildcards in command"));
1133 printf ("%-20s %s\n",
1134 "more", _("view a file in the pager"));
1135 printf ("%-20s %s\n",
1136 "reopen", _("close and reopen libguestfs handle"));
1137 printf ("%-20s %s\n",
1138 "sparse", _("allocate a sparse image file"));
1139 printf ("%-20s %s\n",
1140 "supported", _("list supported groups of commands"));
1141 printf ("%-20s %s\n",
1142 "time", _("measure time taken to run command"));
1144 /* actions are printed after this (see list_commands) */
1148 display_builtin_command (const char *cmd)
1150 /* help for actions is auto-generated, see display_command */
1152 if (STRCASEEQ (cmd, "alloc") ||
1153 STRCASEEQ (cmd, "allocate")) {
1154 printf (_("alloc - allocate an image\n"
1155 " alloc <filename> <size>\n"
1157 " This creates an empty (zeroed) file of the given size,\n"
1158 " and then adds so it can be further examined.\n"
1160 " For more advanced image creation, see qemu-img utility.\n"
1162 " Size can be specified using standard suffixes, eg. '1M'.\n"
1166 else if (STRCASEEQ (cmd, "echo")) {
1167 printf (_("echo - display a line of text\n"
1168 " echo [<params> ...]\n"
1170 " This echos the parameters to the terminal.\n"));
1173 else if (STRCASEEQ (cmd, "edit") ||
1174 STRCASEEQ (cmd, "vi") ||
1175 STRCASEEQ (cmd, "emacs")) {
1176 printf (_("edit - edit a file in the image\n"
1177 " edit <filename>\n"
1179 " This is used to edit a file.\n"
1181 " It is the equivalent of (and is implemented by)\n"
1182 " running \"cat\", editing locally, and then \"write\".\n"
1184 " Normally it uses $EDITOR, but if you use the aliases\n"
1185 " \"vi\" or \"emacs\" you will get those editors.\n"
1187 " NOTE: This will not work reliably for large files\n"
1188 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1191 else if (STRCASEEQ (cmd, "lcd")) {
1192 printf (_("lcd - local change directory\n"
1193 " lcd <directory>\n"
1195 " Change guestfish's current directory. This command is\n"
1196 " useful if you want to download files to a particular\n"
1200 else if (STRCASEEQ (cmd, "glob")) {
1201 printf (_("glob - expand wildcards in command\n"
1202 " glob <command> [<args> ...]\n"
1204 " Glob runs <command> with wildcards expanded in any\n"
1205 " command args. Note that the command is run repeatedly\n"
1206 " once for each expanded argument.\n"));
1209 else if (STRCASEEQ (cmd, "man") ||
1210 STRCASEEQ (cmd, "manual")) {
1211 printf (_("man - read the manual\n"
1214 " Opens the manual page for guestfish.\n"));
1217 else if (STRCASEEQ (cmd, "help")) {
1218 printf (_("help - display a list of commands or help on a command\n"
1223 else if (STRCASEEQ (cmd, "more") ||
1224 STRCASEEQ (cmd, "less")) {
1225 printf (_("more - view a file in the pager\n"
1226 " more <filename>\n"
1228 " This is used to view a file in the pager.\n"
1230 " It is the equivalent of (and is implemented by)\n"
1231 " running \"cat\" and using the pager.\n"
1233 " Normally it uses $PAGER, but if you use the alias\n"
1234 " \"less\" then it always uses \"less\".\n"
1236 " NOTE: This will not work reliably for large files\n"
1237 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1240 else if (STRCASEEQ (cmd, "quit") ||
1241 STRCASEEQ (cmd, "exit") ||
1242 STRCASEEQ (cmd, "q")) {
1243 printf (_("quit - quit guestfish\n"
1247 else if (STRCASEEQ (cmd, "reopen")) {
1248 printf (_("reopen - close and reopen the libguestfs handle\n"
1251 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1252 "this normally, because the handle is closed properly when guestfish\n"
1253 "exits. However this is occasionally useful for testing.\n"));
1256 else if (STRCASEEQ (cmd, "sparse")) {
1257 printf (_("sparse - allocate a sparse image file\n"
1258 " sparse <filename> <size>\n"
1260 " This creates an empty sparse file of the given size,\n"
1261 " and then adds so it can be further examined.\n"
1263 " In all respects it works the same as the 'alloc'\n"
1264 " command, except that the image file is allocated\n"
1265 " sparsely, which means that disk blocks are not assigned\n"
1266 " to the file until they are needed. Sparse disk files\n"
1267 " only use space when written to, but they are slower\n"
1268 " and there is a danger you could run out of real disk\n"
1269 " space during a write operation.\n"
1271 " For more advanced image creation, see qemu-img utility.\n"
1273 " Size can be specified using standard suffixes, eg. '1M'.\n"
1277 else if (STRCASEEQ (cmd, "supported")) {
1278 printf (_("supported - list supported groups of commands\n"
1281 " This command returns a list of the optional groups\n"
1282 " known to the daemon, and indicates which ones are\n"
1283 " supported by this build of the libguestfs appliance.\n"
1285 " See also guestfs(3) section AVAILABILITY.\n"
1289 else if (STRCASEEQ (cmd, "time")) {
1290 printf (_("time - measure time taken to run command\n"
1291 " time <command> [<args> ...]\n"
1293 " This runs <command> as usual, and prints the elapsed\n"
1294 " time afterwards.\n"));
1298 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1304 /* This is printed when the user types in an unknown command for the
1305 * first command issued. A common case is the user doing:
1306 * guestfish disk.img
1307 * expecting guestfish to open 'disk.img' (in fact, this tried to
1308 * run a command 'disk.img').
1311 extended_help_message (void)
1314 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1315 "For a list of commands: guestfish -h\n"
1316 "For complete documentation: man guestfish\n"));
1320 free_strings (char **argv)
1324 for (argc = 0; argv[argc] != NULL; ++argc)
1330 count_strings (char *const *argv)
1334 for (c = 0; argv[c]; ++c)
1340 print_strings (char *const *argv)
1344 for (argc = 0; argv[argc] != NULL; ++argc)
1345 printf ("%s\n", argv[argc]);
1349 print_table (char *const *argv)
1353 for (i = 0; argv[i] != NULL; i += 2)
1354 printf ("%s: %s\n", argv[i], argv[i+1]);
1358 is_true (const char *str)
1361 STRCASENEQ (str, "0") &&
1362 STRCASENEQ (str, "f") &&
1363 STRCASENEQ (str, "false") &&
1364 STRCASENEQ (str, "n") &&
1365 STRCASENEQ (str, "no");
1368 /* Free strings from a non-NULL terminated char** */
1370 free_n_strings (char **str, size_t len)
1374 for (i = 0; i < len; i++) {
1381 parse_string_list (const char *str)
1384 size_t argv_len = 0;
1386 /* Current position pointer */
1387 const char *p = str;
1389 /* Token might be simple:
1392 * 'This is a single token'
1393 * or contain embedded single-quoted sections:
1394 * This' is a sing'l'e to'ken
1396 * The latter may seem over-complicated, but it's what a normal shell does.
1397 * Not doing it risks surprising somebody.
1399 * This outer loop is over complete tokens.
1405 /* Skip leading whitespace */
1406 p += strspn (p, " \t");
1410 /* This loop is over token 'fragments'. A token can be in multiple bits if
1411 * it contains single quotes. We also treat both sides of an escaped quote
1412 * as separate fragments because we can't just copy it: we have to remove
1415 while (*p && (!c_isblank (*p) || in_quote)) {
1416 const char *end = p;
1418 /* Check if the fragment starts with a quote */
1420 /* Toggle in_quote */
1421 in_quote = !in_quote;
1423 /* Skip the quote */
1427 /* If we're in a quote, look for an end quote */
1429 end += strcspn (end, "'");
1432 /* Otherwise, look for whitespace or a quote */
1434 end += strcspn (end, " \t'");
1437 /* Grow the token to accommodate the fragment */
1438 size_t tok_end = tok_len;
1440 char *tok_new = realloc (tok, tok_len + 1);
1441 if (NULL == tok_new) {
1443 free_n_strings (argv, argv_len);
1445 exit (EXIT_FAILURE);
1449 /* Check if we stopped on an escaped quote */
1450 if ('\'' == *end && end != p && *(end-1) == '\\') {
1451 /* Add everything before \' to the token */
1452 memcpy (&tok[tok_end], p, end - p - 1);
1455 tok[tok_len-1] = '\'';
1457 /* Already processed the quote */
1462 /* Add the whole fragment */
1463 memcpy (&tok[tok_end], p, end - p);
1469 /* We've reached the end of a token. We shouldn't still be in quotes. */
1471 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1473 free_n_strings (argv, argv_len);
1478 /* Add this token if there is one. There might not be if there was
1479 * whitespace at the end of the input string */
1481 /* Add the NULL terminator */
1482 tok[tok_len] = '\0';
1484 /* Add the argument to the argument list */
1486 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1487 if (NULL == argv_new) {
1489 free_n_strings (argv, argv_len-1);
1491 exit (EXIT_FAILURE);
1495 argv[argv_len-1] = tok;
1499 /* NULL terminate the argument list */
1501 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1502 if (NULL == argv_new) {
1504 free_n_strings (argv, argv_len-1);
1505 exit (EXIT_FAILURE);
1509 argv[argv_len-1] = NULL;
1514 #ifdef HAVE_LIBREADLINE
1515 static char histfile[1024];
1516 static int nr_history_lines = 0;
1520 initialize_readline (void)
1522 #ifdef HAVE_LIBREADLINE
1525 home = getenv ("HOME");
1527 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1529 (void) read_history (histfile);
1532 rl_readline_name = "guestfish";
1533 rl_attempted_completion_function = do_completion;
1535 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1536 * call the readline(), which happens later. Therefore, these
1537 * provide default values which can be overridden by the user if
1540 (void) rl_variable_bind ("completion-ignore-case", "on");
1545 cleanup_readline (void)
1547 #ifdef HAVE_LIBREADLINE
1550 if (histfile[0] != '\0') {
1551 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1558 #ifdef HAVE_APPEND_HISTORY
1559 (void) append_history (nr_history_lines, histfile);
1561 (void) write_history (histfile);
1567 #ifdef HAVE_LIBREADLINE
1569 add_history_line (const char *line)
1577 xwrite (int fd, const void *v_buf, size_t len)
1580 const char *buf = v_buf;
1583 r = write (fd, buf, len);
1595 /* Resolve the special "win:..." form for Windows-specific paths.
1596 * This always returns a newly allocated string which is freed by the
1597 * caller function in "cmds.c".
1600 resolve_win_path (const char *path)
1605 if (STRCASENEQLEN (path, "win:", 4)) {
1606 ret = strdup (path);
1614 /* Drop drive letter, if it's "C:". */
1615 if (STRCASEEQLEN (path, "c:", 2))
1625 ret = strdup (path);
1631 /* Blindly convert any backslashes into forward slashes. Is this good? */
1632 for (i = 0; i < strlen (ret); ++i)
1636 char *t = guestfs_case_sensitive_path (g, ret);
1643 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1644 * The caller (cmds.c) will call free_file_in after the command has
1645 * run which should clean up resources.
1647 static char *file_in_heredoc (const char *endmarker);
1648 static char *file_in_tmpfile = NULL;
1651 file_in (const char *arg)
1655 if (STREQ (arg, "-")) {
1656 ret = strdup ("/dev/stdin");
1662 else if (STRPREFIX (arg, "-<<")) {
1663 const char *endmarker = &arg[3];
1664 if (*endmarker == '\0') {
1665 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1669 ret = file_in_heredoc (endmarker);
1685 file_in_heredoc (const char *endmarker)
1687 static const char template[] = "/tmp/heredocXXXXXX";
1688 file_in_tmpfile = strdup (template);
1689 if (file_in_tmpfile == NULL) {
1694 int fd = mkstemp (file_in_tmpfile);
1700 size_t markerlen = strlen (endmarker);
1702 char buffer[BUFSIZ];
1703 int write_error = 0;
1704 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1705 /* Look for "END"<EOF> or "END\n" in input. */
1706 size_t blen = strlen (buffer);
1707 if (STREQLEN (buffer, endmarker, markerlen) &&
1708 (blen == markerlen ||
1709 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1712 if (xwrite (fd, buffer, blen) == -1) {
1713 if (!write_error) perror ("write");
1715 /* continue reading up to the end marker */
1719 /* Reached EOF of stdin without finding the end marker, which
1720 * is likely to be an error.
1722 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1723 program_name, endmarker);
1732 if (close (fd) == -1) {
1737 return file_in_tmpfile;
1740 unlink (file_in_tmpfile);
1743 free (file_in_tmpfile);
1744 file_in_tmpfile = NULL;
1749 free_file_in (char *s)
1751 if (file_in_tmpfile) {
1752 if (unlink (file_in_tmpfile) == -1)
1753 perror (file_in_tmpfile);
1754 file_in_tmpfile = NULL;
1757 /* Free the device or file name which was strdup'd in file_in().
1758 * Note it's not immediately clear, but for -<< heredocs,
1759 * s == file_in_tmpfile, so this frees up that buffer.
1764 /* Resolve the special FileOut paths ("-" or filename).
1765 * The caller (cmds.c) will call free (str) after the command has run.
1768 file_out (const char *arg)
1772 if (STREQ (arg, "-"))
1773 ret = strdup ("/dev/stdout");
1784 /* Read a passphrase ('Key') from /dev/tty with echo off.
1785 * The caller (cmds.c) will call free on the string afterwards.
1786 * Based on the code in cryptsetup file lib/utils.c.
1789 read_key (const char *param)
1792 struct termios orig, temp;
1795 /* Read and write to /dev/tty if available. */
1796 if (keys_from_stdin ||
1797 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1802 /* Print the prompt and set no echo. */
1803 int tty = isatty (fileno (infp));
1806 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1808 if (tcgetattr (fileno (infp), &orig) == -1) {
1809 perror ("tcgetattr");
1812 memcpy (&temp, &orig, sizeof temp);
1813 temp.c_lflag &= ~ECHO;
1815 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1821 len = getline (&ret, &n, infp);
1828 /* Remove the terminating \n if there is one. */
1829 if (len > 0 && ret[len-1] == '\n')
1833 /* Restore echo, close file descriptor. */
1836 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1840 fclose (infp); /* outfp == infp, so this is closed also */