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