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