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