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