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>
35 #ifdef HAVE_LIBREADLINE
36 #include <readline/readline.h>
37 #include <readline/history.h>
47 /* List of drives added via -a, -d or -N options. */
50 enum { drv_a, drv_d, drv_N } type;
53 char *filename; /* disk filename */
54 const char *format; /* format (NULL == autodetect) */
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 void free_drives (struct drv *drv);
78 static void free_mps (struct mp *mp);
79 static int launch (void);
80 static void interactive (void);
81 static void shell_script (void);
82 static void script (int prompt);
83 static void cmdline (char *argv[], int optind, int argc);
84 static void initialize_readline (void);
85 static void cleanup_readline (void);
86 #ifdef HAVE_LIBREADLINE
87 static void add_history_line (const char *);
90 static int override_progress_bars = -1;
92 /* Currently open libguestfs handle. */
98 int remote_control_listen = 0;
99 int remote_control = 0;
100 int exit_on_error = 1;
102 int keys_from_stdin = 0;
104 const char *libvirt_uri = NULL;
107 int have_terminfo = 0;
108 int progress_bars = 0;
110 static void __attribute__((noreturn))
113 if (status != EXIT_SUCCESS)
114 fprintf (stderr, _("Try `%s --help' for more information.\n"),
118 _("%s: guest filesystem shell\n"
119 "%s lets you edit virtual machine filesystems\n"
120 "Copyright (C) 2009-2010 Red Hat Inc.\n"
122 " %s [--options] cmd [: cmd : cmd ...]\n"
123 " %s [--ro] -i -a disk-image\n"
124 " %s [--ro] -i -d libvirt-domain\n"
125 "or for interactive use:\n"
127 "or from a shell script:\n"
133 " -h|--cmd-help List available commands\n"
134 " -h|--cmd-help cmd Display detailed help on 'cmd'\n"
135 " -a|--add image Add image\n"
136 " -c|--connect uri Specify libvirt URI for -d option\n"
137 " -d|--domain guest Add disks from libvirt guest\n"
138 " -D|--no-dest-paths Don't tab-complete paths from guest fs\n"
139 " --echo-keys Don't turn off echo for passphrases\n"
140 " -f|--file file Read commands from file\n"
141 " --format[=raw|..] Force disk format for -a option\n"
142 " -i|--inspector Automatically mount filesystems\n"
143 " --keys-from-stdin Read passphrases from stdin\n"
144 " --listen Listen for remote commands\n"
145 " -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
146 " -n|--no-sync Don't autosync\n"
147 " -N|--new type Create prepared disk (test1.img, ...)\n"
148 " --progress-bars Enable progress bars even when not interactive\n"
149 " --no-progress-bars Disable progress bars\n"
150 " --remote[=pid] Send commands to remote %s\n"
151 " -r|--ro Mount read-only\n"
152 " --selinux Enable SELinux support\n"
153 " -v|--verbose Verbose messages\n"
154 " -x Echo each command before executing it\n"
155 " -V|--version Display version and exit\n"
156 "For more information, see the manpage %s(1).\n"),
157 program_name, program_name, program_name,
158 program_name, program_name, program_name,
159 program_name, program_name, program_name);
165 main (int argc, char *argv[])
167 /* Set global program name that is not polluted with libtool artifacts. */
168 set_program_name (argv[0]);
170 atexit (close_stdout);
172 setlocale (LC_ALL, "");
173 bindtextdomain (PACKAGE, LOCALEBASEDIR);
174 textdomain (PACKAGE);
178 enum { HELP_OPTION = CHAR_MAX + 1 };
180 static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
181 static const struct option long_options[] = {
182 { "add", 1, 0, 'a' },
183 { "cmd-help", 2, 0, 'h' },
184 { "connect", 1, 0, 'c' },
185 { "domain", 1, 0, 'd' },
186 { "echo-keys", 0, 0, 0 },
187 { "file", 1, 0, 'f' },
188 { "format", 2, 0, 0 },
189 { "help", 0, 0, HELP_OPTION },
190 { "inspector", 0, 0, 'i' },
191 { "keys-from-stdin", 0, 0, 0 },
192 { "listen", 0, 0, 0 },
193 { "mount", 1, 0, 'm' },
194 { "new", 1, 0, 'N' },
195 { "no-dest-paths", 0, 0, 'D' },
196 { "no-sync", 0, 0, 'n' },
197 { "progress-bars", 0, 0, 0 },
198 { "no-progress-bars", 0, 0, 0 },
199 { "remote", 2, 0, 0 },
201 { "selinux", 0, 0, 0 },
202 { "verbose", 0, 0, 'v' },
203 { "version", 0, 0, 'V' },
206 struct drv *drvs = NULL;
208 struct mp *mps = NULL;
210 char *p, *file = NULL;
211 const char *format = NULL;
215 int next_prepared_drive = 1;
217 initialize_readline ();
219 memset (&sa, 0, sizeof sa);
220 sa.sa_handler = SIG_IGN;
221 sa.sa_flags = SA_RESTART;
222 sigaction (SIGPIPE, &sa, NULL);
224 /* guestfs_create is meant to be a lightweight operation, so
225 * it's OK to do it early here.
227 g = guestfs_create ();
229 fprintf (stderr, _("guestfs_create: failed to create handle\n"));
233 guestfs_set_autosync (g, 1);
235 /* If developing, add ./appliance to the path. Note that libtools
236 * interferes with this because uninstalled guestfish is a shell
237 * script that runs the real program with an absolute path. Detect
240 * BUT if LIBGUESTFS_PATH environment variable is already set by
241 * the user, then don't override it.
243 if (getenv ("LIBGUESTFS_PATH") == NULL &&
245 (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
246 guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
248 /* CAUTION: we are careful to modify argv[0] here, only after
249 * using it just above.
251 * getopt_long uses argv[0], so give it the sanitized name. Save a copy
252 * of the original, in case it's needed below.
254 char *real_argv0 = argv[0];
255 argv[0] = bad_cast (program_name);
258 c = getopt_long (argc, argv, options, long_options, &option_index);
262 case 0: /* options which are long only */
263 if (STREQ (long_options[option_index].name, "listen"))
264 remote_control_listen = 1;
265 else if (STREQ (long_options[option_index].name, "remote")) {
267 if (sscanf (optarg, "%d", &remote_control) != 1) {
268 fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
269 program_name, optarg);
273 p = getenv ("GUESTFISH_PID");
274 if (!p || sscanf (p, "%d", &remote_control) != 1) {
275 fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
276 " to the PID of the remote process\n"),
281 } else if (STREQ (long_options[option_index].name, "selinux")) {
282 guestfs_set_selinux (g, 1);
283 } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
285 } else if (STREQ (long_options[option_index].name, "progress-bars")) {
286 override_progress_bars = 1;
287 } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
288 override_progress_bars = 0;
289 } else if (STREQ (long_options[option_index].name, "echo-keys")) {
291 } else if (STREQ (long_options[option_index].name, "format")) {
292 if (!optarg || STREQ (optarg, ""))
297 fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
298 program_name, long_options[option_index].name, option_index);
304 if (access (optarg, R_OK) != 0) {
308 drv = malloc (sizeof (struct drv));
314 drv->a.filename = optarg;
315 drv->a.format = format;
321 libvirt_uri = optarg;
325 drv = malloc (sizeof (struct drv));
331 drv->d.guest = optarg;
337 if (STRCASEEQ (optarg, "list") ||
338 STRCASEEQ (optarg, "help") ||
339 STRCASEEQ (optarg, "h") ||
340 STRCASEEQ (optarg, "?")) {
341 list_prepared_drives ();
344 drv = malloc (sizeof (struct drv));
350 if (asprintf (&drv->N.filename, "test%d.img",
351 next_prepared_drive++) == -1) {
355 drv->N.data = create_prepared_file (optarg, drv->N.filename);
356 drv->N.device = NULL; /* filled in by add_drives */
362 complete_dest_paths = 0;
367 fprintf (stderr, _("%s: only one -f parameter can be given\n"),
378 r = display_command (optarg);
379 else if (argv[optind] && argv[optind][0] != '-')
380 r = display_command (argv[optind++]);
384 exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
392 mp = malloc (sizeof (struct mp));
397 p = strchr (optarg, ':');
400 mp->mountpoint = p+1;
402 mp->mountpoint = bad_cast ("/");
409 guestfs_set_autosync (g, 0);
418 guestfs_set_verbose (g, verbose);
422 struct guestfs_version *v = guestfs_version (g);
423 printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
424 v->major, v->minor, v->release, v->extra);
429 guestfs_set_trace (g, 1);
433 usage (EXIT_SUCCESS);
436 usage (EXIT_FAILURE);
440 /* Old-style -i syntax? Since -a/-d/-N and -i was disallowed
441 * previously, if we have -i without any drives but with something
442 * on the command line, it must be old-style syntax.
444 if (inspector && drvs == NULL && optind < argc) {
445 while (optind < argc) {
446 if (strchr (argv[optind], '/') ||
447 access (argv[optind], F_OK) == 0) { /* simulate -a option */
448 drv = malloc (sizeof (struct drv));
454 drv->a.filename = argv[optind];
455 drv->a.format = NULL;
458 } else { /* simulate -d option */
459 drv = malloc (sizeof (struct drv));
465 drv->d.guest = argv[optind];
474 /* If we've got drives to add, add them now. */
475 add_drives (drvs, 'a');
477 /* If we've got mountpoints or prepared drives or -i option, we must
478 * launch the guest and mount them.
480 if (next_prepared_drive > 1 || mps != NULL || inspector) {
481 /* RHBZ#612178: If --listen flag is given, then we will fork into
482 * the background in rc_listen(). However you can't do this while
483 * holding a libguestfs handle open because the recovery process
484 * will think the main program has died and kill qemu. Therefore
485 * don't use the recovery process for this case. (A better
486 * solution would be to call launch () etc after the fork, but
487 * that greatly complicates the code here).
489 if (remote_control_listen)
490 guestfs_set_recovery_proc (g, 0);
492 if (launch () == -1) exit (EXIT_FAILURE);
497 prepare_drives (drvs);
501 /* Free up data structures, no longer needed after this point. */
505 /* Remote control? */
506 if (remote_control_listen && remote_control) {
508 _("%s: cannot use --listen and --remote options at the same time\n"),
513 if (remote_control_listen) {
516 _("%s: extra parameters on the command line with --listen flag\n"),
522 _("%s: cannot use --listen and --file options at the same time\n"),
529 /* -f (file) parameter? */
532 if (open (file, O_RDONLY) == -1) {
538 /* Decide if we display progress bars. */
540 override_progress_bars >= 0
541 ? override_progress_bars
542 : (optind >= argc && isatty (0));
545 guestfs_set_progress_callback (g, progress_callback, NULL);
547 /* Interactive, shell script, or command(s) on the command line? */
548 if (optind >= argc) {
555 cmdline (argv, optind, argc);
562 /* The <term.h> header file which defines this has "issues". */
563 extern int tgetent (char *, const char *);
566 set_up_terminal (void)
568 /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
569 utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
571 char *term = getenv ("TERM");
573 //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
577 int r = tgetent (NULL, term);
579 fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
583 fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
592 pod2text (const char *name, const char *shortdesc, const char *str)
596 fp = popen ("pod2text", "w");
598 /* pod2text failed, maybe not found, so let's just print the
599 * source instead, since that's better than doing nothing.
601 printf ("%s - %s\n\n%s\n", name, shortdesc, str);
604 fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
609 /* List is built in reverse order, so mount them in reverse order. */
611 mount_mps (struct mp *mp)
616 mount_mps (mp->next);
618 /* Don't use guestfs_mount here because that will default to mount
619 * options -o sync,noatime. For more information, see guestfs(3)
620 * section "LIBGUESTFS GOTCHAS".
622 const char *options = read_only ? "ro" : "";
623 r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
625 /* Display possible mountpoints before exiting. */
626 char **fses = guestfs_list_filesystems (g);
627 if (fses == NULL || fses[0] == NULL)
630 _("guestfish: '%s' could not be mounted. Did you mean one of these?\n"),
633 for (i = 0; fses[i] != NULL; i += 2)
634 fprintf (stderr, "\t%s (%s)\n", fses[i], fses[i+1]);
643 add_drives (struct drv *drv, char next_drive)
646 struct guestfs_add_drive_opts_argv ad_optargs;
648 if (next_drive > 'z') {
650 _("guestfish: too many drives added on the command line\n"));
655 next_drive = add_drives (drv->next, next_drive);
659 ad_optargs.bitmask = 0;
661 ad_optargs.bitmask |= GUESTFS_ADD_DRIVE_OPTS_READONLY_BITMASK;
662 ad_optargs.readonly = 1;
665 ad_optargs.bitmask |= GUESTFS_ADD_DRIVE_OPTS_FORMAT_BITMASK;
666 ad_optargs.format = drv->a.format;
668 r = guestfs_add_drive_opts_argv (g, drv->a.filename, &ad_optargs);
676 r = add_libvirt_drives (drv->d.guest);
684 /* guestfs_add_drive (ie. autodetecting) should be safe here
685 * since we have just created the prepared disk. At the moment
686 * it will always be "raw" but in a theoretical future we might
687 * create other formats.
689 /* -N option is not affected by --ro */
690 r = guestfs_add_drive (g, drv->N.filename);
694 if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
702 default: /* keep GCC happy */
711 prepare_drives (struct drv *drv)
714 prepare_drives (drv->next);
715 if (drv->type == drv_N)
716 prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
721 free_drives (struct drv *drv)
724 free_drives (drv->next);
727 case drv_a: /* a.filename and a.format are optargs, don't free them */ break;
728 case drv_d: /* d.filename is optarg, don't free it */ break;
730 free (drv->N.filename);
731 free (drv->N.device);
732 free_prep_data (drv->N.data);
734 default: ; /* keep GCC happy */
740 free_mps (struct mp *mp)
745 /* The drive and mountpoint fields are not allocated
746 * from the heap, so we should not free them here.
755 if (guestfs_is_config (g)) {
756 if (guestfs_launch (g) == -1)
774 #define FISH "><fs> "
776 static char *line_read = NULL;
781 #ifdef HAVE_LIBREADLINE
789 line_read = readline (prompt ? FISH : "");
791 if (line_read && *line_read)
792 add_history_line (line_read);
797 #endif /* HAVE_LIBREADLINE */
799 static char buf[8192];
802 if (prompt) printf (FISH);
803 line_read = fgets (buf, sizeof buf, stdin);
806 len = strlen (line_read);
807 if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
821 int global_exit_on_error = !prompt;
826 "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
827 "editing virtual machine filesystems.\n"
829 "Type: 'help' for a list of commands\n"
830 " 'man' to read the manual\n"
831 " 'quit' to quit the shell\n"
835 print_inspect_prompt ();
843 exit_on_error = global_exit_on_error;
845 buf = rl_gets (prompt);
851 /* Skip any initial whitespace before the command. */
853 while (*buf && c_isspace (*buf))
858 /* If the next character is '#' then this is a comment. */
859 if (*buf == '#') continue;
861 /* If the next character is '!' then pass the whole lot to system(3). */
869 (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
870 WEXITSTATUS (r) != 0)
876 /* If the next character is '-' allow the command to fail without
877 * exiting on error (just for this one command though).
885 /* Get the command (cannot be quoted). */
886 len = strcspn (buf, " \t");
888 if (len == 0) continue;
892 if (buf[len] == '\0') {
899 p += strspn (p, " \t");
901 /* Get the parameters. */
902 while (*p && i < sizeof argv / sizeof argv[0]) {
905 /* Parameters which start with quotes or pipes are treated
906 * specially. Bare parameters are delimited by whitespace.
910 len = strcspn (p, "\"");
911 if (p[len] == '\0') {
912 fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
913 if (exit_on_error) exit (EXIT_FAILURE);
916 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
918 _("%s: command arguments not separated by whitespace\n"),
920 if (exit_on_error) exit (EXIT_FAILURE);
924 pend = p[len+1] ? &p[len+2] : &p[len+1];
925 } else if (*p == '\'') {
927 len = strcspn (p, "'");
928 if (p[len] == '\0') {
929 fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
930 if (exit_on_error) exit (EXIT_FAILURE);
933 if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
935 _("%s: command arguments not separated by whitespace\n"),
937 if (exit_on_error) exit (EXIT_FAILURE);
941 pend = p[len+1] ? &p[len+2] : &p[len+1];
942 } else if (*p == '|') {
947 } else if (*p == '[') {
951 while (*pend && c != 0) {
952 if (*pend == '[') c++;
953 else if (*pend == ']') c--;
958 _("%s: unterminated \"[...]\" sequence\n"), program_name);
959 if (exit_on_error) exit (EXIT_FAILURE);
962 if (*pend && (*pend != ' ' && *pend != '\t')) {
964 _("%s: command arguments not separated by whitespace\n"),
966 if (exit_on_error) exit (EXIT_FAILURE);
971 } else if (*p != ' ' && *p != '\t') {
972 /* If the first character is a ~ then note that this parameter
973 * is a candidate for ~username expansion. NB this does not
974 * apply to quoted parameters.
976 tilde_candidate = *p == '~';
977 len = strcspn (p, " \t");
984 fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
989 if (!tilde_candidate)
992 argv[i] = try_tilde_expansion (p);
997 p += strspn (p, " \t");
1000 if (i == sizeof argv / sizeof argv[0]) {
1001 fprintf (stderr, _("%s: too many arguments\n"), program_name);
1002 if (exit_on_error) exit (EXIT_FAILURE);
1009 if (issue_command (cmd, argv, pipe) == -1) {
1010 if (exit_on_error) exit (EXIT_FAILURE);
1015 if (prompt) printf ("\n");
1019 cmdline (char *argv[], int optind, int argc)
1026 if (optind >= argc) return;
1028 cmd = argv[optind++];
1029 if (STREQ (cmd, ":")) {
1030 fprintf (stderr, _("%s: empty command on command line\n"), program_name);
1031 exit (EXIT_FAILURE);
1034 /* Allow -cmd on the command line to mean (temporarily) override
1035 * the normal exit on error (RHBZ#578407).
1037 if (cmd[0] == '-') {
1042 params = &argv[optind];
1044 /* Search for end of command list or ":" ... */
1045 while (optind < argc && STRNEQ (argv[optind], ":"))
1048 if (optind == argc) {
1049 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
1050 exit (EXIT_FAILURE);
1052 argv[optind] = NULL;
1053 if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
1054 exit (EXIT_FAILURE);
1055 cmdline (argv, optind+1, argc);
1060 issue_command (const char *cmd, char *argv[], const char *pipecmd)
1063 int stdout_saved_fd = -1;
1067 reset_progress_bar ();
1069 /* This counts the commands issued, starting at 1. */
1072 /* For | ... commands. Annoyingly we can't use popen(3) here. */
1076 if (fflush (stdout) == EOF) {
1077 perror ("failed to flush standard output");
1080 if (pipe (fd) < 0) {
1081 perror ("pipe failed");
1090 if (pid == 0) { /* Child process. */
1092 if (dup2 (fd[0], 0) < 0) {
1093 perror ("dup2 of stdin failed");
1097 r = system (pipecmd);
1102 _exit (WEXITSTATUS (r));
1105 if ((stdout_saved_fd = dup (1)) < 0) {
1106 perror ("failed to dup stdout");
1110 if (dup2 (fd[1], 1) < 0) {
1111 perror ("failed to dup stdout");
1112 close (stdout_saved_fd);
1118 for (argc = 0; argv[argc] != NULL; ++argc)
1121 /* If --remote was set, then send this command to a remote process. */
1123 r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
1125 /* Otherwise execute it locally. */
1126 else if (STRCASEEQ (cmd, "help")) {
1131 r = display_command (argv[0]);
1133 else if (STRCASEEQ (cmd, "quit") ||
1134 STRCASEEQ (cmd, "exit") ||
1135 STRCASEEQ (cmd, "q")) {
1140 r = run_action (cmd, argc, argv);
1142 /* Always flush stdout after every command, so that messages, results
1143 * etc appear immediately.
1145 if (fflush (stdout) == EOF) {
1146 perror ("failed to flush standard output");
1152 if (dup2 (stdout_saved_fd, 1) < 0) {
1153 perror ("failed to dup2 standard output");
1156 close (stdout_saved_fd);
1157 if (waitpid (pid, NULL, 0) < 0) {
1158 perror ("waiting for command to complete");
1167 list_builtin_commands (void)
1169 /* help and quit should appear at the top */
1170 printf ("%-20s %s\n",
1171 "help", _("display a list of commands or help on a command"));
1172 printf ("%-20s %s\n",
1173 "quit", _("quit guestfish"));
1175 /* actions are printed after this (see list_commands) */
1179 display_builtin_command (const char *cmd)
1181 /* help for actions is auto-generated, see display_command */
1183 if (STRCASEEQ (cmd, "help")) {
1184 printf (_("help - display a list of commands or help on a command\n"
1189 else if (STRCASEEQ (cmd, "quit") ||
1190 STRCASEEQ (cmd, "exit") ||
1191 STRCASEEQ (cmd, "q")) {
1192 printf (_("quit - quit guestfish\n"
1197 fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1203 /* This is printed when the user types in an unknown command for the
1204 * first command issued. A common case is the user doing:
1205 * guestfish disk.img
1206 * expecting guestfish to open 'disk.img' (in fact, this tried to
1207 * run a command 'disk.img').
1210 extended_help_message (void)
1213 _("Did you mean to open a disk image? guestfish -a disk.img\n"
1214 "For a list of commands: guestfish -h\n"
1215 "For complete documentation: man guestfish\n"));
1219 free_strings (char **argv)
1223 for (argc = 0; argv[argc] != NULL; ++argc)
1229 count_strings (char *const *argv)
1233 for (c = 0; argv[c]; ++c)
1239 print_strings (char *const *argv)
1243 for (argc = 0; argv[argc] != NULL; ++argc)
1244 printf ("%s\n", argv[argc]);
1248 print_table (char *const *argv)
1252 for (i = 0; argv[i] != NULL; i += 2)
1253 printf ("%s: %s\n", argv[i], argv[i+1]);
1257 is_true (const char *str)
1260 STRCASENEQ (str, "0") &&
1261 STRCASENEQ (str, "f") &&
1262 STRCASENEQ (str, "false") &&
1263 STRCASENEQ (str, "n") &&
1264 STRCASENEQ (str, "no");
1267 /* Free strings from a non-NULL terminated char** */
1269 free_n_strings (char **str, size_t len)
1273 for (i = 0; i < len; i++) {
1280 parse_string_list (const char *str)
1283 size_t argv_len = 0;
1285 /* Current position pointer */
1286 const char *p = str;
1288 /* Token might be simple:
1291 * 'This is a single token'
1292 * or contain embedded single-quoted sections:
1293 * This' is a sing'l'e to'ken
1295 * The latter may seem over-complicated, but it's what a normal shell does.
1296 * Not doing it risks surprising somebody.
1298 * This outer loop is over complete tokens.
1304 /* Skip leading whitespace */
1305 p += strspn (p, " \t");
1309 /* This loop is over token 'fragments'. A token can be in multiple bits if
1310 * it contains single quotes. We also treat both sides of an escaped quote
1311 * as separate fragments because we can't just copy it: we have to remove
1314 while (*p && (!c_isblank (*p) || in_quote)) {
1315 const char *end = p;
1317 /* Check if the fragment starts with a quote */
1319 /* Toggle in_quote */
1320 in_quote = !in_quote;
1322 /* Skip the quote */
1326 /* If we're in a quote, look for an end quote */
1328 end += strcspn (end, "'");
1331 /* Otherwise, look for whitespace or a quote */
1333 end += strcspn (end, " \t'");
1336 /* Grow the token to accommodate the fragment */
1337 size_t tok_end = tok_len;
1339 char *tok_new = realloc (tok, tok_len + 1);
1340 if (NULL == tok_new) {
1342 free_n_strings (argv, argv_len);
1344 exit (EXIT_FAILURE);
1348 /* Check if we stopped on an escaped quote */
1349 if ('\'' == *end && end != p && *(end-1) == '\\') {
1350 /* Add everything before \' to the token */
1351 memcpy (&tok[tok_end], p, end - p - 1);
1354 tok[tok_len-1] = '\'';
1356 /* Already processed the quote */
1361 /* Add the whole fragment */
1362 memcpy (&tok[tok_end], p, end - p);
1368 /* We've reached the end of a token. We shouldn't still be in quotes. */
1370 fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1372 free_n_strings (argv, argv_len);
1377 /* Add this token if there is one. There might not be if there was
1378 * whitespace at the end of the input string */
1380 /* Add the NULL terminator */
1381 tok[tok_len] = '\0';
1383 /* Add the argument to the argument list */
1385 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1386 if (NULL == argv_new) {
1388 free_n_strings (argv, argv_len-1);
1390 exit (EXIT_FAILURE);
1394 argv[argv_len-1] = tok;
1398 /* NULL terminate the argument list */
1400 char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1401 if (NULL == argv_new) {
1403 free_n_strings (argv, argv_len-1);
1404 exit (EXIT_FAILURE);
1408 argv[argv_len-1] = NULL;
1413 #ifdef HAVE_LIBREADLINE
1414 static char histfile[1024];
1415 static int nr_history_lines = 0;
1419 initialize_readline (void)
1421 #ifdef HAVE_LIBREADLINE
1424 home = getenv ("HOME");
1426 snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1428 (void) read_history (histfile);
1431 rl_readline_name = "guestfish";
1432 rl_attempted_completion_function = do_completion;
1434 /* Note that .inputrc (or /etc/inputrc) is not read until the first
1435 * call the readline(), which happens later. Therefore, these
1436 * provide default values which can be overridden by the user if
1439 (void) rl_variable_bind ("completion-ignore-case", "on");
1444 cleanup_readline (void)
1446 #ifdef HAVE_LIBREADLINE
1449 if (histfile[0] != '\0') {
1450 fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1457 #ifdef HAVE_APPEND_HISTORY
1458 (void) append_history (nr_history_lines, histfile);
1460 (void) write_history (histfile);
1467 #ifdef HAVE_LIBREADLINE
1469 add_history_line (const char *line)
1477 xwrite (int fd, const void *v_buf, size_t len)
1480 const char *buf = v_buf;
1483 r = write (fd, buf, len);
1495 /* Resolve the special "win:..." form for Windows-specific paths.
1496 * This always returns a newly allocated string which is freed by the
1497 * caller function in "cmds.c".
1500 resolve_win_path (const char *path)
1505 if (STRCASENEQLEN (path, "win:", 4)) {
1506 ret = strdup (path);
1514 /* Drop drive letter, if it's "C:". */
1515 if (STRCASEEQLEN (path, "c:", 2))
1525 ret = strdup (path);
1531 /* Blindly convert any backslashes into forward slashes. Is this good? */
1532 for (i = 0; i < strlen (ret); ++i)
1536 char *t = guestfs_case_sensitive_path (g, ret);
1543 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1544 * The caller (cmds.c) will call free_file_in after the command has
1545 * run which should clean up resources.
1547 static char *file_in_heredoc (const char *endmarker);
1548 static char *file_in_tmpfile = NULL;
1551 file_in (const char *arg)
1555 if (STREQ (arg, "-")) {
1556 ret = strdup ("/dev/stdin");
1562 else if (STRPREFIX (arg, "-<<")) {
1563 const char *endmarker = &arg[3];
1564 if (*endmarker == '\0') {
1565 fprintf (stderr, "%s: missing end marker in -<< expression\n",
1569 ret = file_in_heredoc (endmarker);
1585 file_in_heredoc (const char *endmarker)
1587 TMP_TEMPLATE_ON_STACK (template);
1588 file_in_tmpfile = strdup (template);
1589 if (file_in_tmpfile == NULL) {
1594 int fd = mkstemp (file_in_tmpfile);
1600 size_t markerlen = strlen (endmarker);
1602 char buffer[BUFSIZ];
1603 int write_error = 0;
1604 while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1605 /* Look for "END"<EOF> or "END\n" in input. */
1606 size_t blen = strlen (buffer);
1607 if (STREQLEN (buffer, endmarker, markerlen) &&
1608 (blen == markerlen ||
1609 (blen == markerlen+1 && buffer[markerlen] == '\n')))
1612 if (xwrite (fd, buffer, blen) == -1) {
1613 if (!write_error) perror ("write");
1615 /* continue reading up to the end marker */
1619 /* Reached EOF of stdin without finding the end marker, which
1620 * is likely to be an error.
1622 fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1623 program_name, endmarker);
1632 if (close (fd) == -1) {
1637 return file_in_tmpfile;
1640 unlink (file_in_tmpfile);
1643 free (file_in_tmpfile);
1644 file_in_tmpfile = NULL;
1649 free_file_in (char *s)
1651 if (file_in_tmpfile) {
1652 if (unlink (file_in_tmpfile) == -1)
1653 perror (file_in_tmpfile);
1654 file_in_tmpfile = NULL;
1657 /* Free the device or file name which was strdup'd in file_in().
1658 * Note it's not immediately clear, but for -<< heredocs,
1659 * s == file_in_tmpfile, so this frees up that buffer.
1664 /* Resolve the special FileOut paths ("-" or filename).
1665 * The caller (cmds.c) will call free (str) after the command has run.
1668 file_out (const char *arg)
1672 if (STREQ (arg, "-"))
1673 ret = strdup ("/dev/stdout");
1684 /* Read a passphrase ('Key') from /dev/tty with echo off.
1685 * The caller (cmds.c) will call free on the string afterwards.
1686 * Based on the code in cryptsetup file lib/utils.c.
1689 read_key (const char *param)
1692 struct termios orig, temp;
1695 /* Read and write to /dev/tty if available. */
1696 if (keys_from_stdin ||
1697 (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1702 /* Print the prompt and set no echo. */
1703 int tty = isatty (fileno (infp));
1706 fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1709 if (tcgetattr (fileno (infp), &orig) == -1) {
1710 perror ("tcgetattr");
1713 memcpy (&temp, &orig, sizeof temp);
1714 temp.c_lflag &= ~ECHO;
1716 tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1723 len = getline (&ret, &n, infp);
1730 /* Remove the terminating \n if there is one. */
1731 if (len > 0 && ret[len-1] == '\n')
1735 /* Restore echo, close file descriptor. */
1738 tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1742 fclose (infp); /* outfp == infp, so this is closed also */