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