1 /* guestfish - the filesystem interactive shell
2 * Copyright (C) 2009-2011 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>
48 /* Return from parse_command_line. See description below. */
49 struct parsed_command {
56 static void user_cancel (int);
57 static void set_up_terminal (void);
58 static void prepare_drives (struct drv *drv);
59 static int launch (void);
60 static void interactive (void);
61 static void shell_script (void);
62 static void script (int prompt);
63 static void cmdline (char *argv[], int optind, int argc);
64 static struct parsed_command parse_command_line (char *buf, int *exit_on_error_rtn);
65 static int parse_quoted_string (char *p);
66 static int execute_and_inline (const char *cmd, int exit_on_error);
67 static void error_cb (guestfs_h *g, void *data, const char *msg);
68 static void initialize_readline (void);
69 static void cleanup_readline (void);
70 #ifdef HAVE_LIBREADLINE
71 static void add_history_line (const char *);
74 static int override_progress_bars = -1;
76 /* Currently open libguestfs handle. */
83 int remote_control_listen = 0;
84 int remote_control_csh = 0;
85 int remote_control = 0;
87 int keys_from_stdin = 0;
89 const char *libvirt_uri = NULL;
92 int have_terminfo = 0;
93 int progress_bars = 0;
94 int is_interactive = 0;
95 const char *input_file = NULL;
98 static void __attribute__((noreturn))
101 if (status != EXIT_SUCCESS)
102 fprintf (stderr, _("Try `%s --help' for more information.\n"),
106 _("%s: guest filesystem shell\n"
107 "%s lets you edit virtual machine filesystems\n"
108 "Copyright (C) 2009-2011 Red Hat Inc.\n"
110 " %s [--options] cmd [: cmd : cmd ...]\n"
112 " -h|--cmd-help List available commands\n"
113 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
114 " -a|--add image Add image\n"
115 " -c|--connect uri Specify libvirt URI for -d option\n"
116 " --csh Make --listen csh-compatible\n"
117 " -d|--domain guest Add disks from libvirt guest\n"
118 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
119 " --echo-keys Don't turn off echo for passphrases\n"
120 " -f|--file file Read commands from file\n"
121 " --format[=raw|..] Force disk format for -a option\n"
122 " -i|--inspector Automatically mount filesystems\n"
123 " --keys-from-stdin Read passphrases from stdin\n"
124 " --listen Listen for remote commands\n"
125 " --live Connect to a live virtual machine\n"
126 " -m|--mount dev[:mnt[:opts]] Mount dev on mnt (if omitted, /)\n"
127 " -n|--no-sync Don't autosync\n"
128 " -N|--new type Create prepared disk (test1.img, ...)\n"
129 " --progress-bars Enable progress bars even when not interactive\n"
130 " --no-progress-bars Disable progress bars\n"
131 " --remote[=pid] Send commands to remote %s\n"
132 " -r|--ro Mount read-only\n"
133 " --selinux Enable SELinux support\n"
134 " -v|--verbose Verbose messages\n"
135 " -V|--version Display version and exit\n"
136 " -w|--rw Mount read-write\n"
137 " -x Echo each command before executing it\n"
139 "To examine a disk image, ISO, hard disk, filesystem etc:\n"
140 " %s [--ro|--rw] -i -a /path/to/disk.img\n"
142 " %s [--ro|--rw] -i -d name-of-libvirt-domain\n"
144 "--ro recommended to avoid any writes to the disk image. If -i option fails\n"
145 "run again without -i and use 'run' + 'list-filesystems' + 'mount' cmds.\n"
147 "For more information, see the manpage %s(1).\n"),
148 program_name, program_name, program_name,
149 program_name, program_name, program_name,
156 main (int argc, char *argv[])
158 /* Set global program name that is not polluted with libtool artifacts. */
159 set_program_name (argv[0]);
161 atexit (close_stdout);
163 setlocale (LC_ALL, "");
164 bindtextdomain (PACKAGE, LOCALEBASEDIR);
165 textdomain (PACKAGE);
171 enum { HELP_OPTION = CHAR_MAX + 1 };
173 static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
174 static const struct option long_options[] = {
175 { "add", 1, 0, 'a' },
176 { "cmd-help", 2, 0, 'h' },
177 { "connect", 1, 0, 'c' },
179 { "domain", 1, 0, 'd' },
180 { "echo-keys", 0, 0, 0 },
181 { "file", 1, 0, 'f' },
182 { "format", 2, 0, 0 },
183 { "help", 0, 0, HELP_OPTION },
184 { "inspector", 0, 0, 'i' },
185 { "keys-from-stdin", 0, 0, 0 },
186 { "listen", 0, 0, 0 },
188 { "mount", 1, 0, 'm' },
189 { "new", 1, 0, 'N' },
190 { "no-dest-paths", 0, 0, 'D' },
191 { "no-sync", 0, 0, 'n' },
192 { "progress-bars", 0, 0, 0 },
193 { "no-progress-bars", 0, 0, 0 },
194 { "remote", 2, 0, 0 },
197 { "selinux", 0, 0, 0 },
198 { "verbose", 0, 0, 'v' },
199 { "version", 0, 0, 'V' },
202 struct drv *drvs = NULL;
204 struct mp *mps = NULL;
206 char *p, *file = NULL;
207 const char *format = NULL;
211 int next_prepared_drive = 1;
213 initialize_readline ();
215 memset (&sa, 0, sizeof sa);
216 sa.sa_handler = SIG_IGN;
217 sa.sa_flags = SA_RESTART;
218 sigaction (SIGPIPE, &sa, NULL);
220 /* guestfs_create is meant to be a lightweight operation, so
221 * it's OK to do it early here.
223 g = guestfs_create ();
225 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
229 /* CAUTION: we are careful to modify argv[0] here, only after
230 * using it just above.
232 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
233 * of the original, in case it's needed below.
235 //char *real_argv0 = argv[0];
236 argv[0] = bad_cast (program_name);
239 c = getopt_long (argc, argv, options, long_options, &option_index);
243 case 0: /* options which are long only */
244 if (STREQ (long_options[option_index].name, "listen"))
245 remote_control_listen = 1;
246 else if (STREQ (long_options[option_index].name, "remote")) {
248 if (sscanf (optarg, "%d", &remote_control) != 1) {
249 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
250 program_name, optarg);
254 p = getenv ("GUESTFISH_PID");
255 if (!p || sscanf (p, "%d", &remote_control) != 1) {
256 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
257 " to the PID of the remote process\n"),
262 } else if (STREQ (long_options[option_index].name, "selinux")) {
263 guestfs_set_selinux (g, 1);
264 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
266 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
267 override_progress_bars = 1;
268 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
269 override_progress_bars = 0;
270 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
272 } else if (STREQ (long_options[option_index].name, "format")) {
273 if (!optarg || STREQ (optarg, ""))
277 } else if (STREQ (long_options[option_index].name, "csh")) {
278 remote_control_csh = 1;
279 } else if (STREQ (long_options[option_index].name, "live")) {
282 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
283 program_name, long_options[option_index].name, option_index);
301 complete_dest_paths = 0;
306 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
317 r = display_command (optarg);
318 else if (argv[optind] && argv[optind][0] != '-')
319 r = display_command (argv[optind++]);
323 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
339 if (STRCASEEQ (optarg, "list") ||
340 STRCASEEQ (optarg, "help") ||
341 STRCASEEQ (optarg, "h") ||
342 STRCASEEQ (optarg, "?")) {
343 list_prepared_drives ();
346 drv = malloc (sizeof (struct drv));
354 if (asprintf (&drv->N.filename, "test%d.img",
355 next_prepared_drive++) == -1) {
359 drv->N.data = create_prepared_file (optarg, drv->N.filename);
360 drv->N.data_free = free_prep_data;
386 usage (EXIT_SUCCESS);
389 usage (EXIT_FAILURE);
393 /* Decide here if this will be an interactive session. We have to
394 * do this as soon as possible after processing the command line
397 is_interactive = !file && isatty (0);
399 /* Register a ^C handler. We have to do this before launch could
400 * possibly be called below.
402 if (is_interactive) {
403 memset (&sa, 0, sizeof sa);
404 sa.sa_handler = user_cancel;
405 sa.sa_flags = SA_RESTART;
406 sigaction (SIGINT, &sa, NULL);
408 guestfs_set_pgroup (g, 1);
411 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
412 * previously, if we have -i without any drives but with something
413 * on the command line, it must be old-style syntax.
415 if (inspector && drvs == NULL && optind < argc) {
416 while (optind < argc) {
417 if (strchr (argv[optind], '/') ||
418 access (argv[optind], F_OK) == 0) { /* simulate -a option */
419 drv = malloc (sizeof (struct drv));
425 drv->a.filename = argv[optind];
426 drv->a.format = NULL;
429 } else { /* simulate -d option */
430 drv = malloc (sizeof (struct drv));
436 drv->d.guest = argv[optind];
445 /* If we've got drives to add, add them now. */
446 add_drives (drvs, 'a');
448 /* If we've got mountpoints or prepared drives or -i option, we must
449 * launch the guest and mount them.
451 if (next_prepared_drive > 1 || mps != NULL || inspector) {
452 /* RHBZ#612178: If --listen flag is given, then we will fork into
453 * the background in rc_listen(). However you can't do this while
454 * holding a libguestfs handle open because the recovery process
455 * will think the main program has died and kill qemu. Therefore
456 * don't use the recovery process for this case. (A better
457 * solution would be to call launch () etc after the fork, but
458 * that greatly complicates the code here).
460 if (remote_control_listen)
461 guestfs_set_recovery_proc (g, 0);
463 if (launch () == -1) exit (EXIT_FAILURE);
468 prepare_drives (drvs);
472 /* Free up data structures, no longer needed after this point. */
476 /* Remote control? */
477 if (remote_control_listen && remote_control) {
479 _("%s: cannot use --listen and --remote options at the same time\n"),
484 if (remote_control_listen) {
487 _("%s: extra parameters on the command line with --listen flag\n"),
493 _("%s: cannot use --listen and --file options at the same time\n"),
500 /* -f (file) parameter? */
503 if (open (file, O_RDONLY) == -1) {
509 /* Get the name of the input file, for error messages, and replace
510 * the default error handler.
512 if (!is_interactive) {
516 input_file = "*stdin*";
517 guestfs_set_error_handler (g, error_cb, NULL);
521 /* Decide if we display progress bars. */
523 override_progress_bars >= 0
524 ? override_progress_bars
525 : (optind >= argc && is_interactive);
528 guestfs_set_event_callback (g, progress_callback,
529 GUESTFS_EVENT_PROGRESS, 0, NULL);
531 /* Interactive, shell script, or command(s) on the command line? */
532 if (optind >= argc) {
539 cmdline (argv, optind, argc);
547 user_cancel (int sig)
550 guestfs_user_cancel (g);
553 /* The <term.h> header file which defines this has "issues". */
554 extern int tgetent (char *, const char *);
557 set_up_terminal (void)
559 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
560 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
562 char *term = getenv ("TERM");
564 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
568 int r = tgetent (NULL, term);
570 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
574 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
583 prepare_drives (struct drv *drv)
586 prepare_drives (drv->next);
587 if (drv->type == drv_N)
588 prepare_drive (drv->N.filename, drv->N.data, drv->device);
595 if (guestfs_is_config (g)) {
596 if (guestfs_launch (g) == -1)
614 #define FISH "><fs> "
616 static char *line_read = NULL;
621 #ifdef HAVE_LIBREADLINE
629 line_read = readline (prompt ? FISH : "");
631 if (line_read && *line_read)
632 add_history_line (line_read);
637 #endif /* HAVE_LIBREADLINE */
639 static char buf[8192];
642 if (prompt) printf (FISH);
643 line_read = fgets (buf, sizeof buf, stdin);
646 len = strlen (line_read);
647 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
657 int global_exit_on_error = !prompt;
659 struct parsed_command pcmd;
663 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
664 "editing virtual machine filesystems.\n"
666 "Type: 'help' for help on commands\n"
667 " 'man' to read the manual\n"
668 " 'quit' to quit the shell\n"
672 print_inspect_prompt ();
678 exit_on_error = global_exit_on_error;
680 buf = rl_gets (prompt);
688 pcmd = parse_command_line (buf, &exit_on_error);
689 if (pcmd.status == -1 && exit_on_error)
691 if (pcmd.status == 1) {
692 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
693 if (exit_on_error) exit (EXIT_FAILURE);
697 if (prompt) printf ("\n");
700 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
701 * This destructively updates 'buf'.
703 * 'exit_on_error_rtn' is used to pass in the global exit_on_error
704 * setting and to return the local setting (eg. if the command begins
707 * Returns in parsed_command.status:
708 * 1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
709 * 0 = no guestfish command, but otherwise OK
712 static struct parsed_command
713 parse_command_line (char *buf, int *exit_on_error_rtn)
715 struct parsed_command pcmd;
720 const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
722 /* Note that pcmd.pipe must be set to NULL for correct usage. Other
723 * fields do not need to be, but this silences a gcc warning.
725 memset (&pcmd, 0, sizeof pcmd);
728 /* Skip any initial whitespace before the command. */
729 while (*buf && c_isspace (*buf))
737 /* If the next character is '#' then this is a comment. */
743 /* If the next character is '!' then pass the whole lot to system(3). */
748 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
749 WEXITSTATUS (r) != 0)
756 /* If the next two characters are "<!" then pass the command to
757 * popen(3), read the result and execute it as guestfish commands.
759 if (buf[0] == '<' && buf[1] == '!') {
760 int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
768 /* If the next character is '-' allow the command to fail without
769 * exiting on error (just for this one command though).
772 *exit_on_error_rtn = 0;
777 /* Get the command (cannot be quoted). */
778 len = strcspn (buf, " \t");
787 if (buf[len] == '\0') {
795 p += strspn (p, " \t");
797 /* Get the parameters. */
798 while (*p && i < argv_len) {
801 /* Parameters which start with quotes or pipes are treated
802 * specially. Bare parameters are delimited by whitespace.
806 len = parse_quoted_string (p);
811 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
813 _("%s: command arguments not separated by whitespace\n"),
818 pend = p[len+1] ? &p[len+2] : &p[len+1];
819 } else if (*p == '\'') {
821 len = strcspn (p, "'");
822 if (p[len] == '\0') {
823 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
827 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
829 _("%s: command arguments not separated by whitespace\n"),
835 pend = p[len+1] ? &p[len+2] : &p[len+1];
836 } else if (*p == '|') {
840 } else if (*p != ' ' && *p != '\t') {
841 /* If the first character is a ~ then note that this parameter
842 * is a candidate for ~username expansion. NB this does not
843 * apply to quoted parameters.
845 tilde_candidate = *p == '~';
846 len = strcspn (p, " \t");
853 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
858 if (!tilde_candidate)
861 pcmd.argv[i] = try_tilde_expansion (p);
866 p += strspn (p, " \t");
870 fprintf (stderr, _("%s: too many arguments\n"), program_name);
885 case '0'...'9': return d - '0';
886 case 'a'...'f': return d - 'a' + 10;
887 case 'A'...'F': return d - 'A' + 10;
892 /* Parse double-quoted strings, replacing backslash escape sequences
893 * with the true character. Since the string is returned in place,
894 * the escapes must make the string shorter.
897 parse_quoted_string (char *p)
901 for (; *p && *p != '"'; p++) {
907 case 'a': *p = '\a'; break;
908 case 'b': *p = '\b'; break;
909 case 'f': *p = '\f'; break;
910 case 'n': *p = '\n'; break;
911 case 'r': *p = '\r'; break;
912 case 't': *p = '\t'; break;
913 case 'v': *p = '\v'; break;
914 case '"': *p = '"'; break;
915 case '\'': *p = '\''; break;
916 case '?': *p = '?'; break;
918 case '0'...'7': /* octal escape - always 3 digits */
920 if (p[2] >= '0' && p[2] <= '7' &&
921 p[3] >= '0' && p[3] <= '7') {
922 c = (p[1] - '0') * 0100 + (p[2] - '0') * 010 + (p[3] - '0');
923 if (c < 1 || c > 255)
931 case 'x': /* hex escape - always 2 digits */
933 if (c_isxdigit (p[2]) && c_isxdigit (p[3])) {
934 c = hexdigit (p[2]) * 0x10 + hexdigit (p[3]);
935 if (c < 1 || c > 255)
945 fprintf (stderr, _("%s: invalid escape sequence in string (starting at offset %d)\n"),
946 program_name, (int) (p - start));
949 memmove (p+1, p+1+m, strlen (p+1+m) + 1);
954 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
962 /* Used to handle "<!" (execute command and inline result). */
964 execute_and_inline (const char *cmd, int global_exit_on_error)
971 struct parsed_command pcmd;
973 pp = popen (cmd, "r");
979 while ((n = getline (&line, &len, pp)) != -1) {
980 exit_on_error = global_exit_on_error;
982 /* Chomp final line ending which parse_command_line would not expect. */
983 if (n > 0 && line[n-1] == '\n')
986 pcmd = parse_command_line (line, &exit_on_error);
987 if (pcmd.status == -1 && exit_on_error)
989 if (pcmd.status == 1) {
990 if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
991 if (exit_on_error) exit (EXIT_FAILURE);
998 if (pclose (pp) != 0) {
1007 cmdline (char *argv[], int optind, int argc)
1015 if (optind >= argc) return;
1017 cmd = argv[optind++];
1018 if (STREQ (cmd, ":")) {
1019 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
1020 exit (EXIT_FAILURE);
1023 /* Allow -cmd on the command line to mean (temporarily) override
1024 * the normal exit on error (RHBZ#578407).
1026 if (cmd[0] == '-') {
1031 params = &argv[optind];
1033 /* Search for end of command list or ":" ... */
1034 while (optind < argc && STRNEQ (argv[optind], ":"))
1037 if (optind == argc) {
1038 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1039 exit (EXIT_FAILURE);
1041 argv[optind] = NULL;
1042 if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1043 exit (EXIT_FAILURE);
1044 cmdline (argv, optind+1, argc);
1048 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
1049 * pass to the remote server (when issuing --remote commands). It
1050 * does not cause issue_command itself to exit on error.
1053 issue_command (const char *cmd, char *argv[], const char *pipecmd,
1054 int rc_exit_on_error_flag)
1057 int stdout_saved_fd = -1;
1061 reset_progress_bar ();
1063 /* This counts the commands issued, starting at 1. */
1066 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1070 if (fflush (stdout) == EOF) {
1071 perror ("failed to flush standard output");
1074 if (pipe (fd) < 0) {
1075 perror ("pipe failed");
1084 if (pid == 0) { /* Child process. */
1086 if (dup2 (fd[0], 0) < 0) {
1087 perror ("dup2 of stdin failed");
1091 r = system (pipecmd);
1096 _exit (WEXITSTATUS (r));
1099 if ((stdout_saved_fd = dup (1)) < 0) {
1100 perror ("failed to dup stdout");
1104 if (dup2 (fd[1], 1) < 0) {
1105 perror ("failed to dup stdout");
1106 close (stdout_saved_fd);
1112 for (argc = 0; argv[argc] != NULL; ++argc)
1115 /* If --remote was set, then send this command to a remote process. */
1117 r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1119 /* Otherwise execute it locally. */
1120 else if (STRCASEEQ (cmd, "help")) {
1125 r = display_command (argv[0]);
1127 else if (STRCASEEQ (cmd, "quit") ||
1128 STRCASEEQ (cmd, "exit") ||
1129 STRCASEEQ (cmd, "q")) {
1134 r = run_action (cmd, argc, argv);
1136 /* Always flush stdout after every command, so that messages, results
1137 * etc appear immediately.
1139 if (fflush (stdout) == EOF) {
1140 perror ("failed to flush standard output");
1146 if (dup2 (stdout_saved_fd, 1) < 0) {
1147 perror ("failed to dup2 standard output");
1150 close (stdout_saved_fd);
1151 if (waitpid (pid, NULL, 0) < 0) {
1152 perror ("waiting for command to complete");
1161 list_builtin_commands (void)
1163 /* help and quit should appear at the top */
1164 printf ("%-20s %s\n",
1165 "help", _("display a list of commands or help on a command"));
1166 printf ("%-20s %s\n",
1167 "quit", _("quit guestfish"));
1169 /* actions are printed after this (see list_commands) */
1173 display_builtin_command (const char *cmd)
1175 /* help for actions is auto-generated, see display_command */
1177 if (STRCASEEQ (cmd, "help")) {
1178 printf (_("help - display a list of commands or help on a command\n"
1183 else if (STRCASEEQ (cmd, "quit") ||
1184 STRCASEEQ (cmd, "exit") ||
1185 STRCASEEQ (cmd, "q")) {
1186 printf (_("quit - quit guestfish\n"
1191 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1197 /* This is printed when the user types in an unknown command for the
1198 * first command issued. A common case is the user doing:
1199 * guestfish disk.img
1200 * expecting guestfish to open 'disk.img' (in fact, this tried to
1201 * run a command 'disk.img').
1204 extended_help_message (void)
1207 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1208 "For a list of commands: guestfish -h\n"
1209 "For complete documentation: man guestfish\n"));
1212 /* Error callback. This replaces the standard libguestfs error handler. */
1214 error_cb (guestfs_h *g, void *data, const char *msg)
1216 fprintf (stderr, _("%s:%d: libguestfs: error: %s\n"),
1217 input_file, input_lineno, msg);
1221 free_strings (char **argv)
1225 for (argc = 0; argv[argc] != NULL; ++argc)
1231 count_strings (char *const *argv)
1235 for (c = 0; argv[c]; ++c)
1241 print_strings (char *const *argv)
1245 for (argc = 0; argv[argc] != NULL; ++argc)
1246 printf ("%s\n", argv[argc]);
1250 print_table (char *const *argv)
1254 for (i = 0; argv[i] != NULL; i += 2)
1255 printf ("%s: %s\n", argv[i], argv[i+1]);
1259 is_true (const char *str)
1262 STRCASENEQ (str, "0") &&
1263 STRCASENEQ (str, "f") &&
1264 STRCASENEQ (str, "false") &&
1265 STRCASENEQ (str, "n") &&
1266 STRCASENEQ (str, "no");
1269 /* Free strings from a non-NULL terminated char** */
1271 free_n_strings (char **str, size_t len)
1275 for (i = 0; i < len; i++) {
1282 parse_string_list (const char *str)
1285 size_t argv_len = 0;
1287 /* Current position pointer */
1288 const char *p = str;
1290 /* Token might be simple:
1293 * 'This is a single token'
1294 * or contain embedded single-quoted sections:
1295 * This' is a sing'l'e to'ken
1297 * The latter may seem over-complicated, but it's what a normal shell does.
1298 * Not doing it risks surprising somebody.
1300 * This outer loop is over complete tokens.
1306 /* Skip leading whitespace */
1307 p += strspn (p, " \t");
1311 /* This loop is over token 'fragments'. A token can be in multiple bits if
1312 * it contains single quotes. We also treat both sides of an escaped quote
1313 * as separate fragments because we can't just copy it: we have to remove
1316 while (*p && (!c_isblank (*p) || in_quote)) {
1317 const char *end = p;
1319 /* Check if the fragment starts with a quote */
1321 /* Toggle in_quote */
1322 in_quote = !in_quote;
1324 /* Skip the quote */
1328 /* If we're in a quote, look for an end quote */
1330 end += strcspn (end, "'");
1333 /* Otherwise, look for whitespace or a quote */
1335 end += strcspn (end, " \t'");
1338 /* Grow the token to accommodate the fragment */
1339 size_t tok_end = tok_len;
1341 char *tok_new = realloc (tok, tok_len + 1);
1342 if (NULL == tok_new) {
1344 free_n_strings (argv, argv_len);
1346 exit (EXIT_FAILURE);
1350 /* Check if we stopped on an escaped quote */
1351 if ('\'' == *end && end != p && *(end-1) == '\\') {
1352 /* Add everything before \' to the token */
1353 memcpy (&tok[tok_end], p, end - p - 1);
1356 tok[tok_len-1] = '\'';
1358 /* Already processed the quote */
1363 /* Add the whole fragment */
1364 memcpy (&tok[tok_end], p, end - p);
1370 /* We've reached the end of a token. We shouldn't still be in quotes. */
1372 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1373 free_n_strings (argv, argv_len);
1378 /* Add this token if there is one. There might not be if there was
1379 * whitespace at the end of the input string */
1381 /* Add the NULL terminator */
1382 tok[tok_len] = '\0';
1384 /* Add the argument to the argument list */
1386 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1387 if (NULL == argv_new) {
1389 free_n_strings (argv, argv_len-1);
1391 exit (EXIT_FAILURE);
1395 argv[argv_len-1] = tok;
1399 /* NULL terminate the argument list */
1401 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1402 if (NULL == argv_new) {
1404 free_n_strings (argv, argv_len-1);
1405 exit (EXIT_FAILURE);
1409 argv[argv_len-1] = NULL;
1414 #ifdef HAVE_LIBREADLINE
1415 static char histfile[1024];
1416 static int nr_history_lines = 0;
1420 initialize_readline (void)
1422 #ifdef HAVE_LIBREADLINE
1425 home = getenv ("HOME");
1427 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1429 (void) read_history (histfile);
1432 rl_readline_name = "guestfish";
1433 rl_attempted_completion_function = do_completion;
1435 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1436 * call the readline(), which happens later. Therefore, these
1437 * provide default values which can be overridden by the user if
1440 (void) rl_variable_bind ("completion-ignore-case", "on");
1445 cleanup_readline (void)
1447 #ifdef HAVE_LIBREADLINE
1450 if (histfile[0] != '\0') {
1451 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1458 #ifdef HAVE_APPEND_HISTORY
1459 (void) append_history (nr_history_lines, histfile);
1461 (void) write_history (histfile);
1468 #ifdef HAVE_LIBREADLINE
1470 add_history_line (const char *line)
1478 xwrite (int fd, const void *v_buf, size_t len)
1481 const char *buf = v_buf;
1484 r = write (fd, buf, len);
1496 /* Resolve the special "win:..." form for Windows-specific paths. The
1497 * generated code calls this for all device or path arguments.
1499 * The function returns a newly allocated string, and the caller must
1500 * free this string; else display an error and return NULL.
1502 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1505 win_prefix (const char *path)
1510 /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1511 if (STRCASENEQLEN (path, "win:", 4)) {
1512 ret = strdup (path);
1520 /* If there is a drive letter, rewrite the path. */
1521 if (c_isalpha (path[0]) && path[1] == ':') {
1522 char drive_letter = c_tolower (path[0]);
1523 /* This returns the newly allocated string. */
1524 ret = win_prefix_drive_letter (drive_letter, path + 2);
1536 ret = strdup (path);
1543 /* Blindly convert any backslashes into forward slashes. Is this good? */
1544 for (i = 0; i < strlen (ret); ++i)
1548 char *t = guestfs_case_sensitive_path (g, ret);
1556 win_prefix_drive_letter (char drive_letter, const char *path)
1558 char **roots = NULL;
1559 char **drives = NULL;
1560 char **mountpoints = NULL;
1561 char *device, *mountpoint, *ret = NULL;
1564 /* Resolve the drive letter using the drive mappings table. */
1565 roots = guestfs_inspect_get_roots (g);
1568 if (roots[0] == NULL) {
1569 fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1573 drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1574 if (drives == NULL || drives[0] == NULL) {
1575 fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1581 for (i = 0; drives[i] != NULL; i += 2) {
1582 if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1583 device = drives[i+1];
1588 if (device == NULL) {
1589 fprintf (stderr, _("%s: drive '%c:' not found. To list available drives do:\n inspect-get-drive-mappings %s\n"),
1590 program_name, drive_letter, roots[0]);
1594 /* This drive letter must be mounted somewhere (we won't do it). */
1595 mountpoints = guestfs_mountpoints (g);
1596 if (mountpoints == NULL)
1600 for (i = 0; mountpoints[i] != NULL; i += 2) {
1601 if (STREQ (mountpoints[i], device)) {
1602 mountpoint = mountpoints[i+1];
1607 if (mountpoint == NULL) {
1608 fprintf (stderr, _("%s: to access '%c:', mount %s first. One way to do this is:\n umount-all\n mount %s /\n"),
1609 program_name, drive_letter, device, device);
1613 /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1614 if (asprintf (&ret, "%s%s%s",
1615 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1616 perror ("asprintf");
1622 free_strings (roots);
1624 free_strings (drives);
1626 free_strings (mountpoints);
1631 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1632 * The caller (cmds.c) will call free_file_in after the command has
1633 * run which should clean up resources.
1635 static char *file_in_heredoc (const char *endmarker);
1636 static char *file_in_tmpfile = NULL;
1639 file_in (const char *arg)
1643 if (STREQ (arg, "-")) {
1644 ret = strdup ("/dev/stdin");
1650 else if (STRPREFIX (arg, "-<<")) {
1651 const char *endmarker = &arg[3];
1652 if (*endmarker == '\0') {
1653 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1657 ret = file_in_heredoc (endmarker);
1673 file_in_heredoc (const char *endmarker)
1675 TMP_TEMPLATE_ON_STACK (template);
1676 file_in_tmpfile = strdup (template);
1677 if (file_in_tmpfile == NULL) {
1682 int fd = mkstemp (file_in_tmpfile);
1688 size_t markerlen = strlen (endmarker);
1690 char buffer[BUFSIZ];
1691 int write_error = 0;
1692 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1693 /* Look for "END"<EOF> or "END\n" in input. */
1694 size_t blen = strlen (buffer);
1695 if (STREQLEN (buffer, endmarker, markerlen) &&
1696 (blen == markerlen ||
1697 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1700 if (xwrite (fd, buffer, blen) == -1) {
1701 if (!write_error) perror ("write");
1703 /* continue reading up to the end marker */
1707 /* Reached EOF of stdin without finding the end marker, which
1708 * is likely to be an error.
1710 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1711 program_name, endmarker);
1720 if (close (fd) == -1) {
1725 return file_in_tmpfile;
1728 unlink (file_in_tmpfile);
1731 free (file_in_tmpfile);
1732 file_in_tmpfile = NULL;
1737 free_file_in (char *s)
1739 if (file_in_tmpfile) {
1740 if (unlink (file_in_tmpfile) == -1)
1741 perror (file_in_tmpfile);
1742 file_in_tmpfile = NULL;
1745 /* Free the device or file name which was strdup'd in file_in().
1746 * Note it's not immediately clear, but for -<< heredocs,
1747 * s == file_in_tmpfile, so this frees up that buffer.
1752 /* Resolve the special FileOut paths ("-" or filename).
1753 * The caller (cmds.c) will call free (str) after the command has run.
1756 file_out (const char *arg)
1760 if (STREQ (arg, "-"))
1761 ret = strdup ("/dev/stdout");