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