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