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