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