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 /* Currently open libguestfs handle. */
94 int remote_control_listen = 0;
95 int remote_control = 0;
96 int exit_on_error = 1;
98 int keys_from_stdin = 0;
99 const char *libvirt_uri = NULL;
102 int have_terminfo = 0;
104 static void __attribute__((noreturn))
107 if (status != EXIT_SUCCESS)
108 fprintf (stderr, _("Try `%s --help' for more information.\n"),
112 _("%s: guest filesystem shell\n"
113 "%s lets you edit virtual machine filesystems\n"
114 "Copyright (C) 2009 Red Hat Inc.\n"
116 " %s [--options] cmd [: cmd : cmd ...]\n"
117 " %s -i libvirt-domain\n"
118 " %s -i disk-image(s)\n"
119 "or for interactive use:\n"
121 "or from a shell script:\n"
127 " -h|--cmd-help List available commands\n"
128 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
129 " -a|--add image Add image\n"
130 " -c|--connect uri Specify libvirt URI for -d option\n"
131 " -d|--domain guest Add disks from libvirt guest\n"
132 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
133 " -f|--file file Read commands from file\n"
134 " -i|--inspector Automatically mount filesystems\n"
135 " --keys-from-stdin Read passphrases from stdin\n"
136 " --listen Listen for remote commands\n"
137 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
138 " -n|--no-sync Don't autosync\n"
139 " -N|--new type Create prepared disk (test1.img, ...)\n"
140 " --remote[=pid] Send commands to remote %s\n"
141 " -r|--ro Mount read-only\n"
142 " --selinux Enable SELinux support\n"
143 " -v|--verbose Verbose messages\n"
144 " -x Echo each command before executing it\n"
145 " -V|--version Display version and exit\n"
146 "For more information, see the manpage %s(1).\n"),
147 program_name, program_name, program_name,
148 program_name, program_name, program_name,
149 program_name, program_name, program_name);
155 main (int argc, char *argv[])
157 /* Set global program name that is not polluted with libtool artifacts. */
158 set_program_name (argv[0]);
160 atexit (close_stdout);
162 setlocale (LC_ALL, "");
163 bindtextdomain (PACKAGE, LOCALEBASEDIR);
164 textdomain (PACKAGE);
168 enum { HELP_OPTION = CHAR_MAX + 1 };
170 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
171 static const struct option long_options[] = {
172 { "add", 1, 0, 'a' },
173 { "cmd-help", 2, 0, 'h' },
174 { "connect", 1, 0, 'c' },
175 { "domain", 1, 0, 'd' },
176 { "file", 1, 0, 'f' },
177 { "help", 0, 0, HELP_OPTION },
178 { "inspector", 0, 0, 'i' },
179 { "keys-from-stdin", 0, 0, 0 },
180 { "listen", 0, 0, 0 },
181 { "mount", 1, 0, 'm' },
182 { "new", 1, 0, 'N' },
183 { "no-dest-paths", 0, 0, 'D' },
184 { "no-sync", 0, 0, 'n' },
185 { "remote", 2, 0, 0 },
187 { "selinux", 0, 0, 0 },
188 { "verbose", 0, 0, 'v' },
189 { "version", 0, 0, 'V' },
192 struct drv *drvs = NULL;
194 struct mp *mps = NULL;
196 char *p, *file = NULL;
200 int next_prepared_drive = 1;
202 initialize_readline ();
204 memset (&sa, 0, sizeof sa);
205 sa.sa_handler = SIG_IGN;
206 sa.sa_flags = SA_RESTART;
207 sigaction (SIGPIPE, &sa, NULL);
209 /* guestfs_create is meant to be a lightweight operation, so
210 * it's OK to do it early here.
212 g = guestfs_create ();
214 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
218 guestfs_set_autosync (g, 1);
220 /* If developing, add ./appliance to the path. Note that libtools
221 * interferes with this because uninstalled guestfish is a shell
222 * script that runs the real program with an absolute path. Detect
225 * BUT if LIBGUESTFS_PATH environment variable is already set by
226 * the user, then don't override it.
228 if (getenv ("LIBGUESTFS_PATH") == NULL &&
230 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
231 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
233 /* CAUTION: we are careful to modify argv[0] here, only after
234 * using it just above.
236 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
237 * of the original, in case it's needed below.
239 char *real_argv0 = argv[0];
240 argv[0] = bad_cast (program_name);
243 c = getopt_long (argc, argv, options, long_options, &option_index);
247 case 0: /* options which are long only */
248 if (STREQ (long_options[option_index].name, "listen"))
249 remote_control_listen = 1;
250 else if (STREQ (long_options[option_index].name, "remote")) {
252 if (sscanf (optarg, "%d", &remote_control) != 1) {
253 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
254 program_name, optarg);
258 p = getenv ("GUESTFISH_PID");
259 if (!p || sscanf (p, "%d", &remote_control) != 1) {
260 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
261 " to the PID of the remote process\n"),
266 } else if (STREQ (long_options[option_index].name, "selinux")) {
267 guestfs_set_selinux (g, 1);
268 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
271 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
272 program_name, long_options[option_index].name, option_index);
278 if (access (optarg, R_OK) != 0) {
282 drv = malloc (sizeof (struct drv));
288 drv->a.filename = optarg;
294 libvirt_uri = optarg;
298 drv = malloc (sizeof (struct drv));
304 drv->d.guest = optarg;
310 if (STRCASEEQ (optarg, "list")) {
311 list_prepared_drives ();
314 drv = malloc (sizeof (struct drv));
320 if (asprintf (&drv->N.filename, "test%d.img",
321 next_prepared_drive++) == -1) {
325 drv->N.data = create_prepared_file (optarg, drv->N.filename);
326 drv->N.device = NULL; /* filled in by add_drives */
332 complete_dest_paths = 0;
337 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
348 r = display_command (optarg);
349 else if (argv[optind] && argv[optind][0] != '-')
350 r = display_command (argv[optind++]);
354 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
362 mp = malloc (sizeof (struct mp));
367 p = strchr (optarg, ':');
370 mp->mountpoint = p+1;
372 mp->mountpoint = bad_cast ("/");
379 guestfs_set_autosync (g, 0);
388 guestfs_set_verbose (g, verbose);
392 struct guestfs_version *v = guestfs_version (g);
393 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
394 v->major, v->minor, v->release, v->extra);
399 guestfs_set_trace (g, 1);
403 usage (EXIT_SUCCESS);
406 usage (EXIT_FAILURE);
410 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
411 * previously, if we have -i without any drives but with something
412 * on the command line, it must be old-style syntax.
414 if (inspector && drvs == NULL && optind < argc) {
415 while (optind < argc) {
416 if (strchr (argv[optind], '/') ||
417 access (argv[optind], F_OK) == 0) { /* simulate -a option */
418 drv = malloc (sizeof (struct drv));
424 drv->a.filename = argv[optind];
427 } else { /* simulate -d option */
428 drv = malloc (sizeof (struct drv));
434 drv->d.guest = argv[optind];
443 /* If we've got drives to add, add them now. */
444 add_drives (drvs, 'a');
446 /* If we've got mountpoints or prepared drives or -i option, we must
447 * launch the guest and mount them.
449 if (next_prepared_drive > 1 || mps != NULL || inspector) {
450 /* RHBZ#612178: If --listen flag is given, then we will fork into
451 * the background in rc_listen(). However you can't do this while
452 * holding a libguestfs handle open because the recovery process
453 * will think the main program has died and kill qemu. Therefore
454 * don't use the recovery process for this case. (A better
455 * solution would be to call launch () etc after the fork, but
456 * that greatly complicates the code here).
458 if (remote_control_listen)
459 guestfs_set_recovery_proc (g, 0);
461 if (launch () == -1) exit (EXIT_FAILURE);
466 prepare_drives (drvs);
470 /* Remote control? */
471 if (remote_control_listen && remote_control) {
473 _("%s: cannot use --listen and --remote options at the same time\n"),
478 if (remote_control_listen) {
481 _("%s: extra parameters on the command line with --listen flag\n"),
487 _("%s: cannot use --listen and --file options at the same time\n"),
494 /* -f (file) parameter? */
497 if (open (file, O_RDONLY) == -1) {
503 /* Interactive, shell script, or command(s) on the command line? */
504 if (optind >= argc) {
511 cmdline (argv, optind, argc);
518 /* The <term.h> header file which defines this has "issues". */
519 extern int tgetent (char *, const char *);
522 set_up_terminal (void)
524 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
525 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
527 char *term = getenv ("TERM");
529 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
533 int r = tgetent (NULL, term);
535 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
539 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
548 pod2text (const char *name, const char *shortdesc, const char *str)
552 fp = popen ("pod2text", "w");
554 /* pod2text failed, maybe not found, so let's just print the
555 * source instead, since that's better than doing nothing.
557 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
560 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
565 /* List is built in reverse order, so mount them in reverse order. */
567 mount_mps (struct mp *mp)
572 mount_mps (mp->next);
574 /* Don't use guestfs_mount here because that will default to mount
575 * options -o sync,noatime. For more information, see guestfs(3)
576 * section "LIBGUESTFS GOTCHAS".
578 const char *options = read_only ? "ro" : "";
579 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
586 add_drives (struct drv *drv, char next_drive)
590 if (next_drive > 'z') {
592 _("guestfish: too many drives added on the command line\n"));
597 next_drive = add_drives (drv->next, next_drive);
602 r = guestfs_add_drive (g, drv->a.filename);
604 r = guestfs_add_drive_ro (g, drv->a.filename);
612 r = add_libvirt_drives (drv->d.guest);
620 /* -N option is not affected by --ro */
621 r = guestfs_add_drive (g, drv->N.filename);
625 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
633 default: /* keep GCC happy */
642 prepare_drives (struct drv *drv)
645 prepare_drives (drv->next);
646 if (drv->type == drv_N)
647 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
654 if (guestfs_is_config (g)) {
655 if (guestfs_launch (g) == -1)
673 #define FISH "><fs> "
675 static char *line_read = NULL;
680 #ifdef HAVE_LIBREADLINE
688 line_read = readline (prompt ? FISH : "");
690 if (line_read && *line_read)
691 add_history_line (line_read);
696 #endif /* HAVE_LIBREADLINE */
698 static char buf[8192];
701 if (prompt) printf (FISH);
702 line_read = fgets (buf, sizeof buf, stdin);
705 len = strlen (line_read);
706 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
720 int global_exit_on_error = !prompt;
725 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
726 "editing virtual machine filesystems.\n"
728 "Type: 'help' for a list of commands\n"
729 " 'man' to read the manual\n"
730 " 'quit' to quit the shell\n"
734 print_inspect_prompt ();
742 exit_on_error = global_exit_on_error;
744 buf = rl_gets (prompt);
750 /* Skip any initial whitespace before the command. */
752 while (*buf && c_isspace (*buf))
757 /* If the next character is '#' then this is a comment. */
758 if (*buf == '#') continue;
760 /* If the next character is '!' then pass the whole lot to system(3). */
768 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
769 WEXITSTATUS (r) != 0)
775 /* If the next character is '-' allow the command to fail without
776 * exiting on error (just for this one command though).
784 /* Get the command (cannot be quoted). */
785 len = strcspn (buf, " \t");
787 if (len == 0) continue;
791 if (buf[len] == '\0') {
798 p += strspn (p, " \t");
800 /* Get the parameters. */
801 while (*p && i < sizeof argv / sizeof argv[0]) {
804 /* Parameters which start with quotes or pipes are treated
805 * specially. Bare parameters are delimited by whitespace.
809 len = strcspn (p, "\"");
810 if (p[len] == '\0') {
811 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
812 if (exit_on_error) exit (EXIT_FAILURE);
815 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
817 _("%s: command arguments not separated by whitespace\n"),
819 if (exit_on_error) exit (EXIT_FAILURE);
823 pend = p[len+1] ? &p[len+2] : &p[len+1];
824 } else if (*p == '\'') {
826 len = strcspn (p, "'");
827 if (p[len] == '\0') {
828 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
829 if (exit_on_error) exit (EXIT_FAILURE);
832 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
834 _("%s: command arguments not separated by whitespace\n"),
836 if (exit_on_error) exit (EXIT_FAILURE);
840 pend = p[len+1] ? &p[len+2] : &p[len+1];
841 } else if (*p == '|') {
846 } else if (*p == '[') {
850 while (*pend && c != 0) {
851 if (*pend == '[') c++;
852 else if (*pend == ']') c--;
857 _("%s: unterminated \"[...]\" sequence\n"), program_name);
858 if (exit_on_error) exit (EXIT_FAILURE);
861 if (*pend && (*pend != ' ' && *pend != '\t')) {
863 _("%s: command arguments not separated by whitespace\n"),
865 if (exit_on_error) exit (EXIT_FAILURE);
870 } else if (*p != ' ' && *p != '\t') {
871 /* If the first character is a ~ then note that this parameter
872 * is a candidate for ~username expansion. NB this does not
873 * apply to quoted parameters.
875 tilde_candidate = *p == '~';
876 len = strcspn (p, " \t");
883 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
888 if (!tilde_candidate)
891 argv[i] = try_tilde_expansion (p);
896 p += strspn (p, " \t");
899 if (i == sizeof argv / sizeof argv[0]) {
900 fprintf (stderr, _("%s: too many arguments\n"), program_name);
901 if (exit_on_error) exit (EXIT_FAILURE);
908 if (issue_command (cmd, argv, pipe) == -1) {
909 if (exit_on_error) exit (EXIT_FAILURE);
914 if (prompt) printf ("\n");
918 cmdline (char *argv[], int optind, int argc)
925 if (optind >= argc) return;
927 cmd = argv[optind++];
928 if (STREQ (cmd, ":")) {
929 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
933 /* Allow -cmd on the command line to mean (temporarily) override
934 * the normal exit on error (RHBZ#578407).
941 params = &argv[optind];
943 /* Search for end of command list or ":" ... */
944 while (optind < argc && STRNEQ (argv[optind], ":"))
947 if (optind == argc) {
948 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
952 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
954 cmdline (argv, optind+1, argc);
959 issue_command (const char *cmd, char *argv[], const char *pipecmd)
962 int stdout_saved_fd = -1;
966 /* This counts the commands issued, starting at 1. */
969 /* For | ... commands. Annoyingly we can't use popen(3) here. */
973 if (fflush (stdout) == EOF) {
974 perror ("failed to flush standard output");
978 perror ("pipe failed");
987 if (pid == 0) { /* Child process. */
989 if (dup2 (fd[0], 0) < 0) {
990 perror ("dup2 of stdin failed");
994 r = system (pipecmd);
999 _exit (WEXITSTATUS (r));
1002 if ((stdout_saved_fd = dup (1)) < 0) {
1003 perror ("failed to dup stdout");
1007 if (dup2 (fd[1], 1) < 0) {
1008 perror ("failed to dup stdout");
1009 close (stdout_saved_fd);
1015 for (argc = 0; argv[argc] != NULL; ++argc)
1018 /* If --remote was set, then send this command to a remote process. */
1020 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1022 /* Otherwise execute it locally. */
1023 else if (STRCASEEQ (cmd, "help")) {
1028 r = display_command (argv[0]);
1030 else if (STRCASEEQ (cmd, "quit") ||
1031 STRCASEEQ (cmd, "exit") ||
1032 STRCASEEQ (cmd, "q")) {
1036 else if (STRCASEEQ (cmd, "alloc") ||
1037 STRCASEEQ (cmd, "allocate"))
1038 r = do_alloc (cmd, argc, argv);
1039 else if (STRCASEEQ (cmd, "echo"))
1040 r = do_echo (cmd, argc, argv);
1041 else if (STRCASEEQ (cmd, "edit") ||
1042 STRCASEEQ (cmd, "vi") ||
1043 STRCASEEQ (cmd, "emacs"))
1044 r = do_edit (cmd, argc, argv);
1045 else if (STRCASEEQ (cmd, "lcd"))
1046 r = do_lcd (cmd, argc, argv);
1047 else if (STRCASEEQ (cmd, "glob"))
1048 r = do_glob (cmd, argc, argv);
1049 else if (STRCASEEQ (cmd, "man") ||
1050 STRCASEEQ (cmd, "manual"))
1051 r = do_man (cmd, argc, argv);
1052 else if (STRCASEEQ (cmd, "more") ||
1053 STRCASEEQ (cmd, "less"))
1054 r = do_more (cmd, argc, argv);
1055 else if (STRCASEEQ (cmd, "reopen"))
1056 r = do_reopen (cmd, argc, argv);
1057 else if (STRCASEEQ (cmd, "sparse"))
1058 r = do_sparse (cmd, argc, argv);
1059 else if (STRCASEEQ (cmd, "supported"))
1060 r = do_supported (cmd, argc, argv);
1061 else if (STRCASEEQ (cmd, "time"))
1062 r = do_time (cmd, argc, argv);
1064 r = run_action (cmd, argc, argv);
1066 /* Always flush stdout after every command, so that messages, results
1067 * etc appear immediately.
1069 if (fflush (stdout) == EOF) {
1070 perror ("failed to flush standard output");
1076 if (dup2 (stdout_saved_fd, 1) < 0) {
1077 perror ("failed to dup2 standard output");
1080 close (stdout_saved_fd);
1081 if (waitpid (pid, NULL, 0) < 0) {
1082 perror ("waiting for command to complete");
1091 list_builtin_commands (void)
1093 /* help, man and quit should appear at the top */
1094 printf ("%-20s %s\n",
1095 "help", _("display a list of commands or help on a command"));
1096 printf ("%-20s %s\n",
1097 "man", _("read the manual"));
1098 printf ("%-20s %s\n",
1099 "quit", _("quit guestfish"));
1101 printf ("%-20s %s\n",
1102 "alloc", _("allocate an image"));
1103 printf ("%-20s %s\n",
1104 "echo", _("display a line of text"));
1105 printf ("%-20s %s\n",
1106 "edit", _("edit a file in the image"));
1107 printf ("%-20s %s\n",
1108 "lcd", _("local change directory"));
1109 printf ("%-20s %s\n",
1110 "glob", _("expand wildcards in command"));
1111 printf ("%-20s %s\n",
1112 "more", _("view a file in the pager"));
1113 printf ("%-20s %s\n",
1114 "reopen", _("close and reopen libguestfs handle"));
1115 printf ("%-20s %s\n",
1116 "sparse", _("allocate a sparse image file"));
1117 printf ("%-20s %s\n",
1118 "supported", _("list supported groups of commands"));
1119 printf ("%-20s %s\n",
1120 "time", _("measure time taken to run command"));
1122 /* actions are printed after this (see list_commands) */
1126 display_builtin_command (const char *cmd)
1128 /* help for actions is auto-generated, see display_command */
1130 if (STRCASEEQ (cmd, "alloc") ||
1131 STRCASEEQ (cmd, "allocate")) {
1132 printf (_("alloc - allocate an image\n"
1133 " alloc <filename> <size>\n"
1135 " This creates an empty (zeroed) file of the given size,\n"
1136 " and then adds so it can be further examined.\n"
1138 " For more advanced image creation, see qemu-img utility.\n"
1140 " Size can be specified using standard suffixes, eg. '1M'.\n"
1144 else if (STRCASEEQ (cmd, "echo")) {
1145 printf (_("echo - display a line of text\n"
1146 " echo [<params> ...]\n"
1148 " This echos the parameters to the terminal.\n"));
1151 else if (STRCASEEQ (cmd, "edit") ||
1152 STRCASEEQ (cmd, "vi") ||
1153 STRCASEEQ (cmd, "emacs")) {
1154 printf (_("edit - edit a file in the image\n"
1155 " edit <filename>\n"
1157 " This is used to edit a file.\n"
1159 " It is the equivalent of (and is implemented by)\n"
1160 " running \"cat\", editing locally, and then \"write\".\n"
1162 " Normally it uses $EDITOR, but if you use the aliases\n"
1163 " \"vi\" or \"emacs\" you will get those editors.\n"
1165 " NOTE: This will not work reliably for large files\n"
1166 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1169 else if (STRCASEEQ (cmd, "lcd")) {
1170 printf (_("lcd - local change directory\n"
1171 " lcd <directory>\n"
1173 " Change guestfish's current directory. This command is\n"
1174 " useful if you want to download files to a particular\n"
1178 else if (STRCASEEQ (cmd, "glob")) {
1179 printf (_("glob - expand wildcards in command\n"
1180 " glob <command> [<args> ...]\n"
1182 " Glob runs <command> with wildcards expanded in any\n"
1183 " command args. Note that the command is run repeatedly\n"
1184 " once for each expanded argument.\n"));
1187 else if (STRCASEEQ (cmd, "man") ||
1188 STRCASEEQ (cmd, "manual")) {
1189 printf (_("man - read the manual\n"
1192 " Opens the manual page for guestfish.\n"));
1195 else if (STRCASEEQ (cmd, "help")) {
1196 printf (_("help - display a list of commands or help on a command\n"
1201 else if (STRCASEEQ (cmd, "more") ||
1202 STRCASEEQ (cmd, "less")) {
1203 printf (_("more - view a file in the pager\n"
1204 " more <filename>\n"
1206 " This is used to view a file in the pager.\n"
1208 " It is the equivalent of (and is implemented by)\n"
1209 " running \"cat\" and using the pager.\n"
1211 " Normally it uses $PAGER, but if you use the alias\n"
1212 " \"less\" then it always uses \"less\".\n"
1214 " NOTE: This will not work reliably for large files\n"
1215 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1218 else if (STRCASEEQ (cmd, "quit") ||
1219 STRCASEEQ (cmd, "exit") ||
1220 STRCASEEQ (cmd, "q")) {
1221 printf (_("quit - quit guestfish\n"
1225 else if (STRCASEEQ (cmd, "reopen")) {
1226 printf (_("reopen - close and reopen the libguestfs handle\n"
1229 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1230 "this normally, because the handle is closed properly when guestfish\n"
1231 "exits. However this is occasionally useful for testing.\n"));
1234 else if (STRCASEEQ (cmd, "sparse")) {
1235 printf (_("sparse - allocate a sparse image file\n"
1236 " sparse <filename> <size>\n"
1238 " This creates an empty sparse file of the given size,\n"
1239 " and then adds so it can be further examined.\n"
1241 " In all respects it works the same as the 'alloc'\n"
1242 " command, except that the image file is allocated\n"
1243 " sparsely, which means that disk blocks are not assigned\n"
1244 " to the file until they are needed. Sparse disk files\n"
1245 " only use space when written to, but they are slower\n"
1246 " and there is a danger you could run out of real disk\n"
1247 " space during a write operation.\n"
1249 " For more advanced image creation, see qemu-img utility.\n"
1251 " Size can be specified using standard suffixes, eg. '1M'.\n"
1255 else if (STRCASEEQ (cmd, "supported")) {
1256 printf (_("supported - list supported groups of commands\n"
1259 " This command returns a list of the optional groups\n"
1260 " known to the daemon, and indicates which ones are\n"
1261 " supported by this build of the libguestfs appliance.\n"
1263 " See also guestfs(3) section AVAILABILITY.\n"
1267 else if (STRCASEEQ (cmd, "time")) {
1268 printf (_("time - measure time taken to run command\n"
1269 " time <command> [<args> ...]\n"
1271 " This runs <command> as usual, and prints the elapsed\n"
1272 " time afterwards.\n"));
1276 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1282 /* This is printed when the user types in an unknown command for the
1283 * first command issued. A common case is the user doing:
1284 * guestfish disk.img
1285 * expecting guestfish to open 'disk.img' (in fact, this tried to
1286 * run a command 'disk.img').
1289 extended_help_message (void)
1292 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1293 "For a list of commands: guestfish -h\n"
1294 "For complete documentation: man guestfish\n"));
1298 free_strings (char **argv)
1302 for (argc = 0; argv[argc] != NULL; ++argc)
1308 count_strings (char *const *argv)
1312 for (c = 0; argv[c]; ++c)
1318 print_strings (char *const *argv)
1322 for (argc = 0; argv[argc] != NULL; ++argc)
1323 printf ("%s\n", argv[argc]);
1327 print_table (char *const *argv)
1331 for (i = 0; argv[i] != NULL; i += 2)
1332 printf ("%s: %s\n", argv[i], argv[i+1]);
1336 is_true (const char *str)
1339 STRCASENEQ (str, "0") &&
1340 STRCASENEQ (str, "f") &&
1341 STRCASENEQ (str, "false") &&
1342 STRCASENEQ (str, "n") &&
1343 STRCASENEQ (str, "no");
1346 /* Free strings from a non-NULL terminated char** */
1348 free_n_strings (char **str, size_t len)
1352 for (i = 0; i < len; i++) {
1359 parse_string_list (const char *str)
1362 size_t argv_len = 0;
1364 /* Current position pointer */
1365 const char *p = str;
1367 /* Token might be simple:
1370 * 'This is a single token'
1371 * or contain embedded single-quoted sections:
1372 * This' is a sing'l'e to'ken
1374 * The latter may seem over-complicated, but it's what a normal shell does.
1375 * Not doing it risks surprising somebody.
1377 * This outer loop is over complete tokens.
1383 /* Skip leading whitespace */
1384 p += strspn (p, " \t");
1388 /* This loop is over token 'fragments'. A token can be in multiple bits if
1389 * it contains single quotes. We also treat both sides of an escaped quote
1390 * as separate fragments because we can't just copy it: we have to remove
1393 while (*p && (!c_isblank (*p) || in_quote)) {
1394 const char *end = p;
1396 /* Check if the fragment starts with a quote */
1398 /* Toggle in_quote */
1399 in_quote = !in_quote;
1401 /* Skip the quote */
1405 /* If we're in a quote, look for an end quote */
1407 end += strcspn (end, "'");
1410 /* Otherwise, look for whitespace or a quote */
1412 end += strcspn (end, " \t'");
1415 /* Grow the token to accommodate the fragment */
1416 size_t tok_end = tok_len;
1418 char *tok_new = realloc (tok, tok_len + 1);
1419 if (NULL == tok_new) {
1421 free_n_strings (argv, argv_len);
1423 exit (EXIT_FAILURE);
1427 /* Check if we stopped on an escaped quote */
1428 if ('\'' == *end && end != p && *(end-1) == '\\') {
1429 /* Add everything before \' to the token */
1430 memcpy (&tok[tok_end], p, end - p - 1);
1433 tok[tok_len-1] = '\'';
1435 /* Already processed the quote */
1440 /* Add the whole fragment */
1441 memcpy (&tok[tok_end], p, end - p);
1447 /* We've reached the end of a token. We shouldn't still be in quotes. */
1449 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1451 free_n_strings (argv, argv_len);
1456 /* Add this token if there is one. There might not be if there was
1457 * whitespace at the end of the input string */
1459 /* Add the NULL terminator */
1460 tok[tok_len] = '\0';
1462 /* Add the argument to the argument list */
1464 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1465 if (NULL == argv_new) {
1467 free_n_strings (argv, argv_len-1);
1469 exit (EXIT_FAILURE);
1473 argv[argv_len-1] = tok;
1477 /* NULL terminate the argument list */
1479 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1480 if (NULL == argv_new) {
1482 free_n_strings (argv, argv_len-1);
1483 exit (EXIT_FAILURE);
1487 argv[argv_len-1] = NULL;
1492 #ifdef HAVE_LIBREADLINE
1493 static char histfile[1024];
1494 static int nr_history_lines = 0;
1498 initialize_readline (void)
1500 #ifdef HAVE_LIBREADLINE
1503 home = getenv ("HOME");
1505 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1507 (void) read_history (histfile);
1510 rl_readline_name = "guestfish";
1511 rl_attempted_completion_function = do_completion;
1513 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1514 * call the readline(), which happens later. Therefore, these
1515 * provide default values which can be overridden by the user if
1518 (void) rl_variable_bind ("completion-ignore-case", "on");
1523 cleanup_readline (void)
1525 #ifdef HAVE_LIBREADLINE
1528 if (histfile[0] != '\0') {
1529 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1536 #ifdef HAVE_APPEND_HISTORY
1537 (void) append_history (nr_history_lines, histfile);
1539 (void) write_history (histfile);
1545 #ifdef HAVE_LIBREADLINE
1547 add_history_line (const char *line)
1555 xwrite (int fd, const void *v_buf, size_t len)
1558 const char *buf = v_buf;
1561 r = write (fd, buf, len);
1573 /* Resolve the special "win:..." form for Windows-specific paths.
1574 * This always returns a newly allocated string which is freed by the
1575 * caller function in "cmds.c".
1578 resolve_win_path (const char *path)
1583 if (STRCASENEQLEN (path, "win:", 4)) {
1584 ret = strdup (path);
1592 /* Drop drive letter, if it's "C:". */
1593 if (STRCASEEQLEN (path, "c:", 2))
1603 ret = strdup (path);
1609 /* Blindly convert any backslashes into forward slashes. Is this good? */
1610 for (i = 0; i < strlen (ret); ++i)
1614 char *t = guestfs_case_sensitive_path (g, ret);
1621 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1622 * The caller (cmds.c) will call free_file_in after the command has
1623 * run which should clean up resources.
1625 static char *file_in_heredoc (const char *endmarker);
1626 static char *file_in_tmpfile = NULL;
1629 file_in (const char *arg)
1633 if (STREQ (arg, "-")) {
1634 ret = strdup ("/dev/stdin");
1640 else if (STRPREFIX (arg, "-<<")) {
1641 const char *endmarker = &arg[3];
1642 if (*endmarker == '\0') {
1643 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1647 ret = file_in_heredoc (endmarker);
1663 file_in_heredoc (const char *endmarker)
1665 static const char template[] = "/tmp/heredocXXXXXX";
1666 file_in_tmpfile = strdup (template);
1667 if (file_in_tmpfile == NULL) {
1672 int fd = mkstemp (file_in_tmpfile);
1678 size_t markerlen = strlen (endmarker);
1680 char buffer[BUFSIZ];
1681 int write_error = 0;
1682 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1683 /* Look for "END"<EOF> or "END\n" in input. */
1684 size_t blen = strlen (buffer);
1685 if (STREQLEN (buffer, endmarker, markerlen) &&
1686 (blen == markerlen ||
1687 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1690 if (xwrite (fd, buffer, blen) == -1) {
1691 if (!write_error) perror ("write");
1693 /* continue reading up to the end marker */
1697 /* Reached EOF of stdin without finding the end marker, which
1698 * is likely to be an error.
1700 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1701 program_name, endmarker);
1710 if (close (fd) == -1) {
1715 return file_in_tmpfile;
1718 unlink (file_in_tmpfile);
1721 free (file_in_tmpfile);
1722 file_in_tmpfile = NULL;
1727 free_file_in (char *s)
1729 if (file_in_tmpfile) {
1730 if (unlink (file_in_tmpfile) == -1)
1731 perror (file_in_tmpfile);
1732 file_in_tmpfile = NULL;
1735 /* Free the device or file name which was strdup'd in file_in().
1736 * Note it's not immediately clear, but for -<< heredocs,
1737 * s == file_in_tmpfile, so this frees up that buffer.
1742 /* Resolve the special FileOut paths ("-" or filename).
1743 * The caller (cmds.c) will call free (str) after the command has run.
1746 file_out (const char *arg)
1750 if (STREQ (arg, "-"))
1751 ret = strdup ("/dev/stdout");
1762 /* Read a passphrase ('Key') from /dev/tty with echo off.
1763 * The caller (cmds.c) will call free on the string afterwards.
1764 * Based on the code in cryptsetup file lib/utils.c.
1767 read_key (const char *param)
1770 struct termios orig, temp;
1773 /* Read and write to /dev/tty if available. */
1774 if (keys_from_stdin ||
1775 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1780 /* Print the prompt and set no echo. */
1781 int tty = isatty (fileno (infp));
1784 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1786 if (tcgetattr (fileno (infp), &orig) == -1) {
1787 perror ("tcgetattr");
1790 memcpy (&temp, &orig, sizeof temp);
1791 temp.c_lflag &= ~ECHO;
1793 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1799 len = getline (&ret, &n, infp);
1806 /* Remove the terminating \n if there is one. */
1807 if (len > 0 && ret[len-1] == '\n')
1811 /* Restore echo, close file descriptor. */
1814 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1818 fclose (infp); /* outfp == infp, so this is closed also */