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