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