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