Update FSF address.
[libguestfs.git] / fish / fish.c
1 /* guestfish - the filesystem interactive shell
2  * Copyright (C) 2009-2011 Red Hat Inc.
3  *
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.
8  *
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.
13  *
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <inttypes.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <getopt.h>
28 #include <signal.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <locale.h>
32 #include <langinfo.h>
33
34 #ifdef HAVE_LIBREADLINE
35 #include <readline/readline.h>
36 #include <readline/history.h>
37 #endif
38
39 #include <guestfs.h>
40
41 #include "fish.h"
42 #include "options.h"
43 #include "progress.h"
44
45 #include "c-ctype.h"
46 #include "closeout.h"
47 #include "progname.h"
48
49 /* Return from parse_command_line.  See description below. */
50 struct parsed_command {
51   int status;
52   char *pipe;
53   char *cmd;
54   char *argv[64];
55 };
56
57 static void user_cancel (int);
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 *);
72 #endif
73
74 static int override_progress_bars = -1;
75 static struct progress_bar *bar = NULL;
76
77 /* Currently open libguestfs handle. */
78 guestfs_h *g = NULL;
79
80 int read_only = 0;
81 int live = 0;
82 int quit = 0;
83 int verbose = 0;
84 int remote_control_listen = 0;
85 int remote_control_csh = 0;
86 int remote_control = 0;
87 int command_num = 0;
88 int keys_from_stdin = 0;
89 int echo_keys = 0;
90 const char *libvirt_uri = NULL;
91 int inspector = 0;
92 int progress_bars = 0;
93 int is_interactive = 0;
94 const char *input_file = NULL;
95 int input_lineno = 0;
96
97 static void __attribute__((noreturn))
98 usage (int status)
99 {
100   if (status != EXIT_SUCCESS)
101     fprintf (stderr, _("Try `%s --help' for more information.\n"),
102              program_name);
103   else {
104     fprintf (stdout,
105            _("%s: guest filesystem shell\n"
106              "%s lets you edit virtual machine filesystems\n"
107              "Copyright (C) 2009-2011 Red Hat Inc.\n"
108              "Usage:\n"
109              "  %s [--options] cmd [: cmd : cmd ...]\n"
110              "Options:\n"
111              "  -h|--cmd-help        List available commands\n"
112              "  -h|--cmd-help cmd    Display detailed help on 'cmd'\n"
113              "  -a|--add image       Add image\n"
114              "  -c|--connect uri     Specify libvirt URI for -d option\n"
115              "  --csh                Make --listen csh-compatible\n"
116              "  -d|--domain guest    Add disks from libvirt guest\n"
117              "  -D|--no-dest-paths   Don't tab-complete paths from guest fs\n"
118              "  --echo-keys          Don't turn off echo for passphrases\n"
119              "  -f|--file file       Read commands from file\n"
120              "  --format[=raw|..]    Force disk format for -a option\n"
121              "  -i|--inspector       Automatically mount filesystems\n"
122              "  --keys-from-stdin    Read passphrases from stdin\n"
123              "  --listen             Listen for remote commands\n"
124              "  --live               Connect to a live virtual machine\n"
125              "  -m|--mount dev[:mnt[:opts]] Mount dev on mnt (if omitted, /)\n"
126              "  -n|--no-sync         Don't autosync\n"
127              "  -N|--new type        Create prepared disk (test1.img, ...)\n"
128              "  --progress-bars      Enable progress bars even when not interactive\n"
129              "  --no-progress-bars   Disable progress bars\n"
130              "  --remote[=pid]       Send commands to remote %s\n"
131              "  -r|--ro              Mount read-only\n"
132              "  --selinux            Enable SELinux support\n"
133              "  -v|--verbose         Verbose messages\n"
134              "  -V|--version         Display version and exit\n"
135              "  -w|--rw              Mount read-write\n"
136              "  -x                   Echo each command before executing it\n"
137              "\n"
138              "To examine a disk image, ISO, hard disk, filesystem etc:\n"
139              "  %s [--ro|--rw] -i -a /path/to/disk.img\n"
140              "or\n"
141              "  %s [--ro|--rw] -i -d name-of-libvirt-domain\n"
142              "\n"
143              "--ro recommended to avoid any writes to the disk image.  If -i option fails\n"
144              "run again without -i and use 'run' + 'list-filesystems' + 'mount' cmds.\n"
145              "\n"
146              "For more information, see the manpage %s(1).\n"),
147              program_name, program_name, program_name,
148              program_name, program_name, program_name,
149              program_name);
150   }
151   exit (status);
152 }
153
154 int
155 main (int argc, char *argv[])
156 {
157   /* Set global program name that is not polluted with libtool artifacts.  */
158   set_program_name (argv[0]);
159
160   atexit (close_stdout);
161
162   setlocale (LC_ALL, "");
163   bindtextdomain (PACKAGE, LOCALEBASEDIR);
164   textdomain (PACKAGE);
165
166   parse_config ();
167
168   enum { HELP_OPTION = CHAR_MAX + 1 };
169
170   static const char *options = "a:c:d:Df:h::im:nN:rv?Vwx";
171   static const struct option long_options[] = {
172     { "add", 1, 0, 'a' },
173     { "cmd-help", 2, 0, 'h' },
174     { "connect", 1, 0, 'c' },
175     { "csh", 0, 0, 0 },
176     { "domain", 1, 0, 'd' },
177     { "echo-keys", 0, 0, 0 },
178     { "file", 1, 0, 'f' },
179     { "format", 2, 0, 0 },
180     { "help", 0, 0, HELP_OPTION },
181     { "inspector", 0, 0, 'i' },
182     { "keys-from-stdin", 0, 0, 0 },
183     { "listen", 0, 0, 0 },
184     { "live", 0, 0, 0 },
185     { "mount", 1, 0, 'm' },
186     { "new", 1, 0, 'N' },
187     { "no-dest-paths", 0, 0, 'D' },
188     { "no-sync", 0, 0, 'n' },
189     { "progress-bars", 0, 0, 0 },
190     { "no-progress-bars", 0, 0, 0 },
191     { "remote", 2, 0, 0 },
192     { "ro", 0, 0, 'r' },
193     { "rw", 0, 0, 'w' },
194     { "selinux", 0, 0, 0 },
195     { "verbose", 0, 0, 'v' },
196     { "version", 0, 0, 'V' },
197     { 0, 0, 0, 0 }
198   };
199   struct drv *drvs = NULL;
200   struct drv *drv;
201   struct mp *mps = NULL;
202   struct mp *mp;
203   char *p, *file = NULL;
204   const char *format = NULL;
205   int c;
206   int option_index;
207   struct sigaction sa;
208   int next_prepared_drive = 1;
209
210   initialize_readline ();
211
212   memset (&sa, 0, sizeof sa);
213   sa.sa_handler = SIG_IGN;
214   sa.sa_flags = SA_RESTART;
215   sigaction (SIGPIPE, &sa, NULL);
216
217   /* guestfs_create is meant to be a lightweight operation, so
218    * it's OK to do it early here.
219    */
220   g = guestfs_create ();
221   if (g == NULL) {
222     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
223     exit (EXIT_FAILURE);
224   }
225
226   /* CAUTION: we are careful to modify argv[0] here, only after
227    * using it just above.
228    *
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.
231    */
232   //char *real_argv0 = argv[0];
233   argv[0] = bad_cast (program_name);
234
235   for (;;) {
236     c = getopt_long (argc, argv, options, long_options, &option_index);
237     if (c == -1) break;
238
239     switch (c) {
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")) {
244         if (optarg) {
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);
248             exit (EXIT_FAILURE);
249           }
250         } else {
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"),
255                      program_name);
256             exit (EXIT_FAILURE);
257           }
258         }
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")) {
262         keys_from_stdin = 1;
263       } else if (STREQ (long_options[option_index].name, "progress-bars")) {
264         override_progress_bars = 1;
265       } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
266         override_progress_bars = 0;
267       } else if (STREQ (long_options[option_index].name, "echo-keys")) {
268         echo_keys = 1;
269       } else if (STREQ (long_options[option_index].name, "format")) {
270         if (!optarg || STREQ (optarg, ""))
271           format = NULL;
272         else
273           format = optarg;
274       } else if (STREQ (long_options[option_index].name, "csh")) {
275         remote_control_csh = 1;
276       } else if (STREQ (long_options[option_index].name, "live")) {
277         live = 1;
278       } else {
279         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
280                  program_name, long_options[option_index].name, option_index);
281         exit (EXIT_FAILURE);
282       }
283       break;
284
285     case 'a':
286       OPTION_a;
287       break;
288
289     case 'c':
290       OPTION_c;
291       break;
292
293     case 'd':
294       OPTION_d;
295       break;
296
297     case 'D':
298       complete_dest_paths = 0;
299       break;
300
301     case 'f':
302       if (file) {
303         fprintf (stderr, _("%s: only one -f parameter can be given\n"),
304                  program_name);
305         exit (EXIT_FAILURE);
306       }
307       file = optarg;
308       break;
309
310     case 'h': {
311       int r = 0;
312
313       if (optarg)
314         r = display_command (optarg);
315       else if (argv[optind] && argv[optind][0] != '-')
316         r = display_command (argv[optind++]);
317       else
318         list_commands ();
319
320       exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
321     }
322
323     case 'i':
324       OPTION_i;
325       break;
326
327     case 'm':
328       OPTION_m;
329       break;
330
331     case 'n':
332       OPTION_n;
333       break;
334
335     case 'N':
336       if (STRCASEEQ (optarg, "list") ||
337           STRCASEEQ (optarg, "help") ||
338           STRCASEEQ (optarg, "h") ||
339           STRCASEEQ (optarg, "?")) {
340         list_prepared_drives ();
341         exit (EXIT_SUCCESS);
342       }
343       drv = malloc (sizeof (struct drv));
344       if (!drv) {
345         perror ("malloc");
346         exit (EXIT_FAILURE);
347       }
348       drv->type = drv_N;
349       drv->device = NULL;
350       drv->nr_drives = -1;
351       if (asprintf (&drv->N.filename, "test%d.img",
352                     next_prepared_drive++) == -1) {
353         perror ("asprintf");
354         exit (EXIT_FAILURE);
355       }
356       drv->N.data = create_prepared_file (optarg, drv->N.filename);
357       drv->N.data_free = free_prep_data;
358       drv->next = drvs;
359       drvs = drv;
360       break;
361
362     case 'r':
363       OPTION_r;
364       break;
365
366     case 'v':
367       OPTION_v;
368       break;
369
370     case 'V':
371       OPTION_V;
372       break;
373
374     case 'w':
375       OPTION_w;
376       break;
377
378     case 'x':
379       OPTION_x;
380       break;
381
382     case HELP_OPTION:
383       usage (EXIT_SUCCESS);
384
385     default:
386       usage (EXIT_FAILURE);
387     }
388   }
389
390   /* Decide here if this will be an interactive session.  We have to
391    * do this as soon as possible after processing the command line
392    * args.
393    */
394   is_interactive = !file && isatty (0);
395
396   /* Register a ^C handler.  We have to do this before launch could
397    * possibly be called below.
398    */
399   if (is_interactive) {
400     memset (&sa, 0, sizeof sa);
401     sa.sa_handler = user_cancel;
402     sa.sa_flags = SA_RESTART;
403     sigaction (SIGINT, &sa, NULL);
404
405     guestfs_set_pgroup (g, 1);
406   }
407
408   /* Old-style -i syntax?  Since -a/-d/-N and -i was disallowed
409    * previously, if we have -i without any drives but with something
410    * on the command line, it must be old-style syntax.
411    */
412   if (inspector && drvs == NULL && optind < argc) {
413     while (optind < argc) {
414       if (strchr (argv[optind], '/') ||
415           access (argv[optind], F_OK) == 0) { /* simulate -a option */
416         drv = malloc (sizeof (struct drv));
417         if (!drv) {
418           perror ("malloc");
419           exit (EXIT_FAILURE);
420         }
421         drv->type = drv_a;
422         drv->a.filename = argv[optind];
423         drv->a.format = NULL;
424         drv->next = drvs;
425         drvs = drv;
426       } else {                  /* simulate -d option */
427         drv = malloc (sizeof (struct drv));
428         if (!drv) {
429           perror ("malloc");
430           exit (EXIT_FAILURE);
431         }
432         drv->type = drv_d;
433         drv->d.guest = argv[optind];
434         drv->next = drvs;
435         drvs = drv;
436       }
437
438       optind++;
439     }
440   }
441
442   /* If we've got drives to add, add them now. */
443   add_drives (drvs, 'a');
444
445   /* If we've got mountpoints or prepared drives or -i option, we must
446    * launch the guest and mount them.
447    */
448   if (next_prepared_drive > 1 || mps != NULL || inspector) {
449     /* RHBZ#612178: If --listen flag is given, then we will fork into
450      * the background in rc_listen().  However you can't do this while
451      * holding a libguestfs handle open because the recovery process
452      * will think the main program has died and kill qemu.  Therefore
453      * don't use the recovery process for this case.  (A better
454      * solution would be to call launch () etc after the fork, but
455      * that greatly complicates the code here).
456      */
457     if (remote_control_listen)
458       guestfs_set_recovery_proc (g, 0);
459
460     if (launch () == -1) exit (EXIT_FAILURE);
461
462     if (inspector)
463       inspect_mount ();
464
465     prepare_drives (drvs);
466     mount_mps (mps);
467   }
468
469   /* Free up data structures, no longer needed after this point. */
470   free_drives (drvs);
471   free_mps (mps);
472
473   /* Remote control? */
474   if (remote_control_listen && remote_control) {
475     fprintf (stderr,
476              _("%s: cannot use --listen and --remote options at the same time\n"),
477              program_name);
478     exit (EXIT_FAILURE);
479   }
480
481   if (remote_control_listen) {
482     if (optind < argc) {
483       fprintf (stderr,
484                _("%s: extra parameters on the command line with --listen flag\n"),
485                program_name);
486       exit (EXIT_FAILURE);
487     }
488     if (file) {
489       fprintf (stderr,
490                _("%s: cannot use --listen and --file options at the same time\n"),
491                program_name);
492       exit (EXIT_FAILURE);
493     }
494     rc_listen ();
495   }
496
497   /* -f (file) parameter? */
498   if (file) {
499     close (0);
500     if (open (file, O_RDONLY) == -1) {
501       perror (file);
502       exit (EXIT_FAILURE);
503     }
504   }
505
506   /* Get the name of the input file, for error messages, and replace
507    * the default error handler.
508    */
509   if (!is_interactive) {
510     if (file)
511       input_file = file;
512     else
513       input_file = "*stdin*";
514     guestfs_set_error_handler (g, error_cb, NULL);
515   }
516   input_lineno = 0;
517
518   /* Decide if we display progress bars. */
519   progress_bars =
520     override_progress_bars >= 0
521     ? override_progress_bars
522     : (optind >= argc && is_interactive);
523
524   if (progress_bars) {
525     bar = progress_bar_init (0);
526     if (!bar) {
527       perror ("progress_bar_init");
528       exit (EXIT_FAILURE);
529     }
530
531     guestfs_set_event_callback (g, progress_callback,
532                                 GUESTFS_EVENT_PROGRESS, 0, NULL);
533   }
534
535   /* Interactive, shell script, or command(s) on the command line? */
536   if (optind >= argc) {
537     if (is_interactive)
538       interactive ();
539     else
540       shell_script ();
541   }
542   else
543     cmdline (argv, optind, argc);
544
545   cleanup_readline ();
546
547   if (progress_bars)
548     progress_bar_free (bar);
549
550   guestfs_close (g);
551
552   exit (EXIT_SUCCESS);
553 }
554
555 static void
556 user_cancel (int sig)
557 {
558   if (g)
559     guestfs_user_cancel (g);
560 }
561
562 static void
563 prepare_drives (struct drv *drv)
564 {
565   if (drv) {
566     prepare_drives (drv->next);
567     if (drv->type == drv_N)
568       prepare_drive (drv->N.filename, drv->N.data, drv->device);
569   }
570 }
571
572 static int
573 launch (void)
574 {
575   if (guestfs_is_config (g)) {
576     if (guestfs_launch (g) == -1)
577       return -1;
578   }
579   return 0;
580 }
581
582 static void
583 interactive (void)
584 {
585   script (1);
586 }
587
588 static void
589 shell_script (void)
590 {
591   script (0);
592 }
593
594 #define FISH "><fs> "
595
596 static char *line_read = NULL;
597
598 static char *
599 rl_gets (int prompt)
600 {
601 #ifdef HAVE_LIBREADLINE
602
603   if (prompt) {
604     if (line_read) {
605       free (line_read);
606       line_read = NULL;
607     }
608
609     line_read = readline (prompt ? FISH : "");
610
611     if (line_read && *line_read)
612       add_history_line (line_read);
613
614     return line_read;
615   }
616
617 #endif /* HAVE_LIBREADLINE */
618
619   static char buf[8192];
620   int len;
621
622   if (prompt) printf (FISH);
623   line_read = fgets (buf, sizeof buf, stdin);
624
625   if (line_read) {
626     len = strlen (line_read);
627     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
628   }
629
630   return line_read;
631 }
632
633 static void
634 script (int prompt)
635 {
636   char *buf;
637   int global_exit_on_error = !prompt;
638   int exit_on_error;
639   struct parsed_command pcmd;
640
641   if (prompt) {
642     printf (_("\n"
643               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
644               "editing virtual machine filesystems.\n"
645               "\n"
646               "Type: 'help' for help on commands\n"
647               "      'man' to read the manual\n"
648               "      'quit' to quit the shell\n"
649               "\n"));
650
651     if (inspector) {
652       print_inspect_prompt ();
653       printf ("\n");
654     }
655   }
656
657   while (!quit) {
658     exit_on_error = global_exit_on_error;
659
660     buf = rl_gets (prompt);
661     if (!buf) {
662       quit = 1;
663       break;
664     }
665
666     input_lineno++;
667
668     pcmd = parse_command_line (buf, &exit_on_error);
669     if (pcmd.status == -1 && exit_on_error)
670       exit (EXIT_FAILURE);
671     if (pcmd.status == 1) {
672       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
673         if (exit_on_error) exit (EXIT_FAILURE);
674       }
675     }
676   }
677   if (prompt) printf ("\n");
678 }
679
680 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
681  * This destructively updates 'buf'.
682  *
683  * 'exit_on_error_rtn' is used to pass in the global exit_on_error
684  * setting and to return the local setting (eg. if the command begins
685  * with '-').
686  *
687  * Returns in parsed_command.status:
688  *   1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
689  *   0 = no guestfish command, but otherwise OK
690  *  -1 = an error
691  */
692 static struct parsed_command
693 parse_command_line (char *buf, int *exit_on_error_rtn)
694 {
695   struct parsed_command pcmd;
696   char *p, *pend;
697   int len;
698   int tilde_candidate;
699   int r;
700   const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
701
702   /* Note that pcmd.pipe must be set to NULL for correct usage.  Other
703    * fields do not need to be, but this silences a gcc warning.
704    */
705   memset (&pcmd, 0, sizeof pcmd);
706
707  again:
708   /* Skip any initial whitespace before the command. */
709   while (*buf && c_isspace (*buf))
710     buf++;
711
712   if (!*buf) {
713     pcmd.status = 0;
714     return pcmd;
715   }
716
717   /* If the next character is '#' then this is a comment. */
718   if (*buf == '#') {
719     pcmd.status = 0;
720     return pcmd;
721   }
722
723   /* If the next character is '!' then pass the whole lot to system(3). */
724   if (*buf == '!') {
725     r = system (buf+1);
726     if (r == -1 ||
727         (WIFSIGNALED (r) &&
728          (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
729         WEXITSTATUS (r) != 0)
730       pcmd.status = -1;
731     else
732       pcmd.status = 0;
733     return pcmd;
734   }
735
736   /* If the next two characters are "<!" then pass the command to
737    * popen(3), read the result and execute it as guestfish commands.
738    */
739   if (buf[0] == '<' && buf[1] == '!') {
740     int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
741     if (r == -1)
742       pcmd.status = -1;
743     else
744       pcmd.status = 0;
745     return pcmd;
746   }
747
748   /* If the next character is '-' allow the command to fail without
749    * exiting on error (just for this one command though).
750    */
751   if (*buf == '-') {
752     *exit_on_error_rtn = 0;
753     buf++;
754     goto again;
755   }
756
757   /* Get the command (cannot be quoted). */
758   len = strcspn (buf, " \t");
759
760   if (len == 0) {
761     pcmd.status = 0;
762     return pcmd;
763   }
764
765   pcmd.cmd = buf;
766   unsigned int i = 0;
767   if (buf[len] == '\0') {
768     pcmd.argv[0] = NULL;
769     pcmd.status = 1;
770     return pcmd;
771   }
772
773   buf[len] = '\0';
774   p = &buf[len+1];
775   p += strspn (p, " \t");
776
777   /* Get the parameters. */
778   while (*p && i < argv_len) {
779     tilde_candidate = 0;
780
781     /* Parameters which start with quotes or pipes are treated
782      * specially.  Bare parameters are delimited by whitespace.
783      */
784     if (*p == '"') {
785       p++;
786       len = parse_quoted_string (p);
787       if (len == -1) {
788         pcmd.status = -1;
789         return pcmd;
790       }
791       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
792         fprintf (stderr,
793                  _("%s: command arguments not separated by whitespace\n"),
794                  program_name);
795         pcmd.status = -1;
796         return pcmd;
797       }
798       pend = p[len+1] ? &p[len+2] : &p[len+1];
799     } else if (*p == '\'') {
800       p++;
801       len = strcspn (p, "'");
802       if (p[len] == '\0') {
803         fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
804         pcmd.status = -1;
805         return pcmd;
806       }
807       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
808         fprintf (stderr,
809                  _("%s: command arguments not separated by whitespace\n"),
810                  program_name);
811         pcmd.status = -1;
812         return pcmd;
813       }
814       p[len] = '\0';
815       pend = p[len+1] ? &p[len+2] : &p[len+1];
816     } else if (*p == '|') {
817       *p = '\0';
818       pcmd.pipe = p+1;
819       continue;
820     } else if (*p != ' ' && *p != '\t') {
821       /* If the first character is a ~ then note that this parameter
822        * is a candidate for ~username expansion.  NB this does not
823        * apply to quoted parameters.
824        */
825       tilde_candidate = *p == '~';
826       len = strcspn (p, " \t");
827       if (p[len]) {
828         p[len] = '\0';
829         pend = &p[len+1];
830       } else
831         pend = &p[len];
832     } else {
833       fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
834                program_name, p);
835       abort ();
836     }
837
838     if (!tilde_candidate)
839       pcmd.argv[i] = p;
840     else
841       pcmd.argv[i] = try_tilde_expansion (p);
842     i++;
843     p = pend;
844
845     if (*p)
846       p += strspn (p, " \t");
847   }
848
849   if (i == argv_len) {
850     fprintf (stderr, _("%s: too many arguments\n"), program_name);
851     pcmd.status = -1;
852     return pcmd;
853   }
854
855   pcmd.argv[i] = NULL;
856
857   pcmd.status = 1;
858   return pcmd;
859 }
860
861 static int
862 hexdigit (char d)
863 {
864   switch (d) {
865   case '0'...'9': return d - '0';
866   case 'a'...'f': return d - 'a' + 10;
867   case 'A'...'F': return d - 'A' + 10;
868   default: return -1;
869   }
870 }
871
872 /* Parse double-quoted strings, replacing backslash escape sequences
873  * with the true character.  Since the string is returned in place,
874  * the escapes must make the string shorter.
875  */
876 static int
877 parse_quoted_string (char *p)
878 {
879   char *start = p;
880
881   for (; *p && *p != '"'; p++) {
882     if (*p == '\\') {
883       int m = 1, c;
884
885       switch (p[1]) {
886       case '\\': break;
887       case 'a': *p = '\a'; break;
888       case 'b': *p = '\b'; break;
889       case 'f': *p = '\f'; break;
890       case 'n': *p = '\n'; break;
891       case 'r': *p = '\r'; break;
892       case 't': *p = '\t'; break;
893       case 'v': *p = '\v'; break;
894       case '"': *p = '"'; break;
895       case '\'': *p = '\''; break;
896       case '?': *p = '?'; break;
897
898       case '0'...'7':           /* octal escape - always 3 digits */
899         m = 3;
900         if (p[2] >= '0' && p[2] <= '7' &&
901             p[3] >= '0' && p[3] <= '7') {
902           c = (p[1] - '0') * 0100 + (p[2] - '0') * 010 + (p[3] - '0');
903           if (c < 1 || c > 255)
904             goto error;
905           *p = c;
906         }
907         else
908           goto error;
909         break;
910
911       case 'x':                 /* hex escape - always 2 digits */
912         m = 3;
913         if (c_isxdigit (p[2]) && c_isxdigit (p[3])) {
914           c = hexdigit (p[2]) * 0x10 + hexdigit (p[3]);
915           if (c < 1 || c > 255)
916             goto error;
917           *p = c;
918         }
919         else
920           goto error;
921         break;
922
923       default:
924       error:
925         fprintf (stderr, _("%s: invalid escape sequence in string (starting at offset %d)\n"),
926                  program_name, (int) (p - start));
927         return -1;
928       }
929       memmove (p+1, p+1+m, strlen (p+1+m) + 1);
930     }
931   }
932
933   if (!*p) {
934     fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
935     return -1;
936   }
937
938   *p = '\0';
939   return p - start;
940 }
941
942 /* Used to handle "<!" (execute command and inline result). */
943 static int
944 execute_and_inline (const char *cmd, int global_exit_on_error)
945 {
946   FILE *pp;
947   char *line = NULL;
948   size_t len = 0;
949   ssize_t n;
950   int exit_on_error;
951   struct parsed_command pcmd;
952
953   pp = popen (cmd, "r");
954   if (!pp) {
955     perror ("popen");
956     return -1;
957   }
958
959   while ((n = getline (&line, &len, pp)) != -1) {
960     exit_on_error = global_exit_on_error;
961
962     /* Chomp final line ending which parse_command_line would not expect. */
963     if (n > 0 && line[n-1] == '\n')
964       line[n-1] = '\0';
965
966     pcmd = parse_command_line (line, &exit_on_error);
967     if (pcmd.status == -1 && exit_on_error)
968       exit (EXIT_FAILURE);
969     if (pcmd.status == 1) {
970       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
971         if (exit_on_error) exit (EXIT_FAILURE);
972       }
973     }
974   }
975
976   free (line);
977
978   if (pclose (pp) != 0) {
979     perror ("pclose");
980     return -1;
981   }
982
983   return 0;
984 }
985
986 static void
987 cmdline (char *argv[], int optind, int argc)
988 {
989   const char *cmd;
990   char **params;
991   int exit_on_error;
992
993   exit_on_error = 1;
994
995   if (optind >= argc) return;
996
997   cmd = argv[optind++];
998   if (STREQ (cmd, ":")) {
999     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
1000     exit (EXIT_FAILURE);
1001   }
1002
1003   /* Allow -cmd on the command line to mean (temporarily) override
1004    * the normal exit on error (RHBZ#578407).
1005    */
1006   if (cmd[0] == '-') {
1007     exit_on_error = 0;
1008     cmd++;
1009   }
1010
1011   params = &argv[optind];
1012
1013   /* Search for end of command list or ":" ... */
1014   while (optind < argc && STRNEQ (argv[optind], ":"))
1015     optind++;
1016
1017   if (optind == argc) {
1018     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1019         exit (EXIT_FAILURE);
1020   } else {
1021     argv[optind] = NULL;
1022     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1023       exit (EXIT_FAILURE);
1024     cmdline (argv, optind+1, argc);
1025   }
1026 }
1027
1028 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
1029  * pass to the remote server (when issuing --remote commands).  It
1030  * does not cause issue_command itself to exit on error.
1031  */
1032 int
1033 issue_command (const char *cmd, char *argv[], const char *pipecmd,
1034                int rc_exit_on_error_flag)
1035 {
1036   int argc;
1037   int stdout_saved_fd = -1;
1038   int pid = 0;
1039   int r;
1040
1041   if (progress_bars)
1042     progress_bar_reset (bar);
1043
1044   /* This counts the commands issued, starting at 1. */
1045   command_num++;
1046
1047   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
1048   if (pipecmd) {
1049     int fd[2];
1050
1051     if (fflush (stdout) == EOF) {
1052       perror ("failed to flush standard output");
1053       return -1;
1054     }
1055     if (pipe (fd) < 0) {
1056       perror ("pipe failed");
1057       return -1;
1058     }
1059     pid = fork ();
1060     if (pid == -1) {
1061       perror ("fork");
1062       return -1;
1063     }
1064
1065     if (pid == 0) {             /* Child process. */
1066       close (fd[1]);
1067       if (dup2 (fd[0], 0) < 0) {
1068         perror ("dup2 of stdin failed");
1069         _exit (1);
1070       }
1071
1072       r = system (pipecmd);
1073       if (r == -1) {
1074         perror (pipecmd);
1075         _exit (1);
1076       }
1077       _exit (WEXITSTATUS (r));
1078     }
1079
1080     if ((stdout_saved_fd = dup (1)) < 0) {
1081       perror ("failed to dup stdout");
1082       return -1;
1083     }
1084     close (fd[0]);
1085     if (dup2 (fd[1], 1) < 0) {
1086       perror ("failed to dup stdout");
1087       close (stdout_saved_fd);
1088       return -1;
1089     }
1090     close (fd[1]);
1091   }
1092
1093   for (argc = 0; argv[argc] != NULL; ++argc)
1094     ;
1095
1096   /* If --remote was set, then send this command to a remote process. */
1097   if (remote_control)
1098     r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1099
1100   /* Otherwise execute it locally. */
1101   else if (STRCASEEQ (cmd, "help")) {
1102     if (argc == 0) {
1103       display_help ();
1104       r = 0;
1105     } else
1106       r = display_command (argv[0]);
1107   }
1108   else if (STRCASEEQ (cmd, "quit") ||
1109            STRCASEEQ (cmd, "exit") ||
1110            STRCASEEQ (cmd, "q")) {
1111     quit = 1;
1112     r = 0;
1113   }
1114   else
1115     r = run_action (cmd, argc, argv);
1116
1117   /* Always flush stdout after every command, so that messages, results
1118    * etc appear immediately.
1119    */
1120   if (fflush (stdout) == EOF) {
1121     perror ("failed to flush standard output");
1122     return -1;
1123   }
1124
1125   if (pipecmd) {
1126     close (1);
1127     if (dup2 (stdout_saved_fd, 1) < 0) {
1128       perror ("failed to dup2 standard output");
1129       r = -1;
1130     }
1131     close (stdout_saved_fd);
1132     if (waitpid (pid, NULL, 0) < 0) {
1133       perror ("waiting for command to complete");
1134       r = -1;
1135     }
1136   }
1137
1138   return r;
1139 }
1140
1141 void
1142 list_builtin_commands (void)
1143 {
1144   /* help and quit should appear at the top */
1145   printf ("%-20s %s\n",
1146           "help", _("display a list of commands or help on a command"));
1147   printf ("%-20s %s\n",
1148           "quit", _("quit guestfish"));
1149
1150   /* actions are printed after this (see list_commands) */
1151 }
1152
1153 int
1154 display_builtin_command (const char *cmd)
1155 {
1156   /* help for actions is auto-generated, see display_command */
1157
1158   if (STRCASEEQ (cmd, "help")) {
1159     printf (_("help - display a list of commands or help on a command\n"
1160               "     help cmd\n"
1161               "     help\n"));
1162     return 0;
1163   }
1164   else if (STRCASEEQ (cmd, "quit") ||
1165            STRCASEEQ (cmd, "exit") ||
1166            STRCASEEQ (cmd, "q")) {
1167     printf (_("quit - quit guestfish\n"
1168               "     quit\n"));
1169     return 0;
1170   }
1171   else {
1172     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1173              cmd);
1174     return -1;
1175   }
1176 }
1177
1178 /* This is printed when the user types in an unknown command for the
1179  * first command issued.  A common case is the user doing:
1180  *   guestfish disk.img
1181  * expecting guestfish to open 'disk.img' (in fact, this tried to
1182  * run a command 'disk.img').
1183  */
1184 void
1185 extended_help_message (void)
1186 {
1187   fprintf (stderr,
1188            _("Did you mean to open a disk image?  guestfish -a disk.img\n"
1189              "For a list of commands:             guestfish -h\n"
1190              "For complete documentation:         man guestfish\n"));
1191 }
1192
1193 /* Error callback.  This replaces the standard libguestfs error handler. */
1194 static void
1195 error_cb (guestfs_h *g, void *data, const char *msg)
1196 {
1197   fprintf (stderr, _("%s:%d: libguestfs: error: %s\n"),
1198            input_file, input_lineno, msg);
1199 }
1200
1201 void
1202 free_strings (char **argv)
1203 {
1204   int argc;
1205
1206   for (argc = 0; argv[argc] != NULL; ++argc)
1207     free (argv[argc]);
1208   free (argv);
1209 }
1210
1211 int
1212 count_strings (char *const *argv)
1213 {
1214   int c;
1215
1216   for (c = 0; argv[c]; ++c)
1217     ;
1218   return c;
1219 }
1220
1221 void
1222 print_strings (char *const *argv)
1223 {
1224   int argc;
1225
1226   for (argc = 0; argv[argc] != NULL; ++argc)
1227     printf ("%s\n", argv[argc]);
1228 }
1229
1230 void
1231 print_table (char *const *argv)
1232 {
1233   int i;
1234
1235   for (i = 0; argv[i] != NULL; i += 2)
1236     printf ("%s: %s\n", argv[i], argv[i+1]);
1237 }
1238
1239 int
1240 is_true (const char *str)
1241 {
1242   return
1243     STRCASENEQ (str, "0") &&
1244     STRCASENEQ (str, "f") &&
1245     STRCASENEQ (str, "false") &&
1246     STRCASENEQ (str, "n") &&
1247     STRCASENEQ (str, "no");
1248 }
1249
1250 /* Free strings from a non-NULL terminated char** */
1251 static void
1252 free_n_strings (char **str, size_t len)
1253 {
1254   size_t i;
1255
1256   for (i = 0; i < len; i++) {
1257     free (str[i]);
1258   }
1259   free (str);
1260 }
1261
1262 char **
1263 parse_string_list (const char *str)
1264 {
1265   char **argv = NULL;
1266   size_t argv_len = 0;
1267
1268   /* Current position pointer */
1269   const char *p = str;
1270
1271   /* Token might be simple:
1272    *  Token
1273    * or be quoted:
1274    *  'This is a single token'
1275    * or contain embedded single-quoted sections:
1276    *  This' is a sing'l'e to'ken
1277    *
1278    * The latter may seem over-complicated, but it's what a normal shell does.
1279    * Not doing it risks surprising somebody.
1280    *
1281    * This outer loop is over complete tokens.
1282    */
1283   while (*p) {
1284     char *tok = NULL;
1285     size_t tok_len = 0;
1286
1287     /* Skip leading whitespace */
1288     p += strspn (p, " \t");
1289
1290     char in_quote = 0;
1291
1292     /* This loop is over token 'fragments'. A token can be in multiple bits if
1293      * it contains single quotes. We also treat both sides of an escaped quote
1294      * as separate fragments because we can't just copy it: we have to remove
1295      * the \.
1296      */
1297     while (*p && (!c_isblank (*p) || in_quote)) {
1298       const char *end = p;
1299
1300       /* Check if the fragment starts with a quote */
1301       if ('\'' == *p) {
1302         /* Toggle in_quote */
1303         in_quote = !in_quote;
1304
1305         /* Skip the quote */
1306         p++; end++;
1307       }
1308
1309       /* If we're in a quote, look for an end quote */
1310       if (in_quote) {
1311         end += strcspn (end, "'");
1312       }
1313
1314       /* Otherwise, look for whitespace or a quote */
1315       else {
1316         end += strcspn (end, " \t'");
1317       }
1318
1319       /* Grow the token to accommodate the fragment */
1320       size_t tok_end = tok_len;
1321       tok_len += end - p;
1322       char *tok_new = realloc (tok, tok_len + 1);
1323       if (NULL == tok_new) {
1324         perror ("realloc");
1325         free_n_strings (argv, argv_len);
1326         free (tok);
1327         exit (EXIT_FAILURE);
1328       }
1329       tok = tok_new;
1330
1331       /* Check if we stopped on an escaped quote */
1332       if ('\'' == *end && end != p && *(end-1) == '\\') {
1333         /* Add everything before \' to the token */
1334         memcpy (&tok[tok_end], p, end - p - 1);
1335
1336         /* Add the quote */
1337         tok[tok_len-1] = '\'';
1338
1339         /* Already processed the quote */
1340         p = end + 1;
1341       }
1342
1343       else {
1344         /* Add the whole fragment */
1345         memcpy (&tok[tok_end], p, end - p);
1346
1347         p = end;
1348       }
1349     }
1350
1351     /* We've reached the end of a token. We shouldn't still be in quotes. */
1352     if (in_quote) {
1353       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1354       free_n_strings (argv, argv_len);
1355       free (tok);
1356       return NULL;
1357     }
1358
1359     /* Add this token if there is one. There might not be if there was
1360      * whitespace at the end of the input string */
1361     if (tok) {
1362       /* Add the NULL terminator */
1363       tok[tok_len] = '\0';
1364
1365       /* Add the argument to the argument list */
1366       argv_len++;
1367       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1368       if (NULL == argv_new) {
1369         perror ("realloc");
1370         free_n_strings (argv, argv_len-1);
1371         free (tok);
1372         exit (EXIT_FAILURE);
1373       }
1374       argv = argv_new;
1375
1376       argv[argv_len-1] = tok;
1377     }
1378   }
1379
1380   /* NULL terminate the argument list */
1381   argv_len++;
1382   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1383   if (NULL == argv_new) {
1384     perror ("realloc");
1385     free_n_strings (argv, argv_len-1);
1386     exit (EXIT_FAILURE);
1387   }
1388   argv = argv_new;
1389
1390   argv[argv_len-1] = NULL;
1391
1392   return argv;
1393 }
1394
1395 #ifdef HAVE_LIBREADLINE
1396 static char histfile[1024];
1397 static int nr_history_lines = 0;
1398 #endif
1399
1400 static void
1401 initialize_readline (void)
1402 {
1403 #ifdef HAVE_LIBREADLINE
1404   const char *home;
1405
1406   home = getenv ("HOME");
1407   if (home) {
1408     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1409     using_history ();
1410     (void) read_history (histfile);
1411   }
1412
1413   rl_readline_name = "guestfish";
1414   rl_attempted_completion_function = do_completion;
1415
1416   /* Note that .inputrc (or /etc/inputrc) is not read until the first
1417    * call the readline(), which happens later.  Therefore, these
1418    * provide default values which can be overridden by the user if
1419    * they wish.
1420    */
1421   (void) rl_variable_bind ("completion-ignore-case", "on");
1422 #endif
1423 }
1424
1425 static void
1426 cleanup_readline (void)
1427 {
1428 #ifdef HAVE_LIBREADLINE
1429   int fd;
1430
1431   if (histfile[0] != '\0') {
1432     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1433     if (fd == -1) {
1434       perror (histfile);
1435       return;
1436     }
1437     close (fd);
1438
1439 #ifdef HAVE_APPEND_HISTORY
1440     (void) append_history (nr_history_lines, histfile);
1441 #else
1442     (void) write_history (histfile);
1443 #endif
1444     clear_history ();
1445   }
1446 #endif
1447 }
1448
1449 #ifdef HAVE_LIBREADLINE
1450 static void
1451 add_history_line (const char *line)
1452 {
1453   add_history (line);
1454   nr_history_lines++;
1455 }
1456 #endif
1457
1458 int
1459 xwrite (int fd, const void *v_buf, size_t len)
1460 {
1461   int r;
1462   const char *buf = v_buf;
1463
1464   while (len > 0) {
1465     r = write (fd, buf, len);
1466     if (r == -1) {
1467       perror ("write");
1468       return -1;
1469     }
1470     buf += r;
1471     len -= r;
1472   }
1473
1474   return 0;
1475 }
1476
1477 /* Resolve the special "win:..." form for Windows-specific paths.  The
1478  * generated code calls this for all device or path arguments.
1479  *
1480  * The function returns a newly allocated string, and the caller must
1481  * free this string; else display an error and return NULL.
1482  */
1483 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1484
1485 char *
1486 win_prefix (const char *path)
1487 {
1488   char *ret;
1489   size_t i;
1490
1491   /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1492   if (STRCASENEQLEN (path, "win:", 4)) {
1493     ret = strdup (path);
1494     if (ret == NULL)
1495       perror ("strdup");
1496     return ret;
1497   }
1498
1499   path += 4;
1500
1501   /* If there is a drive letter, rewrite the path. */
1502   if (c_isalpha (path[0]) && path[1] == ':') {
1503     char drive_letter = c_tolower (path[0]);
1504     /* This returns the newly allocated string. */
1505     ret = win_prefix_drive_letter (drive_letter, path + 2);
1506     if (ret == NULL)
1507       return NULL;
1508   }
1509   else if (!*path) {
1510     ret = strdup ("/");
1511     if (ret == NULL) {
1512       perror ("strdup");
1513       return NULL;
1514     }
1515   }
1516   else {
1517     ret = strdup (path);
1518     if (ret == NULL) {
1519       perror ("strdup");
1520       return NULL;
1521     }
1522   }
1523
1524   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1525   for (i = 0; i < strlen (ret); ++i)
1526     if (ret[i] == '\\')
1527       ret[i] = '/';
1528
1529   char *t = guestfs_case_sensitive_path (g, ret);
1530   free (ret);
1531   ret = t;
1532
1533   return ret;
1534 }
1535
1536 static char *
1537 win_prefix_drive_letter (char drive_letter, const char *path)
1538 {
1539   char **roots = NULL;
1540   char **drives = NULL;
1541   char **mountpoints = NULL;
1542   char *device, *mountpoint, *ret = NULL;
1543   size_t i;
1544
1545   /* Resolve the drive letter using the drive mappings table. */
1546   roots = guestfs_inspect_get_roots (g);
1547   if (roots == NULL)
1548     goto out;
1549   if (roots[0] == NULL) {
1550     fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1551              program_name);
1552     goto out;
1553   }
1554   drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1555   if (drives == NULL || drives[0] == NULL) {
1556     fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1557              program_name);
1558     goto out;
1559   }
1560
1561   device = NULL;
1562   for (i = 0; drives[i] != NULL; i += 2) {
1563     if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1564       device = drives[i+1];
1565       break;
1566     }
1567   }
1568
1569   if (device == NULL) {
1570     fprintf (stderr, _("%s: drive '%c:' not found.  To list available drives do:\n  inspect-get-drive-mappings %s\n"),
1571              program_name, drive_letter, roots[0]);
1572     goto out;
1573   }
1574
1575   /* This drive letter must be mounted somewhere (we won't do it). */
1576   mountpoints = guestfs_mountpoints (g);
1577   if (mountpoints == NULL)
1578     goto out;
1579
1580   mountpoint = NULL;
1581   for (i = 0; mountpoints[i] != NULL; i += 2) {
1582     if (STREQ (mountpoints[i], device)) {
1583       mountpoint = mountpoints[i+1];
1584       break;
1585     }
1586   }
1587
1588   if (mountpoint == NULL) {
1589     fprintf (stderr, _("%s: to access '%c:', mount %s first.  One way to do this is:\n  umount-all\n  mount %s /\n"),
1590              program_name, drive_letter, device, device);
1591     goto out;
1592   }
1593
1594   /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1595   if (asprintf (&ret, "%s%s%s",
1596                 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1597     perror ("asprintf");
1598     goto out;
1599   }
1600
1601  out:
1602   if (roots)
1603     free_strings (roots);
1604   if (drives)
1605     free_strings (drives);
1606   if (mountpoints)
1607     free_strings (mountpoints);
1608
1609   return ret;
1610 }
1611
1612 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1613  * The caller (cmds.c) will call free_file_in after the command has
1614  * run which should clean up resources.
1615  */
1616 static char *file_in_heredoc (const char *endmarker);
1617 static char *file_in_tmpfile = NULL;
1618
1619 char *
1620 file_in (const char *arg)
1621 {
1622   char *ret;
1623
1624   if (STREQ (arg, "-")) {
1625     ret = strdup ("/dev/stdin");
1626     if (!ret) {
1627       perror ("strdup");
1628       return NULL;
1629     }
1630   }
1631   else if (STRPREFIX (arg, "-<<")) {
1632     const char *endmarker = &arg[3];
1633     if (*endmarker == '\0') {
1634       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1635                program_name);
1636       return NULL;
1637     }
1638     ret = file_in_heredoc (endmarker);
1639     if (ret == NULL)
1640       return NULL;
1641   }
1642   else {
1643     ret = strdup (arg);
1644     if (!ret) {
1645       perror ("strdup");
1646       return NULL;
1647     }
1648   }
1649
1650   return ret;
1651 }
1652
1653 static char *
1654 file_in_heredoc (const char *endmarker)
1655 {
1656   TMP_TEMPLATE_ON_STACK (template);
1657   file_in_tmpfile = strdup (template);
1658   if (file_in_tmpfile == NULL) {
1659     perror ("strdup");
1660     return NULL;
1661   }
1662
1663   int fd = mkstemp (file_in_tmpfile);
1664   if (fd == -1) {
1665     perror ("mkstemp");
1666     goto error1;
1667   }
1668
1669   size_t markerlen = strlen (endmarker);
1670
1671   char buffer[BUFSIZ];
1672   int write_error = 0;
1673   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1674     /* Look for "END"<EOF> or "END\n" in input. */
1675     size_t blen = strlen (buffer);
1676     if (STREQLEN (buffer, endmarker, markerlen) &&
1677         (blen == markerlen ||
1678          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1679       goto found_end;
1680
1681     if (xwrite (fd, buffer, blen) == -1) {
1682       if (!write_error) perror ("write");
1683       write_error = 1;
1684       /* continue reading up to the end marker */
1685     }
1686   }
1687
1688   /* Reached EOF of stdin without finding the end marker, which
1689    * is likely to be an error.
1690    */
1691   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1692            program_name, endmarker);
1693   goto error2;
1694
1695  found_end:
1696   if (write_error) {
1697     close (fd);
1698     goto error2;
1699   }
1700
1701   if (close (fd) == -1) {
1702     perror ("close");
1703     goto error2;
1704   }
1705
1706   return file_in_tmpfile;
1707
1708  error2:
1709   unlink (file_in_tmpfile);
1710
1711  error1:
1712   free (file_in_tmpfile);
1713   file_in_tmpfile = NULL;
1714   return NULL;
1715 }
1716
1717 void
1718 free_file_in (char *s)
1719 {
1720   if (file_in_tmpfile) {
1721     if (unlink (file_in_tmpfile) == -1)
1722       perror (file_in_tmpfile);
1723     file_in_tmpfile = NULL;
1724   }
1725
1726   /* Free the device or file name which was strdup'd in file_in().
1727    * Note it's not immediately clear, but for -<< heredocs,
1728    * s == file_in_tmpfile, so this frees up that buffer.
1729    */
1730   free (s);
1731 }
1732
1733 /* Resolve the special FileOut paths ("-" or filename).
1734  * The caller (cmds.c) will call free (str) after the command has run.
1735  */
1736 char *
1737 file_out (const char *arg)
1738 {
1739   char *ret;
1740
1741   if (STREQ (arg, "-"))
1742     ret = strdup ("/dev/stdout");
1743   else
1744     ret = strdup (arg);
1745
1746   if (!ret) {
1747     perror ("strdup");
1748     return NULL;
1749   }
1750   return ret;
1751 }
1752
1753 /* Callback which displays a progress bar. */
1754 void
1755 progress_callback (guestfs_h *g, void *data,
1756                    uint64_t event, int event_handle, int flags,
1757                    const char *buf, size_t buf_len,
1758                    const uint64_t *array, size_t array_len)
1759 {
1760   if (array_len < 4)
1761     return;
1762
1763   /*uint64_t proc_nr = array[0];*/
1764   /*uint64_t serial = array[1];*/
1765   uint64_t position = array[2];
1766   uint64_t total = array[3];
1767
1768   progress_bar_set (bar, position, total);
1769 }