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