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