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