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