1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2010 Red Hat Inc.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #include <sys/types.h>
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
46 /* List of drives added via -a, -d or -N options. */
49 enum { drv_a, drv_d, drv_N } type;
52 char *filename; /* disk filename */
55 char *guest; /* guest name */
58 char *filename; /* disk filename (testX.img) */
59 prep_data *data; /* prepared type */
60 char *device; /* device inside the appliance */
71 static char add_drives (struct drv *drv, char next_drive);
72 static void prepare_drives (struct drv *drv);
73 static void mount_mps (struct mp *mp);
74 static int launch (void);
75 static void interactive (void);
76 static void shell_script (void);
77 static void script (int prompt);
78 static void cmdline (char *argv[], int optind, int argc);
79 static void initialize_readline (void);
80 static void cleanup_readline (void);
81 #ifdef HAVE_LIBREADLINE
82 static void add_history_line (const char *);
85 /* Currently open libguestfs handle. */
91 int remote_control_listen = 0;
92 int remote_control = 0;
93 int exit_on_error = 1;
95 int keys_from_stdin = 0;
96 const char *libvirt_uri = NULL;
99 static void __attribute__((noreturn))
102 if (status != EXIT_SUCCESS)
103 fprintf (stderr, _("Try `%s --help' for more information.\n"),
107 _("%s: guest filesystem shell\n"
108 "%s lets you edit virtual machine filesystems\n"
109 "Copyright (C) 2009 Red Hat Inc.\n"
111 " %s [--options] cmd [: cmd : cmd ...]\n"
112 " %s -i libvirt-domain\n"
113 " %s -i disk-image(s)\n"
114 "or for interactive use:\n"
116 "or from a shell script:\n"
122 " -h|--cmd-help List available commands\n"
123 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
124 " -a|--add image Add image\n"
125 " -c|--connect uri Specify libvirt URI for -d option\n"
126 " -d|--domain guest Add disks from libvirt guest\n"
127 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
128 " -f|--file file Read commands from file\n"
129 " -i|--inspector Automatically mount filesystems\n"
130 " --keys-from-stdin Read passphrases from stdin\n"
131 " --listen Listen for remote commands\n"
132 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
133 " -n|--no-sync Don't autosync\n"
134 " -N|--new type Create prepared disk (test1.img, ...)\n"
135 " --remote[=pid] Send commands to remote %s\n"
136 " -r|--ro Mount read-only\n"
137 " --selinux Enable SELinux support\n"
138 " -v|--verbose Verbose messages\n"
139 " -x Echo each command before executing it\n"
140 " -V|--version Display version and exit\n"
141 "For more information, see the manpage %s(1).\n"),
142 program_name, program_name, program_name,
143 program_name, program_name, program_name,
144 program_name, program_name, program_name);
150 main (int argc, char *argv[])
152 /* Set global program name that is not polluted with libtool artifacts. */
153 set_program_name (argv[0]);
155 atexit (close_stdout);
157 setlocale (LC_ALL, "");
158 bindtextdomain (PACKAGE, LOCALEBASEDIR);
159 textdomain (PACKAGE);
161 enum { HELP_OPTION = CHAR_MAX + 1 };
163 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
164 static const struct option long_options[] = {
165 { "add", 1, 0, 'a' },
166 { "cmd-help", 2, 0, 'h' },
167 { "connect", 1, 0, 'c' },
168 { "domain", 1, 0, 'd' },
169 { "file", 1, 0, 'f' },
170 { "help", 0, 0, HELP_OPTION },
171 { "inspector", 0, 0, 'i' },
172 { "keys-from-stdin", 0, 0, 0 },
173 { "listen", 0, 0, 0 },
174 { "mount", 1, 0, 'm' },
175 { "new", 1, 0, 'N' },
176 { "no-dest-paths", 0, 0, 'D' },
177 { "no-sync", 0, 0, 'n' },
178 { "remote", 2, 0, 0 },
180 { "selinux", 0, 0, 0 },
181 { "verbose", 0, 0, 'v' },
182 { "version", 0, 0, 'V' },
185 struct drv *drvs = NULL;
187 struct mp *mps = NULL;
189 char *p, *file = NULL;
193 int next_prepared_drive = 1;
195 initialize_readline ();
197 memset (&sa, 0, sizeof sa);
198 sa.sa_handler = SIG_IGN;
199 sa.sa_flags = SA_RESTART;
200 sigaction (SIGPIPE, &sa, NULL);
202 /* guestfs_create is meant to be a lightweight operation, so
203 * it's OK to do it early here.
205 g = guestfs_create ();
207 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
211 guestfs_set_autosync (g, 1);
213 /* If developing, add ./appliance to the path. Note that libtools
214 * interferes with this because uninstalled guestfish is a shell
215 * script that runs the real program with an absolute path. Detect
218 * BUT if LIBGUESTFS_PATH environment variable is already set by
219 * the user, then don't override it.
221 if (getenv ("LIBGUESTFS_PATH") == NULL &&
223 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
224 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
226 /* CAUTION: we are careful to modify argv[0] here, only after
227 * using it just above.
229 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
230 * of the original, in case it's needed below.
232 char *real_argv0 = argv[0];
233 argv[0] = bad_cast (program_name);
236 c = getopt_long (argc, argv, options, long_options, &option_index);
240 case 0: /* options which are long only */
241 if (STREQ (long_options[option_index].name, "listen"))
242 remote_control_listen = 1;
243 else if (STREQ (long_options[option_index].name, "remote")) {
245 if (sscanf (optarg, "%d", &remote_control) != 1) {
246 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
247 program_name, optarg);
251 p = getenv ("GUESTFISH_PID");
252 if (!p || sscanf (p, "%d", &remote_control) != 1) {
253 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
254 " to the PID of the remote process\n"),
259 } else if (STREQ (long_options[option_index].name, "selinux")) {
260 guestfs_set_selinux (g, 1);
261 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
264 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
265 program_name, long_options[option_index].name, option_index);
271 if (access (optarg, R_OK) != 0) {
275 drv = malloc (sizeof (struct drv));
281 drv->a.filename = optarg;
287 libvirt_uri = optarg;
291 drv = malloc (sizeof (struct drv));
297 drv->d.guest = optarg;
303 if (STRCASEEQ (optarg, "list")) {
304 list_prepared_drives ();
307 drv = malloc (sizeof (struct drv));
313 if (asprintf (&drv->N.filename, "test%d.img",
314 next_prepared_drive++) == -1) {
318 drv->N.data = create_prepared_file (optarg, drv->N.filename);
319 drv->N.device = NULL; /* filled in by add_drives */
325 complete_dest_paths = 0;
330 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
341 r = display_command (optarg);
342 else if (argv[optind] && argv[optind][0] != '-')
343 r = display_command (argv[optind++]);
347 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
355 mp = malloc (sizeof (struct mp));
360 p = strchr (optarg, ':');
363 mp->mountpoint = p+1;
365 mp->mountpoint = bad_cast ("/");
372 guestfs_set_autosync (g, 0);
381 guestfs_set_verbose (g, verbose);
385 printf ("%s %s\n", program_name, PACKAGE_VERSION);
389 guestfs_set_trace (g, 1);
393 usage (EXIT_SUCCESS);
396 usage (EXIT_FAILURE);
400 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
401 * previously, if we have -i without any drives but with something
402 * on the command line, it must be old-style syntax.
404 if (inspector && drvs == NULL && optind < argc) {
405 while (optind < argc) {
406 if (strchr (argv[optind], '/') ||
407 access (argv[optind], F_OK) == 0) { /* simulate -a option */
408 drv = malloc (sizeof (struct drv));
414 drv->a.filename = argv[optind];
417 } else { /* simulate -d option */
418 drv = malloc (sizeof (struct drv));
424 drv->d.guest = argv[optind];
433 /* If we've got drives to add, add them now. */
434 add_drives (drvs, 'a');
436 /* If we've got mountpoints or prepared drives or -i option, we must
437 * launch the guest and mount them.
439 if (next_prepared_drive > 1 || mps != NULL || inspector) {
440 /* RHBZ#612178: If --listen flag is given, then we will fork into
441 * the background in rc_listen(). However you can't do this while
442 * holding a libguestfs handle open because the recovery process
443 * will think the main program has died and kill qemu. Therefore
444 * don't use the recovery process for this case. (A better
445 * solution would be to call launch () etc after the fork, but
446 * that greatly complicates the code here).
448 if (remote_control_listen)
449 guestfs_set_recovery_proc (g, 0);
451 if (launch () == -1) exit (EXIT_FAILURE);
456 prepare_drives (drvs);
460 /* Remote control? */
461 if (remote_control_listen && remote_control) {
463 _("%s: cannot use --listen and --remote options at the same time\n"),
468 if (remote_control_listen) {
471 _("%s: extra parameters on the command line with --listen flag\n"),
477 _("%s: cannot use --listen and --file options at the same time\n"),
484 /* -f (file) parameter? */
487 if (open (file, O_RDONLY) == -1) {
493 /* Interactive, shell script, or command(s) on the command line? */
494 if (optind >= argc) {
501 cmdline (argv, optind, argc);
509 pod2text (const char *name, const char *shortdesc, const char *str)
513 fp = popen ("pod2text", "w");
515 /* pod2text failed, maybe not found, so let's just print the
516 * source instead, since that's better than doing nothing.
518 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
521 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
526 /* List is built in reverse order, so mount them in reverse order. */
528 mount_mps (struct mp *mp)
533 mount_mps (mp->next);
535 /* Don't use guestfs_mount here because that will default to mount
536 * options -o sync,noatime. For more information, see guestfs(3)
537 * section "LIBGUESTFS GOTCHAS".
539 const char *options = read_only ? "ro" : "";
540 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
547 add_drives (struct drv *drv, char next_drive)
551 if (next_drive > 'z') {
553 _("guestfish: too many drives added on the command line\n"));
558 next_drive = add_drives (drv->next, next_drive);
563 r = guestfs_add_drive (g, drv->a.filename);
565 r = guestfs_add_drive_ro (g, drv->a.filename);
573 r = add_libvirt_drives (drv->d.guest);
581 /* -N option is not affected by --ro */
582 r = guestfs_add_drive (g, drv->N.filename);
586 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
594 default: /* keep GCC happy */
603 prepare_drives (struct drv *drv)
606 prepare_drives (drv->next);
607 if (drv->type == drv_N)
608 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
615 if (guestfs_is_config (g)) {
616 if (guestfs_launch (g) == -1)
634 #define FISH "><fs> "
636 static char *line_read = NULL;
641 #ifdef HAVE_LIBREADLINE
649 line_read = readline (prompt ? FISH : "");
651 if (line_read && *line_read)
652 add_history_line (line_read);
657 #endif /* HAVE_LIBREADLINE */
659 static char buf[8192];
662 if (prompt) printf (FISH);
663 line_read = fgets (buf, sizeof buf, stdin);
666 len = strlen (line_read);
667 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
681 int global_exit_on_error = !prompt;
686 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
687 "editing virtual machine filesystems.\n"
689 "Type: 'help' for a list of commands\n"
690 " 'man' to read the manual\n"
691 " 'quit' to quit the shell\n"
695 print_inspect_prompt ();
703 exit_on_error = global_exit_on_error;
705 buf = rl_gets (prompt);
711 /* Skip any initial whitespace before the command. */
713 while (*buf && c_isspace (*buf))
718 /* If the next character is '#' then this is a comment. */
719 if (*buf == '#') continue;
721 /* If the next character is '!' then pass the whole lot to system(3). */
729 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
730 WEXITSTATUS (r) != 0)
736 /* If the next character is '-' allow the command to fail without
737 * exiting on error (just for this one command though).
745 /* Get the command (cannot be quoted). */
746 len = strcspn (buf, " \t");
748 if (len == 0) continue;
752 if (buf[len] == '\0') {
759 p += strspn (p, " \t");
761 /* Get the parameters. */
762 while (*p && i < sizeof argv / sizeof argv[0]) {
765 /* Parameters which start with quotes or pipes are treated
766 * specially. Bare parameters are delimited by whitespace.
770 len = strcspn (p, "\"");
771 if (p[len] == '\0') {
772 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
773 if (exit_on_error) exit (EXIT_FAILURE);
776 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
778 _("%s: command arguments not separated by whitespace\n"),
780 if (exit_on_error) exit (EXIT_FAILURE);
784 pend = p[len+1] ? &p[len+2] : &p[len+1];
785 } else if (*p == '\'') {
787 len = strcspn (p, "'");
788 if (p[len] == '\0') {
789 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
790 if (exit_on_error) exit (EXIT_FAILURE);
793 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
795 _("%s: command arguments not separated by whitespace\n"),
797 if (exit_on_error) exit (EXIT_FAILURE);
801 pend = p[len+1] ? &p[len+2] : &p[len+1];
802 } else if (*p == '|') {
807 } else if (*p == '[') {
811 while (*pend && c != 0) {
812 if (*pend == '[') c++;
813 else if (*pend == ']') c--;
818 _("%s: unterminated \"[...]\" sequence\n"), program_name);
819 if (exit_on_error) exit (EXIT_FAILURE);
822 if (*pend && (*pend != ' ' && *pend != '\t')) {
824 _("%s: command arguments not separated by whitespace\n"),
826 if (exit_on_error) exit (EXIT_FAILURE);
831 } else if (*p != ' ' && *p != '\t') {
832 /* If the first character is a ~ then note that this parameter
833 * is a candidate for ~username expansion. NB this does not
834 * apply to quoted parameters.
836 tilde_candidate = *p == '~';
837 len = strcspn (p, " \t");
844 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
849 if (!tilde_candidate)
852 argv[i] = try_tilde_expansion (p);
857 p += strspn (p, " \t");
860 if (i == sizeof argv / sizeof argv[0]) {
861 fprintf (stderr, _("%s: too many arguments\n"), program_name);
862 if (exit_on_error) exit (EXIT_FAILURE);
869 if (issue_command (cmd, argv, pipe) == -1) {
870 if (exit_on_error) exit (EXIT_FAILURE);
875 if (prompt) printf ("\n");
879 cmdline (char *argv[], int optind, int argc)
886 if (optind >= argc) return;
888 cmd = argv[optind++];
889 if (STREQ (cmd, ":")) {
890 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
894 /* Allow -cmd on the command line to mean (temporarily) override
895 * the normal exit on error (RHBZ#578407).
902 params = &argv[optind];
904 /* Search for end of command list or ":" ... */
905 while (optind < argc && STRNEQ (argv[optind], ":"))
908 if (optind == argc) {
909 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
913 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
915 cmdline (argv, optind+1, argc);
920 issue_command (const char *cmd, char *argv[], const char *pipecmd)
923 int stdout_saved_fd = -1;
927 /* This counts the commands issued, starting at 1. */
930 /* For | ... commands. Annoyingly we can't use popen(3) here. */
934 if (fflush (stdout) == EOF) {
935 perror ("failed to flush standard output");
939 perror ("pipe failed");
948 if (pid == 0) { /* Child process. */
950 if (dup2 (fd[0], 0) < 0) {
951 perror ("dup2 of stdin failed");
955 r = system (pipecmd);
960 _exit (WEXITSTATUS (r));
963 if ((stdout_saved_fd = dup (1)) < 0) {
964 perror ("failed to dup stdout");
968 if (dup2 (fd[1], 1) < 0) {
969 perror ("failed to dup stdout");
970 close (stdout_saved_fd);
976 for (argc = 0; argv[argc] != NULL; ++argc)
979 /* If --remote was set, then send this command to a remote process. */
981 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
983 /* Otherwise execute it locally. */
984 else if (STRCASEEQ (cmd, "help")) {
989 r = display_command (argv[0]);
991 else if (STRCASEEQ (cmd, "quit") ||
992 STRCASEEQ (cmd, "exit") ||
993 STRCASEEQ (cmd, "q")) {
997 else if (STRCASEEQ (cmd, "alloc") ||
998 STRCASEEQ (cmd, "allocate"))
999 r = do_alloc (cmd, argc, argv);
1000 else if (STRCASEEQ (cmd, "echo"))
1001 r = do_echo (cmd, argc, argv);
1002 else if (STRCASEEQ (cmd, "edit") ||
1003 STRCASEEQ (cmd, "vi") ||
1004 STRCASEEQ (cmd, "emacs"))
1005 r = do_edit (cmd, argc, argv);
1006 else if (STRCASEEQ (cmd, "lcd"))
1007 r = do_lcd (cmd, argc, argv);
1008 else if (STRCASEEQ (cmd, "glob"))
1009 r = do_glob (cmd, argc, argv);
1010 else if (STRCASEEQ (cmd, "man") ||
1011 STRCASEEQ (cmd, "manual"))
1012 r = do_man (cmd, argc, argv);
1013 else if (STRCASEEQ (cmd, "more") ||
1014 STRCASEEQ (cmd, "less"))
1015 r = do_more (cmd, argc, argv);
1016 else if (STRCASEEQ (cmd, "reopen"))
1017 r = do_reopen (cmd, argc, argv);
1018 else if (STRCASEEQ (cmd, "sparse"))
1019 r = do_sparse (cmd, argc, argv);
1020 else if (STRCASEEQ (cmd, "supported"))
1021 r = do_supported (cmd, argc, argv);
1022 else if (STRCASEEQ (cmd, "time"))
1023 r = do_time (cmd, argc, argv);
1025 r = run_action (cmd, argc, argv);
1027 /* Always flush stdout after every command, so that messages, results
1028 * etc appear immediately.
1030 if (fflush (stdout) == EOF) {
1031 perror ("failed to flush standard output");
1037 if (dup2 (stdout_saved_fd, 1) < 0) {
1038 perror ("failed to dup2 standard output");
1041 close (stdout_saved_fd);
1042 if (waitpid (pid, NULL, 0) < 0) {
1043 perror ("waiting for command to complete");
1052 list_builtin_commands (void)
1054 /* help, man and quit should appear at the top */
1055 printf ("%-20s %s\n",
1056 "help", _("display a list of commands or help on a command"));
1057 printf ("%-20s %s\n",
1058 "man", _("read the manual"));
1059 printf ("%-20s %s\n",
1060 "quit", _("quit guestfish"));
1062 printf ("%-20s %s\n",
1063 "alloc", _("allocate an image"));
1064 printf ("%-20s %s\n",
1065 "echo", _("display a line of text"));
1066 printf ("%-20s %s\n",
1067 "edit", _("edit a file in the image"));
1068 printf ("%-20s %s\n",
1069 "lcd", _("local change directory"));
1070 printf ("%-20s %s\n",
1071 "glob", _("expand wildcards in command"));
1072 printf ("%-20s %s\n",
1073 "more", _("view a file in the pager"));
1074 printf ("%-20s %s\n",
1075 "reopen", _("close and reopen libguestfs handle"));
1076 printf ("%-20s %s\n",
1077 "sparse", _("allocate a sparse image file"));
1078 printf ("%-20s %s\n",
1079 "supported", _("list supported groups of commands"));
1080 printf ("%-20s %s\n",
1081 "time", _("measure time taken to run command"));
1083 /* actions are printed after this (see list_commands) */
1087 display_builtin_command (const char *cmd)
1089 /* help for actions is auto-generated, see display_command */
1091 if (STRCASEEQ (cmd, "alloc") ||
1092 STRCASEEQ (cmd, "allocate")) {
1093 printf (_("alloc - allocate an image\n"
1094 " alloc <filename> <size>\n"
1096 " This creates an empty (zeroed) file of the given size,\n"
1097 " and then adds so it can be further examined.\n"
1099 " For more advanced image creation, see qemu-img utility.\n"
1101 " Size can be specified using standard suffixes, eg. '1M'.\n"
1105 else if (STRCASEEQ (cmd, "echo")) {
1106 printf (_("echo - display a line of text\n"
1107 " echo [<params> ...]\n"
1109 " This echos the parameters to the terminal.\n"));
1112 else if (STRCASEEQ (cmd, "edit") ||
1113 STRCASEEQ (cmd, "vi") ||
1114 STRCASEEQ (cmd, "emacs")) {
1115 printf (_("edit - edit a file in the image\n"
1116 " edit <filename>\n"
1118 " This is used to edit a file.\n"
1120 " It is the equivalent of (and is implemented by)\n"
1121 " running \"cat\", editing locally, and then \"write\".\n"
1123 " Normally it uses $EDITOR, but if you use the aliases\n"
1124 " \"vi\" or \"emacs\" you will get those editors.\n"
1126 " NOTE: This will not work reliably for large files\n"
1127 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1130 else if (STRCASEEQ (cmd, "lcd")) {
1131 printf (_("lcd - local change directory\n"
1132 " lcd <directory>\n"
1134 " Change guestfish's current directory. This command is\n"
1135 " useful if you want to download files to a particular\n"
1139 else if (STRCASEEQ (cmd, "glob")) {
1140 printf (_("glob - expand wildcards in command\n"
1141 " glob <command> [<args> ...]\n"
1143 " Glob runs <command> with wildcards expanded in any\n"
1144 " command args. Note that the command is run repeatedly\n"
1145 " once for each expanded argument.\n"));
1148 else if (STRCASEEQ (cmd, "man") ||
1149 STRCASEEQ (cmd, "manual")) {
1150 printf (_("man - read the manual\n"
1153 " Opens the manual page for guestfish.\n"));
1156 else if (STRCASEEQ (cmd, "help")) {
1157 printf (_("help - display a list of commands or help on a command\n"
1162 else if (STRCASEEQ (cmd, "more") ||
1163 STRCASEEQ (cmd, "less")) {
1164 printf (_("more - view a file in the pager\n"
1165 " more <filename>\n"
1167 " This is used to view a file in the pager.\n"
1169 " It is the equivalent of (and is implemented by)\n"
1170 " running \"cat\" and using the pager.\n"
1172 " Normally it uses $PAGER, but if you use the alias\n"
1173 " \"less\" then it always uses \"less\".\n"
1175 " NOTE: This will not work reliably for large files\n"
1176 " (> 2 MB) or binary files containing \\0 bytes.\n"));
1179 else if (STRCASEEQ (cmd, "quit") ||
1180 STRCASEEQ (cmd, "exit") ||
1181 STRCASEEQ (cmd, "q")) {
1182 printf (_("quit - quit guestfish\n"
1186 else if (STRCASEEQ (cmd, "reopen")) {
1187 printf (_("reopen - close and reopen the libguestfs handle\n"
1190 "Close and reopen the libguestfs handle. It is not necessary to use\n"
1191 "this normally, because the handle is closed properly when guestfish\n"
1192 "exits. However this is occasionally useful for testing.\n"));
1195 else if (STRCASEEQ (cmd, "sparse")) {
1196 printf (_("sparse - allocate a sparse image file\n"
1197 " sparse <filename> <size>\n"
1199 " This creates an empty sparse file of the given size,\n"
1200 " and then adds so it can be further examined.\n"
1202 " In all respects it works the same as the 'alloc'\n"
1203 " command, except that the image file is allocated\n"
1204 " sparsely, which means that disk blocks are not assigned\n"
1205 " to the file until they are needed. Sparse disk files\n"
1206 " only use space when written to, but they are slower\n"
1207 " and there is a danger you could run out of real disk\n"
1208 " space during a write operation.\n"
1210 " For more advanced image creation, see qemu-img utility.\n"
1212 " Size can be specified using standard suffixes, eg. '1M'.\n"
1216 else if (STRCASEEQ (cmd, "supported")) {
1217 printf (_("supported - list supported groups of commands\n"
1220 " This command returns a list of the optional groups\n"
1221 " known to the daemon, and indicates which ones are\n"
1222 " supported by this build of the libguestfs appliance.\n"
1224 " See also guestfs(3) section AVAILABILITY.\n"
1228 else if (STRCASEEQ (cmd, "time")) {
1229 printf (_("time - measure time taken to run command\n"
1230 " time <command> [<args> ...]\n"
1232 " This runs <command> as usual, and prints the elapsed\n"
1233 " time afterwards.\n"));
1237 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1243 /* This is printed when the user types in an unknown command for the
1244 * first command issued. A common case is the user doing:
1245 * guestfish disk.img
1246 * expecting guestfish to open 'disk.img' (in fact, this tried to
1247 * run a command 'disk.img').
1250 extended_help_message (void)
1253 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1254 "For a list of commands: guestfish -h\n"
1255 "For complete documentation: man guestfish\n"));
1259 free_strings (char **argv)
1263 for (argc = 0; argv[argc] != NULL; ++argc)
1269 count_strings (char *const *argv)
1273 for (c = 0; argv[c]; ++c)
1279 print_strings (char *const *argv)
1283 for (argc = 0; argv[argc] != NULL; ++argc)
1284 printf ("%s\n", argv[argc]);
1288 print_table (char *const *argv)
1292 for (i = 0; argv[i] != NULL; i += 2)
1293 printf ("%s: %s\n", argv[i], argv[i+1]);
1297 is_true (const char *str)
1300 STRCASENEQ (str, "0") &&
1301 STRCASENEQ (str, "f") &&
1302 STRCASENEQ (str, "false") &&
1303 STRCASENEQ (str, "n") &&
1304 STRCASENEQ (str, "no");
1307 /* Free strings from a non-NULL terminated char** */
1309 free_n_strings (char **str, size_t len)
1313 for (i = 0; i < len; i++) {
1320 parse_string_list (const char *str)
1323 size_t argv_len = 0;
1325 /* Current position pointer */
1326 const char *p = str;
1328 /* Token might be simple:
1331 * 'This is a single token'
1332 * or contain embedded single-quoted sections:
1333 * This' is a sing'l'e to'ken
1335 * The latter may seem over-complicated, but it's what a normal shell does.
1336 * Not doing it risks surprising somebody.
1338 * This outer loop is over complete tokens.
1344 /* Skip leading whitespace */
1345 p += strspn (p, " \t");
1349 /* This loop is over token 'fragments'. A token can be in multiple bits if
1350 * it contains single quotes. We also treat both sides of an escaped quote
1351 * as separate fragments because we can't just copy it: we have to remove
1354 while (*p && (!c_isblank (*p) || in_quote)) {
1355 const char *end = p;
1357 /* Check if the fragment starts with a quote */
1359 /* Toggle in_quote */
1360 in_quote = !in_quote;
1362 /* Skip the quote */
1366 /* If we're in a quote, look for an end quote */
1368 end += strcspn (end, "'");
1371 /* Otherwise, look for whitespace or a quote */
1373 end += strcspn (end, " \t'");
1376 /* Grow the token to accommodate the fragment */
1377 size_t tok_end = tok_len;
1379 char *tok_new = realloc (tok, tok_len + 1);
1380 if (NULL == tok_new) {
1382 free_n_strings (argv, argv_len);
1384 exit (EXIT_FAILURE);
1388 /* Check if we stopped on an escaped quote */
1389 if ('\'' == *end && end != p && *(end-1) == '\\') {
1390 /* Add everything before \' to the token */
1391 memcpy (&tok[tok_end], p, end - p - 1);
1394 tok[tok_len-1] = '\'';
1396 /* Already processed the quote */
1401 /* Add the whole fragment */
1402 memcpy (&tok[tok_end], p, end - p);
1408 /* We've reached the end of a token. We shouldn't still be in quotes. */
1410 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1412 free_n_strings (argv, argv_len);
1417 /* Add this token if there is one. There might not be if there was
1418 * whitespace at the end of the input string */
1420 /* Add the NULL terminator */
1421 tok[tok_len] = '\0';
1423 /* Add the argument to the argument list */
1425 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1426 if (NULL == argv_new) {
1428 free_n_strings (argv, argv_len-1);
1430 exit (EXIT_FAILURE);
1434 argv[argv_len-1] = tok;
1438 /* NULL terminate the argument list */
1440 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1441 if (NULL == argv_new) {
1443 free_n_strings (argv, argv_len-1);
1444 exit (EXIT_FAILURE);
1448 argv[argv_len-1] = NULL;
1453 #ifdef HAVE_LIBREADLINE
1454 static char histfile[1024];
1455 static int nr_history_lines = 0;
1459 initialize_readline (void)
1461 #ifdef HAVE_LIBREADLINE
1464 home = getenv ("HOME");
1466 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1468 (void) read_history (histfile);
1471 rl_readline_name = "guestfish";
1472 rl_attempted_completion_function = do_completion;
1474 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1475 * call the readline(), which happens later. Therefore, these
1476 * provide default values which can be overridden by the user if
1479 (void) rl_variable_bind ("completion-ignore-case", "on");
1484 cleanup_readline (void)
1486 #ifdef HAVE_LIBREADLINE
1489 if (histfile[0] != '\0') {
1490 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1497 #ifdef HAVE_APPEND_HISTORY
1498 (void) append_history (nr_history_lines, histfile);
1500 (void) write_history (histfile);
1506 #ifdef HAVE_LIBREADLINE
1508 add_history_line (const char *line)
1516 xwrite (int fd, const void *v_buf, size_t len)
1519 const char *buf = v_buf;
1522 r = write (fd, buf, len);
1534 /* Resolve the special "win:..." form for Windows-specific paths.
1535 * This always returns a newly allocated string which is freed by the
1536 * caller function in "cmds.c".
1539 resolve_win_path (const char *path)
1544 if (STRCASENEQLEN (path, "win:", 4)) {
1545 ret = strdup (path);
1553 /* Drop drive letter, if it's "C:". */
1554 if (STRCASEEQLEN (path, "c:", 2))
1564 ret = strdup (path);
1570 /* Blindly convert any backslashes into forward slashes. Is this good? */
1571 for (i = 0; i < strlen (ret); ++i)
1575 char *t = guestfs_case_sensitive_path (g, ret);
1582 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1583 * The caller (cmds.c) will call free_file_in after the command has
1584 * run which should clean up resources.
1586 static char *file_in_heredoc (const char *endmarker);
1587 static char *file_in_tmpfile = NULL;
1590 file_in (const char *arg)
1594 if (STREQ (arg, "-")) {
1595 ret = strdup ("/dev/stdin");
1601 else if (STRPREFIX (arg, "-<<")) {
1602 const char *endmarker = &arg[3];
1603 if (*endmarker == '\0') {
1604 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1608 ret = file_in_heredoc (endmarker);
1624 file_in_heredoc (const char *endmarker)
1626 static const char template[] = "/tmp/heredocXXXXXX";
1627 file_in_tmpfile = strdup (template);
1628 if (file_in_tmpfile == NULL) {
1633 int fd = mkstemp (file_in_tmpfile);
1639 size_t markerlen = strlen (endmarker);
1641 char buffer[BUFSIZ];
1642 int write_error = 0;
1643 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1644 /* Look for "END"<EOF> or "END\n" in input. */
1645 size_t blen = strlen (buffer);
1646 if (STREQLEN (buffer, endmarker, markerlen) &&
1647 (blen == markerlen ||
1648 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1651 if (xwrite (fd, buffer, blen) == -1) {
1652 if (!write_error) perror ("write");
1654 /* continue reading up to the end marker */
1658 /* Reached EOF of stdin without finding the end marker, which
1659 * is likely to be an error.
1661 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1662 program_name, endmarker);
1671 if (close (fd) == -1) {
1676 return file_in_tmpfile;
1679 unlink (file_in_tmpfile);
1682 free (file_in_tmpfile);
1683 file_in_tmpfile = NULL;
1688 free_file_in (char *s)
1690 if (file_in_tmpfile) {
1691 if (unlink (file_in_tmpfile) == -1)
1692 perror (file_in_tmpfile);
1693 file_in_tmpfile = NULL;
1696 /* Free the device or file name which was strdup'd in file_in().
1697 * Note it's not immediately clear, but for -<< heredocs,
1698 * s == file_in_tmpfile, so this frees up that buffer.
1703 /* Resolve the special FileOut paths ("-" or filename).
1704 * The caller (cmds.c) will call free (str) after the command has run.
1707 file_out (const char *arg)
1711 if (STREQ (arg, "-"))
1712 ret = strdup ("/dev/stdout");
1723 /* Read a passphrase ('Key') from /dev/tty with echo off.
1724 * The caller (cmds.c) will call free on the string afterwards.
1725 * Based on the code in cryptsetup file lib/utils.c.
1728 read_key (const char *param)
1731 struct termios orig, temp;
1734 /* Read and write to /dev/tty if available. */
1735 if (keys_from_stdin ||
1736 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1741 /* Print the prompt and set no echo. */
1742 int tty = isatty (fileno (infp));
1745 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1747 if (tcgetattr (fileno (infp), &orig) == -1) {
1748 perror ("tcgetattr");
1751 memcpy (&temp, &orig, sizeof temp);
1752 temp.c_lflag &= ~ECHO;
1754 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1760 len = getline (&ret, &n, infp);
1767 /* Remove the terminating \n if there is one. */
1768 if (len > 0 && ret[len-1] == '\n')
1772 /* Restore echo, close file descriptor. */
1775 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1779 fclose (infp); /* outfp == infp, so this is closed also */