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