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