4a7e70b82fdacbe04e49f150844cda7f40956c76
[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     prepare_drive (drv->filename, drv->data, drv->device);
554   }
555 }
556
557 static void
558 interactive (void)
559 {
560   script (1);
561 }
562
563 static void
564 shell_script (void)
565 {
566   script (0);
567 }
568
569 #define FISH "><fs> "
570
571 static char *line_read = NULL;
572
573 static char *
574 rl_gets (int prompt)
575 {
576 #ifdef HAVE_LIBREADLINE
577
578   if (prompt) {
579     if (line_read) {
580       free (line_read);
581       line_read = NULL;
582     }
583
584     line_read = readline (prompt ? FISH : "");
585
586     if (line_read && *line_read)
587       add_history_line (line_read);
588
589     return line_read;
590   }
591
592 #endif /* HAVE_LIBREADLINE */
593
594   static char buf[8192];
595   int len;
596
597   if (prompt) printf (FISH);
598   line_read = fgets (buf, sizeof buf, stdin);
599
600   if (line_read) {
601     len = strlen (line_read);
602     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
603   }
604
605   return line_read;
606 }
607
608 static void
609 script (int prompt)
610 {
611   char *buf;
612   char *cmd;
613   char *p, *pend;
614   char *argv[64];
615   int len;
616   int global_exit_on_error = !prompt;
617   int tilde_candidate;
618
619   if (prompt)
620     printf (_("\n"
621               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
622               "editing virtual machine filesystems.\n"
623               "\n"
624               "Type: 'help' for help with commands\n"
625               "      'quit' to quit the shell\n"
626               "\n"));
627
628   while (!quit) {
629     char *pipe = NULL;
630
631     exit_on_error = global_exit_on_error;
632
633     buf = rl_gets (prompt);
634     if (!buf) {
635       quit = 1;
636       break;
637     }
638
639     /* Skip any initial whitespace before the command. */
640   again:
641     while (*buf && c_isspace (*buf))
642       buf++;
643
644     if (!*buf) continue;
645
646     /* If the next character is '#' then this is a comment. */
647     if (*buf == '#') continue;
648
649     /* If the next character is '!' then pass the whole lot to system(3). */
650     if (*buf == '!') {
651       int r;
652
653       r = system (buf+1);
654       if (exit_on_error) {
655         if (r == -1 ||
656             (WIFSIGNALED (r) &&
657              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
658             WEXITSTATUS (r) != 0)
659           exit (EXIT_FAILURE);
660       }
661       continue;
662     }
663
664     /* If the next character is '-' allow the command to fail without
665      * exiting on error (just for this one command though).
666      */
667     if (*buf == '-') {
668       exit_on_error = 0;
669       buf++;
670       goto again;
671     }
672
673     /* Get the command (cannot be quoted). */
674     len = strcspn (buf, " \t");
675
676     if (len == 0) continue;
677
678     cmd = buf;
679     unsigned int i = 0;
680     if (buf[len] == '\0') {
681       argv[0] = NULL;
682       goto got_command;
683     }
684
685     buf[len] = '\0';
686     p = &buf[len+1];
687     p += strspn (p, " \t");
688
689     /* Get the parameters. */
690     while (*p && i < sizeof argv / sizeof argv[0]) {
691       tilde_candidate = 0;
692
693       /* Parameters which start with quotes or pipes are treated
694        * specially.  Bare parameters are delimited by whitespace.
695        */
696       if (*p == '"') {
697         p++;
698         len = strcspn (p, "\"");
699         if (p[len] == '\0') {
700           fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
701           if (exit_on_error) exit (EXIT_FAILURE);
702           goto next_command;
703         }
704         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
705           fprintf (stderr,
706                    _("%s: command arguments not separated by whitespace\n"),
707                    program_name);
708           if (exit_on_error) exit (EXIT_FAILURE);
709           goto next_command;
710         }
711         p[len] = '\0';
712         pend = p[len+1] ? &p[len+2] : &p[len+1];
713       } else if (*p == '\'') {
714         p++;
715         len = strcspn (p, "'");
716         if (p[len] == '\0') {
717           fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
718           if (exit_on_error) exit (EXIT_FAILURE);
719           goto next_command;
720         }
721         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
722           fprintf (stderr,
723                    _("%s: command arguments not separated by whitespace\n"),
724                    program_name);
725           if (exit_on_error) exit (EXIT_FAILURE);
726           goto next_command;
727         }
728         p[len] = '\0';
729         pend = p[len+1] ? &p[len+2] : &p[len+1];
730       } else if (*p == '|') {
731         *p = '\0';
732         pipe = p+1;
733         continue;
734         /*
735       } else if (*p == '[') {
736         int c = 1;
737         p++;
738         pend = p;
739         while (*pend && c != 0) {
740           if (*pend == '[') c++;
741           else if (*pend == ']') c--;
742           pend++;
743         }
744         if (c != 0) {
745           fprintf (stderr,
746                    _("%s: unterminated \"[...]\" sequence\n"), program_name);
747           if (exit_on_error) exit (EXIT_FAILURE);
748           goto next_command;
749         }
750         if (*pend && (*pend != ' ' && *pend != '\t')) {
751           fprintf (stderr,
752                    _("%s: command arguments not separated by whitespace\n"),
753                    program_name);
754           if (exit_on_error) exit (EXIT_FAILURE);
755           goto next_command;
756         }
757         *(pend-1) = '\0';
758         */
759       } else if (*p != ' ' && *p != '\t') {
760         /* If the first character is a ~ then note that this parameter
761          * is a candidate for ~username expansion.  NB this does not
762          * apply to quoted parameters.
763          */
764         tilde_candidate = *p == '~';
765         len = strcspn (p, " \t");
766         if (p[len]) {
767           p[len] = '\0';
768           pend = &p[len+1];
769         } else
770           pend = &p[len];
771       } else {
772         fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
773                  program_name, p);
774         abort ();
775       }
776
777       if (!tilde_candidate)
778         argv[i] = p;
779       else
780         argv[i] = try_tilde_expansion (p);
781       i++;
782       p = pend;
783
784       if (*p)
785         p += strspn (p, " \t");
786     }
787
788     if (i == sizeof argv / sizeof argv[0]) {
789       fprintf (stderr, _("%s: too many arguments\n"), program_name);
790       if (exit_on_error) exit (EXIT_FAILURE);
791       goto next_command;
792     }
793
794     argv[i] = NULL;
795
796   got_command:
797     if (issue_command (cmd, argv, pipe) == -1) {
798       if (exit_on_error) exit (EXIT_FAILURE);
799     }
800
801   next_command:;
802   }
803   if (prompt) printf ("\n");
804 }
805
806 static void
807 cmdline (char *argv[], int optind, int argc)
808 {
809   const char *cmd;
810   char **params;
811
812   exit_on_error = 1;
813
814   if (optind >= argc) return;
815
816   cmd = argv[optind++];
817   if (STREQ (cmd, ":")) {
818     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
819     exit (EXIT_FAILURE);
820   }
821
822   /* Allow -cmd on the command line to mean (temporarily) override
823    * the normal exit on error (RHBZ#578407).
824    */
825   if (cmd[0] == '-') {
826     exit_on_error = 0;
827     cmd++;
828   }
829
830   params = &argv[optind];
831
832   /* Search for end of command list or ":" ... */
833   while (optind < argc && STRNEQ (argv[optind], ":"))
834     optind++;
835
836   if (optind == argc) {
837     if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
838         exit (EXIT_FAILURE);
839   } else {
840     argv[optind] = NULL;
841     if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
842       exit (EXIT_FAILURE);
843     cmdline (argv, optind+1, argc);
844   }
845 }
846
847 int
848 issue_command (const char *cmd, char *argv[], const char *pipecmd)
849 {
850   int argc;
851   int stdout_saved_fd = -1;
852   int pid = 0;
853   int i, r;
854
855   /* This counts the commands issued, starting at 1. */
856   command_num++;
857
858   if (echo_commands) {
859     printf ("%s", cmd);
860     for (i = 0; argv[i] != NULL; ++i)
861       printf (" %s", argv[i]);
862     printf ("\n");
863   }
864
865   /* For | ... commands.  Annoyingly we can't use popen(3) here. */
866   if (pipecmd) {
867     int fd[2];
868
869     if (fflush (stdout) == EOF) {
870       perror ("failed to flush standard output");
871       return -1;
872     }
873     if (pipe (fd) < 0) {
874       perror ("pipe failed");
875       return -1;
876     }
877     pid = fork ();
878     if (pid == -1) {
879       perror ("fork");
880       return -1;
881     }
882
883     if (pid == 0) {             /* Child process. */
884       close (fd[1]);
885       if (dup2 (fd[0], 0) < 0) {
886         perror ("dup2 of stdin failed");
887         _exit (1);
888       }
889
890       r = system (pipecmd);
891       if (r == -1) {
892         perror (pipecmd);
893         _exit (1);
894       }
895       _exit (WEXITSTATUS (r));
896     }
897
898     if ((stdout_saved_fd = dup (1)) < 0) {
899       perror ("failed to dup stdout");
900       return -1;
901     }
902     close (fd[0]);
903     if (dup2 (fd[1], 1) < 0) {
904       perror ("failed to dup stdout");
905       close (stdout_saved_fd);
906       return -1;
907     }
908     close (fd[1]);
909   }
910
911   for (argc = 0; argv[argc] != NULL; ++argc)
912     ;
913
914   /* If --remote was set, then send this command to a remote process. */
915   if (remote_control)
916     r = rc_remote (remote_control, cmd, argc, argv, exit_on_error);
917
918   /* Otherwise execute it locally. */
919   else if (STRCASEEQ (cmd, "help")) {
920     if (argc == 0)
921       list_commands ();
922     else
923       display_command (argv[0]);
924     r = 0;
925   }
926   else if (STRCASEEQ (cmd, "quit") ||
927            STRCASEEQ (cmd, "exit") ||
928            STRCASEEQ (cmd, "q")) {
929     quit = 1;
930     r = 0;
931   }
932   else if (STRCASEEQ (cmd, "alloc") ||
933            STRCASEEQ (cmd, "allocate"))
934     r = do_alloc (cmd, argc, argv);
935   else if (STRCASEEQ (cmd, "echo"))
936     r = do_echo (cmd, argc, argv);
937   else if (STRCASEEQ (cmd, "edit") ||
938            STRCASEEQ (cmd, "vi") ||
939            STRCASEEQ (cmd, "emacs"))
940     r = do_edit (cmd, argc, argv);
941   else if (STRCASEEQ (cmd, "lcd"))
942     r = do_lcd (cmd, argc, argv);
943   else if (STRCASEEQ (cmd, "glob"))
944     r = do_glob (cmd, argc, argv);
945   else if (STRCASEEQ (cmd, "more") ||
946            STRCASEEQ (cmd, "less"))
947     r = do_more (cmd, argc, argv);
948   else if (STRCASEEQ (cmd, "reopen"))
949     r = do_reopen (cmd, argc, argv);
950   else if (STRCASEEQ (cmd, "sparse"))
951     r = do_sparse (cmd, argc, argv);
952   else if (STRCASEEQ (cmd, "time"))
953     r = do_time (cmd, argc, argv);
954   else
955     r = run_action (cmd, argc, argv);
956
957   /* Always flush stdout after every command, so that messages, results
958    * etc appear immediately.
959    */
960   if (fflush (stdout) == EOF) {
961     perror ("failed to flush standard output");
962     return -1;
963   }
964
965   if (pipecmd) {
966     close (1);
967     if (dup2 (stdout_saved_fd, 1) < 0) {
968       perror ("failed to dup2 standard output");
969       r = -1;
970     }
971     close (stdout_saved_fd);
972     if (waitpid (pid, NULL, 0) < 0) {
973       perror ("waiting for command to complete");
974       r = -1;
975     }
976   }
977
978   return r;
979 }
980
981 void
982 list_builtin_commands (void)
983 {
984   /* help and quit should appear at the top */
985   printf ("%-20s %s\n",
986           "help", _("display a list of commands or help on a command"));
987   printf ("%-20s %s\n",
988           "quit", _("quit guestfish"));
989
990   printf ("%-20s %s\n",
991           "alloc", _("allocate an image"));
992   printf ("%-20s %s\n",
993           "echo", _("display a line of text"));
994   printf ("%-20s %s\n",
995           "edit", _("edit a file in the image"));
996   printf ("%-20s %s\n",
997           "lcd", _("local change directory"));
998   printf ("%-20s %s\n",
999           "glob", _("expand wildcards in command"));
1000   printf ("%-20s %s\n",
1001           "more", _("view a file in the pager"));
1002   printf ("%-20s %s\n",
1003           "reopen", _("close and reopen libguestfs handle"));
1004   printf ("%-20s %s\n",
1005           "sparse", _("allocate a sparse image file"));
1006   printf ("%-20s %s\n",
1007           "time", _("measure time taken to run command"));
1008
1009   /* actions are printed after this (see list_commands) */
1010 }
1011
1012 void
1013 display_builtin_command (const char *cmd)
1014 {
1015   /* help for actions is auto-generated, see display_command */
1016
1017   if (STRCASEEQ (cmd, "alloc") ||
1018       STRCASEEQ (cmd, "allocate"))
1019     printf (_("alloc - allocate an image\n"
1020               "     alloc <filename> <size>\n"
1021               "\n"
1022               "    This creates an empty (zeroed) file of the given size,\n"
1023               "    and then adds so it can be further examined.\n"
1024               "\n"
1025               "    For more advanced image creation, see qemu-img utility.\n"
1026               "\n"
1027               "    Size can be specified (where <nn> means a number):\n"
1028               "    <nn>             number of kilobytes\n"
1029               "      eg: 1440       standard 3.5\" floppy\n"
1030               "    <nn>K or <nn>KB  number of kilobytes\n"
1031               "    <nn>M or <nn>MB  number of megabytes\n"
1032               "    <nn>G or <nn>GB  number of gigabytes\n"
1033               "    <nn>T or <nn>TB  number of terabytes\n"
1034               "    <nn>P or <nn>PB  number of petabytes\n"
1035               "    <nn>E or <nn>EB  number of exabytes\n"
1036               "    <nn>sects        number of 512 byte sectors\n"));
1037   else if (STRCASEEQ (cmd, "echo"))
1038     printf (_("echo - display a line of text\n"
1039               "     echo [<params> ...]\n"
1040               "\n"
1041               "    This echos the parameters to the terminal.\n"));
1042   else if (STRCASEEQ (cmd, "edit") ||
1043            STRCASEEQ (cmd, "vi") ||
1044            STRCASEEQ (cmd, "emacs"))
1045     printf (_("edit - edit a file in the image\n"
1046               "     edit <filename>\n"
1047               "\n"
1048               "    This is used to edit a file.\n"
1049               "\n"
1050               "    It is the equivalent of (and is implemented by)\n"
1051               "    running \"cat\", editing locally, and then \"write-file\".\n"
1052               "\n"
1053               "    Normally it uses $EDITOR, but if you use the aliases\n"
1054               "    \"vi\" or \"emacs\" you will get those editors.\n"
1055               "\n"
1056               "    NOTE: This will not work reliably for large files\n"
1057               "    (> 2 MB) or binary files containing \\0 bytes.\n"));
1058   else if (STRCASEEQ (cmd, "lcd"))
1059     printf (_("lcd - local change directory\n"
1060               "    lcd <directory>\n"
1061               "\n"
1062               "    Change guestfish's current directory. This command is\n"
1063               "    useful if you want to download files to a particular\n"
1064               "    place.\n"));
1065   else if (STRCASEEQ (cmd, "glob"))
1066     printf (_("glob - expand wildcards in command\n"
1067               "    glob <command> [<args> ...]\n"
1068               "\n"
1069               "    Glob runs <command> with wildcards expanded in any\n"
1070               "    command args.  Note that the command is run repeatedly\n"
1071               "    once for each expanded argument.\n"));
1072   else if (STRCASEEQ (cmd, "help"))
1073     printf (_("help - display a list of commands or help on a command\n"
1074               "     help cmd\n"
1075               "     help\n"));
1076   else if (STRCASEEQ (cmd, "more") ||
1077            STRCASEEQ (cmd, "less"))
1078     printf (_("more - view a file in the pager\n"
1079               "     more <filename>\n"
1080               "\n"
1081               "    This is used to view a file in the pager.\n"
1082               "\n"
1083               "    It is the equivalent of (and is implemented by)\n"
1084               "    running \"cat\" and using the pager.\n"
1085               "\n"
1086               "    Normally it uses $PAGER, but if you use the alias\n"
1087               "    \"less\" then it always uses \"less\".\n"
1088               "\n"
1089               "    NOTE: This will not work reliably for large files\n"
1090               "    (> 2 MB) or binary files containing \\0 bytes.\n"));
1091   else if (STRCASEEQ (cmd, "quit") ||
1092            STRCASEEQ (cmd, "exit") ||
1093            STRCASEEQ (cmd, "q"))
1094     printf (_("quit - quit guestfish\n"
1095               "     quit\n"));
1096   else if (STRCASEEQ (cmd, "reopen"))
1097     printf (_("reopen - close and reopen the libguestfs handle\n"
1098               "     reopen\n"
1099               "\n"
1100               "Close and reopen the libguestfs handle.  It is not necessary to use\n"
1101               "this normally, because the handle is closed properly when guestfish\n"
1102               "exits.  However this is occasionally useful for testing.\n"));
1103   else if (STRCASEEQ (cmd, "sparse"))
1104     printf (_("sparse - allocate a sparse image file\n"
1105               "     sparse <filename> <size>\n"
1106               "\n"
1107               "    This creates an empty sparse file of the given size,\n"
1108               "    and then adds so it can be further examined.\n"
1109               "\n"
1110               "    In all respects it works the same as the 'alloc'\n"
1111               "    command, except that the image file is allocated\n"
1112               "    sparsely, which means that disk blocks are not assigned\n"
1113               "    to the file until they are needed.  Sparse disk files\n"
1114               "    only use space when written to, but they are slower\n"
1115               "    and there is a danger you could run out of real disk\n"
1116               "    space during a write operation.\n"
1117               "\n"
1118               "    For more advanced image creation, see qemu-img utility.\n"
1119               "\n"
1120               "    Size can be specified (where <nn> means a number):\n"
1121               "    <nn>             number of kilobytes\n"
1122               "      eg: 1440       standard 3.5\" floppy\n"
1123               "    <nn>K or <nn>KB  number of kilobytes\n"
1124               "    <nn>M or <nn>MB  number of megabytes\n"
1125               "    <nn>G or <nn>GB  number of gigabytes\n"
1126               "    <nn>T or <nn>TB  number of terabytes\n"
1127               "    <nn>P or <nn>PB  number of petabytes\n"
1128               "    <nn>E or <nn>EB  number of exabytes\n"
1129               "    <nn>sects        number of 512 byte sectors\n"));
1130   else if (STRCASEEQ (cmd, "time"))
1131     printf (_("time - measure time taken to run command\n"
1132               "    time <command> [<args> ...]\n"
1133               "\n"
1134               "    This runs <command> as usual, and prints the elapsed\n"
1135               "    time afterwards.\n"));
1136   else
1137     fprintf (stderr, _("%s: command not known, use -h to list all commands\n"),
1138              cmd);
1139 }
1140
1141 /* This is printed when the user types in an unknown command for the
1142  * first command issued.  A common case is the user doing:
1143  *   guestfish disk.img
1144  * expecting guestfish to open 'disk.img' (in fact, this tried to
1145  * run a command 'disk.img').
1146  */
1147 void
1148 extended_help_message (void)
1149 {
1150   fprintf (stderr,
1151            _("Did you mean to open a disk image?  guestfish -a disk.img\n"
1152              "For a list of commands:             guestfish -h\n"
1153              "For complete documentation:         man guestfish\n"));
1154 }
1155
1156 void
1157 free_strings (char **argv)
1158 {
1159   int argc;
1160
1161   for (argc = 0; argv[argc] != NULL; ++argc)
1162     free (argv[argc]);
1163   free (argv);
1164 }
1165
1166 int
1167 count_strings (char *const *argv)
1168 {
1169   int c;
1170
1171   for (c = 0; argv[c]; ++c)
1172     ;
1173   return c;
1174 }
1175
1176 void
1177 print_strings (char *const *argv)
1178 {
1179   int argc;
1180
1181   for (argc = 0; argv[argc] != NULL; ++argc)
1182     printf ("%s\n", argv[argc]);
1183 }
1184
1185 void
1186 print_table (char *const *argv)
1187 {
1188   int i;
1189
1190   for (i = 0; argv[i] != NULL; i += 2)
1191     printf ("%s: %s\n", argv[i], argv[i+1]);
1192 }
1193
1194 int
1195 is_true (const char *str)
1196 {
1197   return
1198     STRCASENEQ (str, "0") &&
1199     STRCASENEQ (str, "f") &&
1200     STRCASENEQ (str, "false") &&
1201     STRCASENEQ (str, "n") &&
1202     STRCASENEQ (str, "no");
1203 }
1204
1205 /* Free strings from a non-NULL terminated char** */
1206 static void
1207 free_n_strings (char **str, size_t len)
1208 {
1209   size_t i;
1210
1211   for (i = 0; i < len; i++) {
1212     free (str[i]);
1213   }
1214   free (str);
1215 }
1216
1217 char **
1218 parse_string_list (const char *str)
1219 {
1220   char **argv = NULL;
1221   size_t argv_len = 0;
1222
1223   /* Current position pointer */
1224   const char *p = str;
1225
1226   /* Token might be simple:
1227    *  Token
1228    * or be quoted:
1229    *  'This is a single token'
1230    * or contain embedded single-quoted sections:
1231    *  This' is a sing'l'e to'ken
1232    *
1233    * The latter may seem over-complicated, but it's what a normal shell does.
1234    * Not doing it risks surprising somebody.
1235    *
1236    * This outer loop is over complete tokens.
1237    */
1238   while (*p) {
1239     char *tok = NULL;
1240     size_t tok_len = 0;
1241
1242     /* Skip leading whitespace */
1243     p += strspn (p, " \t");
1244
1245     char in_quote = 0;
1246
1247     /* This loop is over token 'fragments'. A token can be in multiple bits if
1248      * it contains single quotes. We also treat both sides of an escaped quote
1249      * as separate fragments because we can't just copy it: we have to remove
1250      * the \.
1251      */
1252     while (*p && (!c_isblank (*p) || in_quote)) {
1253       const char *end = p;
1254
1255       /* Check if the fragment starts with a quote */
1256       if ('\'' == *p) {
1257         /* Toggle in_quote */
1258         in_quote = !in_quote;
1259
1260         /* Skip the quote */
1261         p++; end++;
1262       }
1263
1264       /* If we're in a quote, look for an end quote */
1265       if (in_quote) {
1266         end += strcspn (end, "'");
1267       }
1268
1269       /* Otherwise, look for whitespace or a quote */
1270       else {
1271         end += strcspn (end, " \t'");
1272       }
1273
1274       /* Grow the token to accommodate the fragment */
1275       size_t tok_end = tok_len;
1276       tok_len += end - p;
1277       char *tok_new = realloc (tok, tok_len + 1);
1278       if (NULL == tok_new) {
1279         perror ("realloc");
1280         free_n_strings (argv, argv_len);
1281         free (tok);
1282         exit (EXIT_FAILURE);
1283       }
1284       tok = tok_new;
1285
1286       /* Check if we stopped on an escaped quote */
1287       if ('\'' == *end && end != p && *(end-1) == '\\') {
1288         /* Add everything before \' to the token */
1289         memcpy (&tok[tok_end], p, end - p - 1);
1290
1291         /* Add the quote */
1292         tok[tok_len-1] = '\'';
1293
1294         /* Already processed the quote */
1295         p = end + 1;
1296       }
1297
1298       else {
1299         /* Add the whole fragment */
1300         memcpy (&tok[tok_end], p, end - p);
1301
1302         p = end;
1303       }
1304     }
1305
1306     /* We've reached the end of a token. We shouldn't still be in quotes. */
1307     if (in_quote) {
1308       fprintf (stderr, _("Runaway quote in string \"%s\"\n"), str);
1309
1310       free_n_strings (argv, argv_len);
1311
1312       return NULL;
1313     }
1314
1315     /* Add this token if there is one. There might not be if there was
1316      * whitespace at the end of the input string */
1317     if (tok) {
1318       /* Add the NULL terminator */
1319       tok[tok_len] = '\0';
1320
1321       /* Add the argument to the argument list */
1322       argv_len++;
1323       char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1324       if (NULL == argv_new) {
1325         perror ("realloc");
1326         free_n_strings (argv, argv_len-1);
1327         free (tok);
1328         exit (EXIT_FAILURE);
1329       }
1330       argv = argv_new;
1331
1332       argv[argv_len-1] = tok;
1333     }
1334   }
1335
1336   /* NULL terminate the argument list */
1337   argv_len++;
1338   char **argv_new = realloc (argv, sizeof (*argv) * argv_len);
1339   if (NULL == argv_new) {
1340     perror ("realloc");
1341     free_n_strings (argv, argv_len-1);
1342     exit (EXIT_FAILURE);
1343   }
1344   argv = argv_new;
1345
1346   argv[argv_len-1] = NULL;
1347
1348   return argv;
1349 }
1350
1351 #ifdef HAVE_LIBREADLINE
1352 static char histfile[1024];
1353 static int nr_history_lines = 0;
1354 #endif
1355
1356 static void
1357 initialize_readline (void)
1358 {
1359 #ifdef HAVE_LIBREADLINE
1360   const char *home;
1361
1362   home = getenv ("HOME");
1363   if (home) {
1364     snprintf (histfile, sizeof histfile, "%s/.guestfish", home);
1365     using_history ();
1366     (void) read_history (histfile);
1367   }
1368
1369   rl_readline_name = "guestfish";
1370   rl_attempted_completion_function = do_completion;
1371 #endif
1372 }
1373
1374 static void
1375 cleanup_readline (void)
1376 {
1377 #ifdef HAVE_LIBREADLINE
1378   int fd;
1379
1380   if (histfile[0] != '\0') {
1381     fd = open (histfile, O_WRONLY|O_CREAT, 0644);
1382     if (fd == -1) {
1383       perror (histfile);
1384       return;
1385     }
1386     close (fd);
1387
1388 #ifdef HAVE_APPEND_HISTORY
1389     (void) append_history (nr_history_lines, histfile);
1390 #else
1391     (void) write_history (histfile);
1392 #endif
1393   }
1394 #endif
1395 }
1396
1397 static void
1398 add_history_line (const char *line)
1399 {
1400 #ifdef HAVE_LIBREADLINE
1401   add_history (line);
1402   nr_history_lines++;
1403 #endif
1404 }
1405
1406 int
1407 xwrite (int fd, const void *v_buf, size_t len)
1408 {
1409   int r;
1410   const char *buf = v_buf;
1411
1412   while (len > 0) {
1413     r = write (fd, buf, len);
1414     if (r == -1) {
1415       perror ("write");
1416       return -1;
1417     }
1418     buf += r;
1419     len -= r;
1420   }
1421
1422   return 0;
1423 }
1424
1425 /* Resolve the special "win:..." form for Windows-specific paths.
1426  * This always returns a newly allocated string which is freed by the
1427  * caller function in "cmds.c".
1428  */
1429 char *
1430 resolve_win_path (const char *path)
1431 {
1432   char *ret;
1433   size_t i;
1434
1435   if (STRCASENEQLEN (path, "win:", 4)) {
1436     ret = strdup (path);
1437     if (ret == NULL)
1438       perror ("strdup");
1439     return ret;
1440   }
1441
1442   path += 4;
1443
1444   /* Drop drive letter, if it's "C:". */
1445   if (STRCASEEQLEN (path, "c:", 2))
1446     path += 2;
1447
1448   if (!*path) {
1449     ret = strdup ("/");
1450     if (ret == NULL)
1451       perror ("strdup");
1452     return ret;
1453   }
1454
1455   ret = strdup (path);
1456   if (ret == NULL) {
1457     perror ("strdup");
1458     return NULL;
1459   }
1460
1461   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1462   for (i = 0; i < strlen (ret); ++i)
1463     if (ret[i] == '\\')
1464       ret[i] = '/';
1465
1466   char *t = guestfs_case_sensitive_path (g, ret);
1467   free (ret);
1468   ret = t;
1469
1470   return ret;
1471 }
1472
1473 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1474  * The caller (cmds.c) will call free_file_in after the command has
1475  * run which should clean up resources.
1476  */
1477 static char *file_in_heredoc (const char *endmarker);
1478 static char *file_in_tmpfile = NULL;
1479
1480 char *
1481 file_in (const char *arg)
1482 {
1483   char *ret;
1484
1485   if (STREQ (arg, "-")) {
1486     ret = strdup ("/dev/stdin");
1487     if (!ret) {
1488       perror ("strdup");
1489       return NULL;
1490     }
1491   }
1492   else if (STRPREFIX (arg, "-<<")) {
1493     const char *endmarker = &arg[3];
1494     if (*endmarker == '\0') {
1495       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1496                program_name);
1497       return NULL;
1498     }
1499     ret = file_in_heredoc (endmarker);
1500     if (ret == NULL)
1501       return NULL;
1502   }
1503   else {
1504     ret = strdup (arg);
1505     if (!ret) {
1506       perror ("strdup");
1507       return NULL;
1508     }
1509   }
1510
1511   return ret;
1512 }
1513
1514 static char *
1515 file_in_heredoc (const char *endmarker)
1516 {
1517   static const char template[] = "/tmp/heredocXXXXXX";
1518   file_in_tmpfile = strdup (template);
1519   if (file_in_tmpfile == NULL) {
1520     perror ("strdup");
1521     return NULL;
1522   }
1523
1524   int fd = mkstemp (file_in_tmpfile);
1525   if (fd == -1) {
1526     perror ("mkstemp");
1527     goto error1;
1528   }
1529
1530   size_t markerlen = strlen (endmarker);
1531
1532   char buffer[BUFSIZ];
1533   int write_error = 0;
1534   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1535     /* Look for "END"<EOF> or "END\n" in input. */
1536     size_t blen = strlen (buffer);
1537     if (STREQLEN (buffer, endmarker, markerlen) &&
1538         (blen == markerlen ||
1539          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1540       goto found_end;
1541
1542     if (xwrite (fd, buffer, blen) == -1) {
1543       if (!write_error) perror ("write");
1544       write_error = 1;
1545       /* continue reading up to the end marker */
1546     }
1547   }
1548
1549   /* Reached EOF of stdin without finding the end marker, which
1550    * is likely to be an error.
1551    */
1552   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1553            program_name, endmarker);
1554   goto error2;
1555
1556  found_end:
1557   if (write_error) {
1558     close (fd);
1559     goto error2;
1560   }
1561
1562   if (close (fd) == -1) {
1563     perror ("close");
1564     goto error2;
1565   }
1566
1567   return file_in_tmpfile;
1568
1569  error2:
1570   unlink (file_in_tmpfile);
1571
1572  error1:
1573   free (file_in_tmpfile);
1574   file_in_tmpfile = NULL;
1575   return NULL;
1576 }
1577
1578 void
1579 free_file_in (char *s)
1580 {
1581   if (file_in_tmpfile) {
1582     if (unlink (file_in_tmpfile) == -1)
1583       perror (file_in_tmpfile);
1584     file_in_tmpfile = NULL;
1585   }
1586
1587   /* Free the device or file name which was strdup'd in file_in().
1588    * Note it's not immediately clear, but for -<< heredocs,
1589    * s == file_in_tmpfile, so this frees up that buffer.
1590    */
1591   free (s);
1592 }
1593
1594 /* Resolve the special FileOut paths ("-" or filename).
1595  * The caller (cmds.c) will call free (str) after the command has run.
1596  */
1597 char *
1598 file_out (const char *arg)
1599 {
1600   char *ret;
1601
1602   if (STREQ (arg, "-"))
1603     ret = strdup ("/dev/stdout");
1604   else
1605     ret = strdup (arg);
1606
1607   if (!ret) {
1608     perror ("strdup");
1609     return NULL;
1610   }
1611   return ret;
1612 }