man pages: Add a standard EXIT STATUS section to most pages.
[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   exit (EXIT_SUCCESS);
536 }
537
538 static void
539 user_cancel (int sig)
540 {
541   if (g)
542     guestfs_user_cancel (g);
543 }
544
545 static void
546 prepare_drives (struct drv *drv)
547 {
548   if (drv) {
549     prepare_drives (drv->next);
550     if (drv->type == drv_N)
551       prepare_drive (drv->N.filename, drv->N.data, drv->device);
552   }
553 }
554
555 static int
556 launch (void)
557 {
558   if (guestfs_is_config (g)) {
559     if (guestfs_launch (g) == -1)
560       return -1;
561   }
562   return 0;
563 }
564
565 static void
566 interactive (void)
567 {
568   script (1);
569 }
570
571 static void
572 shell_script (void)
573 {
574   script (0);
575 }
576
577 #define FISH "><fs> "
578
579 static char *line_read = NULL;
580
581 static char *
582 rl_gets (int prompt)
583 {
584 #ifdef HAVE_LIBREADLINE
585
586   if (prompt) {
587     if (line_read) {
588       free (line_read);
589       line_read = NULL;
590     }
591
592     line_read = readline (prompt ? FISH : "");
593
594     if (line_read && *line_read)
595       add_history_line (line_read);
596
597     return line_read;
598   }
599
600 #endif /* HAVE_LIBREADLINE */
601
602   static char buf[8192];
603   int len;
604
605   if (prompt) printf (FISH);
606   line_read = fgets (buf, sizeof buf, stdin);
607
608   if (line_read) {
609     len = strlen (line_read);
610     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
611   }
612
613   return line_read;
614 }
615
616 static void
617 script (int prompt)
618 {
619   char *buf;
620   int global_exit_on_error = !prompt;
621   int exit_on_error;
622   struct parsed_command pcmd;
623
624   if (prompt) {
625     printf (_("\n"
626               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
627               "editing virtual machine filesystems.\n"
628               "\n"
629               "Type: 'help' for help on commands\n"
630               "      'man' to read the manual\n"
631               "      'quit' to quit the shell\n"
632               "\n"));
633
634     if (inspector) {
635       print_inspect_prompt ();
636       printf ("\n");
637     }
638   }
639
640   while (!quit) {
641     exit_on_error = global_exit_on_error;
642
643     buf = rl_gets (prompt);
644     if (!buf) {
645       quit = 1;
646       break;
647     }
648
649     pcmd = parse_command_line (buf, &exit_on_error);
650     if (pcmd.status == -1 && exit_on_error)
651       exit (EXIT_FAILURE);
652     if (pcmd.status == 1) {
653       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
654         if (exit_on_error) exit (EXIT_FAILURE);
655       }
656     }
657   }
658   if (prompt) printf ("\n");
659 }
660
661 /* Parse a command string, splitting at whitespace, handling '!', '#' etc.
662  * This destructively updates 'buf'.
663  *
664  * 'exit_on_error_rtn' is used to pass in the global exit_on_error
665  * setting and to return the local setting (eg. if the command begins
666  * with '-').
667  *
668  * Returns in parsed_command.status:
669  *   1 = got a guestfish command (returned in cmd_rtn/argv_rtn/pipe_rtn)
670  *   0 = no guestfish command, but otherwise OK
671  *  -1 = an error
672  */
673 static struct parsed_command
674 parse_command_line (char *buf, int *exit_on_error_rtn)
675 {
676   struct parsed_command pcmd;
677   char *p, *pend;
678   int len;
679   int tilde_candidate;
680   int r;
681   const size_t argv_len = sizeof pcmd.argv / sizeof pcmd.argv[0];
682
683   /* Note that pcmd.pipe must be set to NULL for correct usage.  Other
684    * fields do not need to be, but this silences a gcc warning.
685    */
686   memset (&pcmd, 0, sizeof pcmd);
687
688  again:
689   /* Skip any initial whitespace before the command. */
690   while (*buf && c_isspace (*buf))
691     buf++;
692
693   if (!*buf) {
694     pcmd.status = 0;
695     return pcmd;
696   }
697
698   /* If the next character is '#' then this is a comment. */
699   if (*buf == '#') {
700     pcmd.status = 0;
701     return pcmd;
702   }
703
704   /* If the next character is '!' then pass the whole lot to system(3). */
705   if (*buf == '!') {
706     r = system (buf+1);
707     if (r == -1 ||
708         (WIFSIGNALED (r) &&
709          (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
710         WEXITSTATUS (r) != 0)
711       pcmd.status = -1;
712     else
713       pcmd.status = 0;
714     return pcmd;
715   }
716
717   /* If the next two characters are "<!" then pass the command to
718    * popen(3), read the result and execute it as guestfish commands.
719    */
720   if (buf[0] == '<' && buf[1] == '!') {
721     int r = execute_and_inline (&buf[2], *exit_on_error_rtn);
722     if (r == -1)
723       pcmd.status = -1;
724     else
725       pcmd.status = 0;
726     return pcmd;
727   }
728
729   /* If the next character is '-' allow the command to fail without
730    * exiting on error (just for this one command though).
731    */
732   if (*buf == '-') {
733     *exit_on_error_rtn = 0;
734     buf++;
735     goto again;
736   }
737
738   /* Get the command (cannot be quoted). */
739   len = strcspn (buf, " \t");
740
741   if (len == 0) {
742     pcmd.status = 0;
743     return pcmd;
744   }
745
746   pcmd.cmd = buf;
747   unsigned int i = 0;
748   if (buf[len] == '\0') {
749     pcmd.argv[0] = NULL;
750     pcmd.status = 1;
751     return pcmd;
752   }
753
754   buf[len] = '\0';
755   p = &buf[len+1];
756   p += strspn (p, " \t");
757
758   /* Get the parameters. */
759   while (*p && i < argv_len) {
760     tilde_candidate = 0;
761
762     /* Parameters which start with quotes or pipes are treated
763      * specially.  Bare parameters are delimited by whitespace.
764      */
765     if (*p == '"') {
766       p++;
767       len = parse_quoted_string (p);
768       if (len == -1) {
769         pcmd.status = -1;
770         return pcmd;
771       }
772       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
773         fprintf (stderr,
774                  _("%s: command arguments not separated by whitespace\n"),
775                  program_name);
776         pcmd.status = -1;
777         return pcmd;
778       }
779       pend = p[len+1] ? &p[len+2] : &p[len+1];
780     } else if (*p == '\'') {
781       p++;
782       len = strcspn (p, "'");
783       if (p[len] == '\0') {
784         fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
785         pcmd.status = -1;
786         return pcmd;
787       }
788       if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
789         fprintf (stderr,
790                  _("%s: command arguments not separated by whitespace\n"),
791                  program_name);
792         pcmd.status = -1;
793         return pcmd;
794       }
795       p[len] = '\0';
796       pend = p[len+1] ? &p[len+2] : &p[len+1];
797     } else if (*p == '|') {
798       *p = '\0';
799       pcmd.pipe = p+1;
800       continue;
801     } else if (*p != ' ' && *p != '\t') {
802       /* If the first character is a ~ then note that this parameter
803        * is a candidate for ~username expansion.  NB this does not
804        * apply to quoted parameters.
805        */
806       tilde_candidate = *p == '~';
807       len = strcspn (p, " \t");
808       if (p[len]) {
809         p[len] = '\0';
810         pend = &p[len+1];
811       } else
812         pend = &p[len];
813     } else {
814       fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
815                program_name, p);
816       abort ();
817     }
818
819     if (!tilde_candidate)
820       pcmd.argv[i] = p;
821     else
822       pcmd.argv[i] = try_tilde_expansion (p);
823     i++;
824     p = pend;
825
826     if (*p)
827       p += strspn (p, " \t");
828   }
829
830   if (i == argv_len) {
831     fprintf (stderr, _("%s: too many arguments\n"), program_name);
832     pcmd.status = -1;
833     return pcmd;
834   }
835
836   pcmd.argv[i] = NULL;
837
838   pcmd.status = 1;
839   return pcmd;
840 }
841
842 static int
843 hexdigit (char d)
844 {
845   switch (d) {
846   case '0'...'9': return d - '0';
847   case 'a'...'f': return d - 'a' + 10;
848   case 'A'...'F': return d - 'A' + 10;
849   default: return -1;
850   }
851 }
852
853 /* Parse double-quoted strings, replacing backslash escape sequences
854  * with the true character.  Since the string is returned in place,
855  * the escapes must make the string shorter.
856  */
857 static int
858 parse_quoted_string (char *p)
859 {
860   char *start = p;
861
862   for (; *p && *p != '"'; p++) {
863     if (*p == '\\') {
864       int m = 1, c;
865
866       switch (p[1]) {
867       case '\\': break;
868       case 'a': *p = '\a'; break;
869       case 'b': *p = '\b'; break;
870       case 'f': *p = '\f'; break;
871       case 'n': *p = '\n'; break;
872       case 'r': *p = '\r'; break;
873       case 't': *p = '\t'; break;
874       case 'v': *p = '\v'; break;
875       case '"': *p = '"'; break;
876       case '\'': *p = '\''; break;
877       case '?': *p = '?'; break;
878
879       case '0'...'7':           /* octal escape - always 3 digits */
880         m = 3;
881         if (p[2] >= '0' && p[2] <= '7' &&
882             p[3] >= '0' && p[3] <= '7') {
883           c = (p[1] - '0') * 0100 + (p[2] - '0') * 010 + (p[3] - '0');
884           if (c < 1 || c > 255)
885             goto error;
886           *p = c;
887         }
888         else
889           goto error;
890         break;
891
892       case 'x':                 /* hex escape - always 2 digits */
893         m = 3;
894         if (c_isxdigit (p[2]) && c_isxdigit (p[3])) {
895           c = hexdigit (p[2]) * 0x10 + hexdigit (p[3]);
896           if (c < 1 || c > 255)
897             goto error;
898           *p = c;
899         }
900         else
901           goto error;
902         break;
903
904       default:
905       error:
906         fprintf (stderr, _("%s: invalid escape sequence in string (starting at offset %d)\n"),
907                  program_name, (int) (p - start));
908         return -1;
909       }
910       memmove (p+1, p+1+m, strlen (p+1+m) + 1);
911     }
912   }
913
914   if (!*p) {
915     fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
916     return -1;
917   }
918
919   *p = '\0';
920   return p - start;
921 }
922
923 /* Used to handle "<!" (execute command and inline result). */
924 static int
925 execute_and_inline (const char *cmd, int global_exit_on_error)
926 {
927   FILE *pp;
928   char *line = NULL;
929   size_t len = 0;
930   ssize_t n;
931   int exit_on_error;
932   struct parsed_command pcmd;
933
934   pp = popen (cmd, "r");
935   if (!pp) {
936     perror ("popen");
937     return -1;
938   }
939
940   while ((n = getline (&line, &len, pp)) != -1) {
941     exit_on_error = global_exit_on_error;
942
943     /* Chomp final line ending which parse_command_line would not expect. */
944     if (n > 0 && line[n-1] == '\n')
945       line[n-1] = '\0';
946
947     pcmd = parse_command_line (line, &exit_on_error);
948     if (pcmd.status == -1 && exit_on_error)
949       exit (EXIT_FAILURE);
950     if (pcmd.status == 1) {
951       if (issue_command (pcmd.cmd, pcmd.argv, pcmd.pipe, exit_on_error) == -1) {
952         if (exit_on_error) exit (EXIT_FAILURE);
953       }
954     }
955   }
956
957   free (line);
958
959   if (pclose (pp) != 0) {
960     perror ("pclose");
961     return -1;
962   }
963
964   return 0;
965 }
966
967 static void
968 cmdline (char *argv[], int optind, int argc)
969 {
970   const char *cmd;
971   char **params;
972   int exit_on_error;
973
974   exit_on_error = 1;
975
976   if (optind >= argc) return;
977
978   cmd = argv[optind++];
979   if (STREQ (cmd, ":")) {
980     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
981     exit (EXIT_FAILURE);
982   }
983
984   /* Allow -cmd on the command line to mean (temporarily) override
985    * the normal exit on error (RHBZ#578407).
986    */
987   if (cmd[0] == '-') {
988     exit_on_error = 0;
989     cmd++;
990   }
991
992   params = &argv[optind];
993
994   /* Search for end of command list or ":" ... */
995   while (optind < argc && STRNEQ (argv[optind], ":"))
996     optind++;
997
998   if (optind == argc) {
999     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1000         exit (EXIT_FAILURE);
1001   } else {
1002     argv[optind] = NULL;
1003     if (issue_command (cmd, params, NULL, exit_on_error) == -1 && exit_on_error)
1004       exit (EXIT_FAILURE);
1005     cmdline (argv, optind+1, argc);
1006   }
1007 }
1008
1009 /* Note: 'rc_exit_on_error_flag' is the exit_on_error flag that we
1010  * pass to the remote server (when issuing --remote commands).  It
1011  * does not cause issue_command itself to exit on error.
1012  */
1013 int
1014 issue_command (const char *cmd, char *argv[], const char *pipecmd,
1015                int rc_exit_on_error_flag)
1016 {
1017   int argc;
1018   int stdout_saved_fd = -1;
1019   int pid = 0;
1020   int r;
1021
1022   if (progress_bars)
1023     progress_bar_reset (bar);
1024
1025   /* This counts the commands issued, starting at 1. */
1026   command_num++;
1027
1028   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
1029   if (pipecmd) {
1030     int fd[2];
1031
1032     if (fflush (stdout) == EOF) {
1033       perror ("failed to flush standard output");
1034       return -1;
1035     }
1036     if (pipe (fd) < 0) {
1037       perror ("pipe failed");
1038       return -1;
1039     }
1040     pid = fork ();
1041     if (pid == -1) {
1042       perror ("fork");
1043       return -1;
1044     }
1045
1046     if (pid == 0) {             /* Child process. */
1047       close (fd[1]);
1048       if (dup2 (fd[0], 0) < 0) {
1049         perror ("dup2 of stdin failed");
1050         _exit (1);
1051       }
1052
1053       r = system (pipecmd);
1054       if (r == -1) {
1055         perror (pipecmd);
1056         _exit (1);
1057       }
1058       _exit (WEXITSTATUS (r));
1059     }
1060
1061     if ((stdout_saved_fd = dup (1)) < 0) {
1062       perror ("failed to dup stdout");
1063       return -1;
1064     }
1065     close (fd[0]);
1066     if (dup2 (fd[1], 1) < 0) {
1067       perror ("failed to dup stdout");
1068       close (stdout_saved_fd);
1069       return -1;
1070     }
1071     close (fd[1]);
1072   }
1073
1074   for (argc = 0; argv[argc] != NULL; ++argc)
1075     ;
1076
1077   /* If --remote was set, then send this command to a remote process. */
1078   if (remote_control)
1079     r = rc_remote (remote_control, cmd, argc, argv, rc_exit_on_error_flag);
1080
1081   /* Otherwise execute it locally. */
1082   else if (STRCASEEQ (cmd, "help")) {
1083     if (argc == 0) {
1084       display_help ();
1085       r = 0;
1086     } else
1087       r = display_command (argv[0]);
1088   }
1089   else if (STRCASEEQ (cmd, "quit") ||
1090            STRCASEEQ (cmd, "exit") ||
1091            STRCASEEQ (cmd, "q")) {
1092     quit = 1;
1093     r = 0;
1094   }
1095   else
1096     r = run_action (cmd, argc, argv);
1097
1098   /* Always flush stdout after every command, so that messages, results
1099    * etc appear immediately.
1100    */
1101   if (fflush (stdout) == EOF) {
1102     perror ("failed to flush standard output");
1103     return -1;
1104   }
1105
1106   if (pipecmd) {
1107     close (1);
1108     if (dup2 (stdout_saved_fd, 1) < 0) {
1109       perror ("failed to dup2 standard output");
1110       r = -1;
1111     }
1112     close (stdout_saved_fd);
1113     if (waitpid (pid, NULL, 0) < 0) {
1114       perror ("waiting for command to complete");
1115       r = -1;
1116     }
1117   }
1118
1119   return r;
1120 }
1121
1122 void
1123 list_builtin_commands (void)
1124 {
1125   /* help and quit should appear at the top */
1126   printf ("%-20s %s\n",
1127           "help", _("display a list of commands or help on a command"));
1128   printf ("%-20s %s\n",
1129           "quit", _("quit guestfish"));
1130
1131   /* actions are printed after this (see list_commands) */
1132 }
1133
1134 int
1135 display_builtin_command (const char *cmd)
1136 {
1137   /* help for actions is auto-generated, see display_command */
1138
1139   if (STRCASEEQ (cmd, "help")) {
1140     printf (_("help - display a list of commands or help on a command\n"
1141               "     help cmd\n"
1142               "     help\n"));
1143     return 0;
1144   }
1145   else if (STRCASEEQ (cmd, "quit") ||
1146            STRCASEEQ (cmd, "exit") ||
1147            STRCASEEQ (cmd, "q")) {
1148     printf (_("quit - quit guestfish\n"
1149               "     quit\n"));
1150     return 0;
1151   }
1152   else {
1153     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1154              cmd);
1155     return -1;
1156   }
1157 }
1158
1159 /* This is printed when the user types in an unknown command for the
1160  * first command issued.  A common case is the user doing:
1161  *   guestfish disk.img
1162  * expecting guestfish to open 'disk.img' (in fact, this tried to
1163  * run a command 'disk.img').
1164  */
1165 void
1166 extended_help_message (void)
1167 {
1168   fprintf (stderr,
1169            _("Did you mean to open a disk image?  guestfish -a disk.img\n"
1170              "For a list of commands:             guestfish -h\n"
1171              "For complete documentation:         man guestfish\n"));
1172 }
1173
1174 void
1175 free_strings (char **argv)
1176 {
1177   int argc;
1178
1179   for (argc = 0; argv[argc] != NULL; ++argc)
1180     free (argv[argc]);
1181   free (argv);
1182 }
1183
1184 int
1185 count_strings (char *const *argv)
1186 {
1187   int c;
1188
1189   for (c = 0; argv[c]; ++c)
1190     ;
1191   return c;
1192 }
1193
1194 void
1195 print_strings (char *const *argv)
1196 {
1197   int argc;
1198
1199   for (argc = 0; argv[argc] != NULL; ++argc)
1200     printf ("%s\n", argv[argc]);
1201 }
1202
1203 void
1204 print_table (char *const *argv)
1205 {
1206   int i;
1207
1208   for (i = 0; argv[i] != NULL; i += 2)
1209     printf ("%s: %s\n", argv[i], argv[i+1]);
1210 }
1211
1212 int
1213 is_true (const char *str)
1214 {
1215   return
1216     STRCASENEQ (str, "0") &&
1217     STRCASENEQ (str, "f") &&
1218     STRCASENEQ (str, "false") &&
1219     STRCASENEQ (str, "n") &&
1220     STRCASENEQ (str, "no");
1221 }
1222
1223 /* Free strings from a non-NULL terminated char** */
1224 static void
1225 free_n_strings (char **str, size_t len)
1226 {
1227   size_t i;
1228
1229   for (i = 0; i < len; i++) {
1230     free (str[i]);
1231   }
1232   free (str);
1233 }
1234
1235 char **
1236 parse_string_list (const char *str)
1237 {
1238   char **argv = NULL;
1239   size_t argv_len = 0;
1240
1241   /* Current position pointer */
1242   const char *p = str;
1243
1244   /* Token might be simple:
1245    *  Token
1246    * or be quoted:
1247    *  'This is a single token'
1248    * or contain embedded single-quoted sections:
1249    *  This' is a sing'l'e to'ken
1250    *
1251    * The latter may seem over-complicated, but it's what a normal shell does.
1252    * Not doing it risks surprising somebody.
1253    *
1254    * This outer loop is over complete tokens.
1255    */
1256   while (*p) {
1257     char *tok = NULL;
1258     size_t tok_len = 0;
1259
1260     /* Skip leading whitespace */
1261     p += strspn (p, " \t");
1262
1263     char in_quote = 0;
1264
1265     /* This loop is over token 'fragments'. A token can be in multiple bits if
1266      * it contains single quotes. We also treat both sides of an escaped quote
1267      * as separate fragments because we can't just copy it: we have to remove
1268      * the \.
1269      */
1270     while (*p && (!c_isblank (*p) || in_quote)) {
1271       const char *end = p;
1272
1273       /* Check if the fragment starts with a quote */
1274       if ('\'' == *p) {
1275         /* Toggle in_quote */
1276         in_quote = !in_quote;
1277
1278         /* Skip the quote */
1279         p++; end++;
1280       }
1281
1282       /* If we're in a quote, look for an end quote */
1283       if (in_quote) {
1284         end += strcspn (end, "'");
1285       }
1286
1287       /* Otherwise, look for whitespace or a quote */
1288       else {
1289         end += strcspn (end, " \t'");
1290       }
1291
1292       /* Grow the token to accommodate the fragment */
1293       size_t tok_end = tok_len;
1294       tok_len += end - p;
1295       char *tok_new = realloc (tok, tok_len + 1);
1296       if (NULL == tok_new) {
1297         perror ("realloc");
1298         free_n_strings (argv, argv_len);
1299         free (tok);
1300         exit (EXIT_FAILURE);
1301       }
1302       tok = tok_new;
1303
1304       /* Check if we stopped on an escaped quote */
1305       if ('\'' == *end && end != p && *(end-1) == '\\') {
1306         /* Add everything before \' to the token */
1307         memcpy (&tok[tok_end], p, end - p - 1);
1308
1309         /* Add the quote */
1310         tok[tok_len-1] = '\'';
1311
1312         /* Already processed the quote */
1313         p = end + 1;
1314       }
1315
1316       else {
1317         /* Add the whole fragment */
1318         memcpy (&tok[tok_end], p, end - p);
1319
1320         p = end;
1321       }
1322     }
1323
1324     /* We've reached the end of a token. We shouldn't still be in quotes. */
1325     if (in_quote) {
1326       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1327       free_n_strings (argv, argv_len);
1328       free (tok);
1329       return NULL;
1330     }
1331
1332     /* Add this token if there is one. There might not be if there was
1333      * whitespace at the end of the input string */
1334     if (tok) {
1335       /* Add the NULL terminator */
1336       tok[tok_len] = '\0';
1337
1338       /* Add the argument to the argument list */
1339       argv_len++;
1340       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1341       if (NULL == argv_new) {
1342         perror ("realloc");
1343         free_n_strings (argv, argv_len-1);
1344         free (tok);
1345         exit (EXIT_FAILURE);
1346       }
1347       argv = argv_new;
1348
1349       argv[argv_len-1] = tok;
1350     }
1351   }
1352
1353   /* NULL terminate the argument list */
1354   argv_len++;
1355   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1356   if (NULL == argv_new) {
1357     perror ("realloc");
1358     free_n_strings (argv, argv_len-1);
1359     exit (EXIT_FAILURE);
1360   }
1361   argv = argv_new;
1362
1363   argv[argv_len-1] = NULL;
1364
1365   return argv;
1366 }
1367
1368 #ifdef HAVE_LIBREADLINE
1369 static char histfile[1024];
1370 static int nr_history_lines = 0;
1371 #endif
1372
1373 static void
1374 initialize_readline (void)
1375 {
1376 #ifdef HAVE_LIBREADLINE
1377   const char *home;
1378
1379   home = getenv ("HOME");
1380   if (home) {
1381     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1382     using_history ();
1383     (void) read_history (histfile);
1384   }
1385
1386   rl_readline_name = "guestfish";
1387   rl_attempted_completion_function = do_completion;
1388
1389   /* Note that .inputrc (or /etc/inputrc) is not read until the first
1390    * call the readline(), which happens later.  Therefore, these
1391    * provide default values which can be overridden by the user if
1392    * they wish.
1393    */
1394   (void) rl_variable_bind ("completion-ignore-case", "on");
1395 #endif
1396 }
1397
1398 static void
1399 cleanup_readline (void)
1400 {
1401 #ifdef HAVE_LIBREADLINE
1402   int fd;
1403
1404   if (histfile[0] != '\0') {
1405     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1406     if (fd == -1) {
1407       perror (histfile);
1408       return;
1409     }
1410     close (fd);
1411
1412 #ifdef HAVE_APPEND_HISTORY
1413     (void) append_history (nr_history_lines, histfile);
1414 #else
1415     (void) write_history (histfile);
1416 #endif
1417     clear_history ();
1418   }
1419 #endif
1420 }
1421
1422 #ifdef HAVE_LIBREADLINE
1423 static void
1424 add_history_line (const char *line)
1425 {
1426   add_history (line);
1427   nr_history_lines++;
1428 }
1429 #endif
1430
1431 int
1432 xwrite (int fd, const void *v_buf, size_t len)
1433 {
1434   int r;
1435   const char *buf = v_buf;
1436
1437   while (len > 0) {
1438     r = write (fd, buf, len);
1439     if (r == -1) {
1440       perror ("write");
1441       return -1;
1442     }
1443     buf += r;
1444     len -= r;
1445   }
1446
1447   return 0;
1448 }
1449
1450 /* Resolve the special "win:..." form for Windows-specific paths.  The
1451  * generated code calls this for all device or path arguments.
1452  *
1453  * The function returns a newly allocated string, and the caller must
1454  * free this string; else display an error and return NULL.
1455  */
1456 static char *win_prefix_drive_letter (char drive_letter, const char *path);
1457
1458 char *
1459 win_prefix (const char *path)
1460 {
1461   char *ret;
1462   size_t i;
1463
1464   /* If there is not a "win:..." prefix on the path, return strdup'd string. */
1465   if (STRCASENEQLEN (path, "win:", 4)) {
1466     ret = strdup (path);
1467     if (ret == NULL)
1468       perror ("strdup");
1469     return ret;
1470   }
1471
1472   path += 4;
1473
1474   /* If there is a drive letter, rewrite the path. */
1475   if (c_isalpha (path[0]) && path[1] == ':') {
1476     char drive_letter = c_tolower (path[0]);
1477     /* This returns the newly allocated string. */
1478     ret = win_prefix_drive_letter (drive_letter, path + 2);
1479     if (ret == NULL)
1480       return NULL;
1481   }
1482   else if (!*path) {
1483     ret = strdup ("/");
1484     if (ret == NULL) {
1485       perror ("strdup");
1486       return NULL;
1487     }
1488   }
1489   else {
1490     ret = strdup (path);
1491     if (ret == NULL) {
1492       perror ("strdup");
1493       return NULL;
1494     }
1495   }
1496
1497   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1498   for (i = 0; i < strlen (ret); ++i)
1499     if (ret[i] == '\\')
1500       ret[i] = '/';
1501
1502   char *t = guestfs_case_sensitive_path (g, ret);
1503   free (ret);
1504   ret = t;
1505
1506   return ret;
1507 }
1508
1509 static char *
1510 win_prefix_drive_letter (char drive_letter, const char *path)
1511 {
1512   char **roots = NULL;
1513   char **drives = NULL;
1514   char **mountpoints = NULL;
1515   char *device, *mountpoint, *ret = NULL;
1516   size_t i;
1517
1518   /* Resolve the drive letter using the drive mappings table. */
1519   roots = guestfs_inspect_get_roots (g);
1520   if (roots == NULL)
1521     goto out;
1522   if (roots[0] == NULL) {
1523     fprintf (stderr, _("%s: to use Windows drive letters, you must inspect the guest (\"-i\" option or run \"inspect-os\" command)\n"),
1524              program_name);
1525     goto out;
1526   }
1527   drives = guestfs_inspect_get_drive_mappings (g, roots[0]);
1528   if (drives == NULL || drives[0] == NULL) {
1529     fprintf (stderr, _("%s: to use Windows drive letters, this must be a Windows guest\n"),
1530              program_name);
1531     goto out;
1532   }
1533
1534   device = NULL;
1535   for (i = 0; drives[i] != NULL; i += 2) {
1536     if (c_tolower (drives[i][0]) == drive_letter && drives[i][1] == '\0') {
1537       device = drives[i+1];
1538       break;
1539     }
1540   }
1541
1542   if (device == NULL) {
1543     fprintf (stderr, _("%s: drive '%c:' not found.  To list available drives do:\n  inspect-get-drive-mappings %s\n"),
1544              program_name, drive_letter, roots[0]);
1545     goto out;
1546   }
1547
1548   /* This drive letter must be mounted somewhere (we won't do it). */
1549   mountpoints = guestfs_mountpoints (g);
1550   if (mountpoints == NULL)
1551     goto out;
1552
1553   mountpoint = NULL;
1554   for (i = 0; mountpoints[i] != NULL; i += 2) {
1555     if (STREQ (mountpoints[i], device)) {
1556       mountpoint = mountpoints[i+1];
1557       break;
1558     }
1559   }
1560
1561   if (mountpoint == NULL) {
1562     fprintf (stderr, _("%s: to access '%c:', mount %s first.  One way to do this is:\n  umount-all\n  mount %s /\n"),
1563              program_name, drive_letter, device, device);
1564     goto out;
1565   }
1566
1567   /* Rewrite the path, eg. if C: => /c then C:/foo => /c/foo */
1568   if (asprintf (&ret, "%s%s%s",
1569                 mountpoint, STRNEQ (mountpoint, "/") ? "/" : "", path) == -1) {
1570     perror ("asprintf");
1571     goto out;
1572   }
1573
1574  out:
1575   if (roots)
1576     free_strings (roots);
1577   if (drives)
1578     free_strings (drives);
1579   if (mountpoints)
1580     free_strings (mountpoints);
1581
1582   return ret;
1583 }
1584
1585 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1586  * The caller (cmds.c) will call free_file_in after the command has
1587  * run which should clean up resources.
1588  */
1589 static char *file_in_heredoc (const char *endmarker);
1590 static char *file_in_tmpfile = NULL;
1591
1592 char *
1593 file_in (const char *arg)
1594 {
1595   char *ret;
1596
1597   if (STREQ (arg, "-")) {
1598     ret = strdup ("/dev/stdin");
1599     if (!ret) {
1600       perror ("strdup");
1601       return NULL;
1602     }
1603   }
1604   else if (STRPREFIX (arg, "-<<")) {
1605     const char *endmarker = &arg[3];
1606     if (*endmarker == '\0') {
1607       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1608                program_name);
1609       return NULL;
1610     }
1611     ret = file_in_heredoc (endmarker);
1612     if (ret == NULL)
1613       return NULL;
1614   }
1615   else {
1616     ret = strdup (arg);
1617     if (!ret) {
1618       perror ("strdup");
1619       return NULL;
1620     }
1621   }
1622
1623   return ret;
1624 }
1625
1626 static char *
1627 file_in_heredoc (const char *endmarker)
1628 {
1629   TMP_TEMPLATE_ON_STACK (template);
1630   file_in_tmpfile = strdup (template);
1631   if (file_in_tmpfile == NULL) {
1632     perror ("strdup");
1633     return NULL;
1634   }
1635
1636   int fd = mkstemp (file_in_tmpfile);
1637   if (fd == -1) {
1638     perror ("mkstemp");
1639     goto error1;
1640   }
1641
1642   size_t markerlen = strlen (endmarker);
1643
1644   char buffer[BUFSIZ];
1645   int write_error = 0;
1646   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1647     /* Look for "END"<EOF> or "END\n" in input. */
1648     size_t blen = strlen (buffer);
1649     if (STREQLEN (buffer, endmarker, markerlen) &&
1650         (blen == markerlen ||
1651          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1652       goto found_end;
1653
1654     if (xwrite (fd, buffer, blen) == -1) {
1655       if (!write_error) perror ("write");
1656       write_error = 1;
1657       /* continue reading up to the end marker */
1658     }
1659   }
1660
1661   /* Reached EOF of stdin without finding the end marker, which
1662    * is likely to be an error.
1663    */
1664   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1665            program_name, endmarker);
1666   goto error2;
1667
1668  found_end:
1669   if (write_error) {
1670     close (fd);
1671     goto error2;
1672   }
1673
1674   if (close (fd) == -1) {
1675     perror ("close");
1676     goto error2;
1677   }
1678
1679   return file_in_tmpfile;
1680
1681  error2:
1682   unlink (file_in_tmpfile);
1683
1684  error1:
1685   free (file_in_tmpfile);
1686   file_in_tmpfile = NULL;
1687   return NULL;
1688 }
1689
1690 void
1691 free_file_in (char *s)
1692 {
1693   if (file_in_tmpfile) {
1694     if (unlink (file_in_tmpfile) == -1)
1695       perror (file_in_tmpfile);
1696     file_in_tmpfile = NULL;
1697   }
1698
1699   /* Free the device or file name which was strdup'd in file_in().
1700    * Note it's not immediately clear, but for -<< heredocs,
1701    * s == file_in_tmpfile, so this frees up that buffer.
1702    */
1703   free (s);
1704 }
1705
1706 /* Resolve the special FileOut paths ("-" or filename).
1707  * The caller (cmds.c) will call free (str) after the command has run.
1708  */
1709 char *
1710 file_out (const char *arg)
1711 {
1712   char *ret;
1713
1714   if (STREQ (arg, "-"))
1715     ret = strdup ("/dev/stdout");
1716   else
1717     ret = strdup (arg);
1718
1719   if (!ret) {
1720     perror ("strdup");
1721     return NULL;
1722   }
1723   return ret;
1724 }
1725
1726 /* Callback which displays a progress bar. */
1727 void
1728 progress_callback (guestfs_h *g, void *data,
1729                    uint64_t event, int event_handle, int flags,
1730                    const char *buf, size_t buf_len,
1731                    const uint64_t *array, size_t array_len)
1732 {
1733   if (array_len < 4)
1734     return;
1735
1736   /*uint64_t proc_nr = array[0];*/
1737   /*uint64_t serial = array[1];*/
1738   uint64_t position = array[2];
1739   uint64_t total = array[3];
1740
1741   progress_bar_set (bar, position, total);
1742 }