fish: Implement 'hexedit' command.
[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     } a;
55     struct {
56       char *guest;          /* guest name */
57     } d;
58     struct {
59       char *filename;       /* disk filename (testX.img) */
60       prep_data *data;      /* prepared type */
61       char *device;         /* device inside the appliance */
62     } N;
63   };
64 };
65
66 struct mp {
67   struct mp *next;
68   char *device;
69   char *mountpoint;
70 };
71
72 static void set_up_terminal (void);
73 static char add_drives (struct drv *drv, char next_drive);
74 static void prepare_drives (struct drv *drv);
75 static void mount_mps (struct mp *mp);
76 static void free_drives (struct drv *drv);
77 static void free_mps (struct mp *mp);
78 static int launch (void);
79 static void interactive (void);
80 static void shell_script (void);
81 static void script (int prompt);
82 static void cmdline (char *argv[], int optind, int argc);
83 static void initialize_readline (void);
84 static void cleanup_readline (void);
85 #ifdef HAVE_LIBREADLINE
86 static void add_history_line (const char *);
87 #endif
88
89 static int override_progress_bars = -1;
90
91 /* Currently open libguestfs handle. */
92 guestfs_h *g;
93
94 int read_only = 0;
95 int quit = 0;
96 int verbose = 0;
97 int remote_control_listen = 0;
98 int remote_control = 0;
99 int exit_on_error = 1;
100 int command_num = 0;
101 int keys_from_stdin = 0;
102 int echo_keys = 0;
103 const char *libvirt_uri = NULL;
104 int inspector = 0;
105 int utf8_mode = 0;
106 int have_terminfo = 0;
107 int progress_bars = 0;
108
109 static void __attribute__((noreturn))
110 usage (int status)
111 {
112   if (status != EXIT_SUCCESS)
113     fprintf (stderr, _("Try `%s --help' for more information.\n"),
114              program_name);
115   else {
116     fprintf (stdout,
117            _("%s: guest filesystem shell\n"
118              "%s lets you edit virtual machine filesystems\n"
119              "Copyright (C) 2009-2010 Red Hat Inc.\n"
120              "Usage:\n"
121              "  %s [--options] cmd [: cmd : cmd ...]\n"
122              "  %s [--ro] -i -a disk-image\n"
123              "  %s [--ro] -i -d libvirt-domain\n"
124              "or for interactive use:\n"
125              "  %s\n"
126              "or from a shell script:\n"
127              "  %s <<EOF\n"
128              "  cmd\n"
129              "  ...\n"
130              "  EOF\n"
131              "Options:\n"
132              "  -h|--cmd-help        List available commands\n"
133              "  -h|--cmd-help cmd    Display detailed help on 'cmd'\n"
134              "  -a|--add image       Add image\n"
135              "  -c|--connect uri     Specify libvirt URI for -d option\n"
136              "  -d|--domain guest    Add disks from libvirt guest\n"
137              "  -D|--no-dest-paths   Don't tab-complete paths from guest fs\n"
138              "  --echo-keys          Don't turn off echo for passphrases\n"
139              "  -f|--file file       Read commands from file\n"
140              "  -i|--inspector       Automatically mount filesystems\n"
141              "  --keys-from-stdin    Read passphrases from stdin\n"
142              "  --listen             Listen for remote commands\n"
143              "  -m|--mount dev[:mnt] Mount dev on mnt (if omitted, /)\n"
144              "  -n|--no-sync         Don't autosync\n"
145              "  -N|--new type        Create prepared disk (test1.img, ...)\n"
146              "  --progress-bars      Enable progress bars even when not interactive\n"
147              "  --no-progress-bars   Disable progress bars\n"
148              "  --remote[=pid]       Send commands to remote %s\n"
149              "  -r|--ro              Mount read-only\n"
150              "  --selinux            Enable SELinux support\n"
151              "  -v|--verbose         Verbose messages\n"
152              "  -x                   Echo each command before executing it\n"
153              "  -V|--version         Display version and exit\n"
154              "For more information, see the manpage %s(1).\n"),
155              program_name, program_name, program_name,
156              program_name, program_name, program_name,
157              program_name, program_name, program_name);
158   }
159   exit (status);
160 }
161
162 int
163 main (int argc, char *argv[])
164 {
165   /* Set global program name that is not polluted with libtool artifacts.  */
166   set_program_name (argv[0]);
167
168   atexit (close_stdout);
169
170   setlocale (LC_ALL, "");
171   bindtextdomain (PACKAGE, LOCALEBASEDIR);
172   textdomain (PACKAGE);
173
174   set_up_terminal ();
175
176   enum { HELP_OPTION = CHAR_MAX + 1 };
177
178   static const char *options = "a:c:d:Df:h::im:nN:rv?Vx";
179   static const struct option long_options[] = {
180     { "add", 1, 0, 'a' },
181     { "cmd-help", 2, 0, 'h' },
182     { "connect", 1, 0, 'c' },
183     { "domain", 1, 0, 'd' },
184     { "echo-keys", 0, 0, 0 },
185     { "file", 1, 0, 'f' },
186     { "help", 0, 0, HELP_OPTION },
187     { "inspector", 0, 0, 'i' },
188     { "keys-from-stdin", 0, 0, 0 },
189     { "listen", 0, 0, 0 },
190     { "mount", 1, 0, 'm' },
191     { "new", 1, 0, 'N' },
192     { "no-dest-paths", 0, 0, 'D' },
193     { "no-sync", 0, 0, 'n' },
194     { "progress-bars", 0, 0, 0 },
195     { "no-progress-bars", 0, 0, 0 },
196     { "remote", 2, 0, 0 },
197     { "ro", 0, 0, 'r' },
198     { "selinux", 0, 0, 0 },
199     { "verbose", 0, 0, 'v' },
200     { "version", 0, 0, 'V' },
201     { 0, 0, 0, 0 }
202   };
203   struct drv *drvs = NULL;
204   struct drv *drv;
205   struct mp *mps = NULL;
206   struct mp *mp;
207   char *p, *file = NULL;
208   int c;
209   int option_index;
210   struct sigaction sa;
211   int next_prepared_drive = 1;
212
213   initialize_readline ();
214
215   memset (&sa, 0, sizeof sa);
216   sa.sa_handler = SIG_IGN;
217   sa.sa_flags = SA_RESTART;
218   sigaction (SIGPIPE, &sa, NULL);
219
220   /* guestfs_create is meant to be a lightweight operation, so
221    * it's OK to do it early here.
222    */
223   g = guestfs_create ();
224   if (g == NULL) {
225     fprintf (stderr, _("guestfs_create: failed to create handle\n"));
226     exit (EXIT_FAILURE);
227   }
228
229   guestfs_set_autosync (g, 1);
230
231   /* If developing, add ./appliance to the path.  Note that libtools
232    * interferes with this because uninstalled guestfish is a shell
233    * script that runs the real program with an absolute path.  Detect
234    * that too.
235    *
236    * BUT if LIBGUESTFS_PATH environment variable is already set by
237    * the user, then don't override it.
238    */
239   if (getenv ("LIBGUESTFS_PATH") == NULL &&
240       argv[0] &&
241       (argv[0][0] != '/' || strstr (argv[0], "/.libs/lt-") != NULL))
242     guestfs_set_path (g, "appliance:" GUESTFS_DEFAULT_PATH);
243
244   /* CAUTION: we are careful to modify argv[0] here, only after
245    * using it just above.
246    *
247    * getopt_long uses argv[0], so give it the sanitized name.  Save a copy
248    * of the original, in case it's needed below.
249    */
250   char *real_argv0 = argv[0];
251   argv[0] = bad_cast (program_name);
252
253   for (;;) {
254     c = getopt_long (argc, argv, options, long_options, &option_index);
255     if (c == -1) break;
256
257     switch (c) {
258     case 0:                     /* options which are long only */
259       if (STREQ (long_options[option_index].name, "listen"))
260         remote_control_listen = 1;
261       else if (STREQ (long_options[option_index].name, "remote")) {
262         if (optarg) {
263           if (sscanf (optarg, "%d", &remote_control) != 1) {
264             fprintf (stderr, _("%s: --listen=PID: PID was not a number: %s\n"),
265                      program_name, optarg);
266             exit (EXIT_FAILURE);
267           }
268         } else {
269           p = getenv ("GUESTFISH_PID");
270           if (!p || sscanf (p, "%d", &remote_control) != 1) {
271             fprintf (stderr, _("%s: remote: $GUESTFISH_PID must be set"
272                                " to the PID of the remote process\n"),
273                      program_name);
274             exit (EXIT_FAILURE);
275           }
276         }
277       } else if (STREQ (long_options[option_index].name, "selinux")) {
278         guestfs_set_selinux (g, 1);
279       } else if (STREQ (long_options[option_index].name, "keys-from-stdin")) {
280         keys_from_stdin = 1;
281       } else if (STREQ (long_options[option_index].name, "progress-bars")) {
282         override_progress_bars = 1;
283       } else if (STREQ (long_options[option_index].name, "no-progress-bars")) {
284         override_progress_bars = 0;
285       } else if (STREQ (long_options[option_index].name, "echo-keys")) {
286         echo_keys = 1;
287       } else {
288         fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
289                  program_name, long_options[option_index].name, option_index);
290         exit (EXIT_FAILURE);
291       }
292       break;
293
294     case 'a':
295       if (access (optarg, R_OK) != 0) {
296         perror (optarg);
297         exit (EXIT_FAILURE);
298       }
299       drv = malloc (sizeof (struct drv));
300       if (!drv) {
301         perror ("malloc");
302         exit (EXIT_FAILURE);
303       }
304       drv->type = drv_a;
305       drv->a.filename = optarg;
306       drv->next = drvs;
307       drvs = drv;
308       break;
309
310     case 'c':
311       libvirt_uri = optarg;
312       break;
313
314     case 'd':
315       drv = malloc (sizeof (struct drv));
316       if (!drv) {
317         perror ("malloc");
318         exit (EXIT_FAILURE);
319       }
320       drv->type = drv_d;
321       drv->d.guest = optarg;
322       drv->next = drvs;
323       drvs = drv;
324       break;
325
326     case 'N':
327       if (STRCASEEQ (optarg, "list") ||
328           STRCASEEQ (optarg, "help") ||
329           STRCASEEQ (optarg, "h") ||
330           STRCASEEQ (optarg, "?")) {
331         list_prepared_drives ();
332         exit (EXIT_SUCCESS);
333       }
334       drv = malloc (sizeof (struct drv));
335       if (!drv) {
336         perror ("malloc");
337         exit (EXIT_FAILURE);
338       }
339       drv->type = drv_N;
340       if (asprintf (&drv->N.filename, "test%d.img",
341                     next_prepared_drive++) == -1) {
342         perror ("asprintf");
343         exit (EXIT_FAILURE);
344       }
345       drv->N.data = create_prepared_file (optarg, drv->N.filename);
346       drv->N.device = NULL;     /* filled in by add_drives */
347       drv->next = drvs;
348       drvs = drv;
349       break;
350
351     case 'D':
352       complete_dest_paths = 0;
353       break;
354
355     case 'f':
356       if (file) {
357         fprintf (stderr, _("%s: only one -f parameter can be given\n"),
358                  program_name);
359         exit (EXIT_FAILURE);
360       }
361       file = optarg;
362       break;
363
364     case 'h': {
365       int r = 0;
366
367       if (optarg)
368         r = display_command (optarg);
369       else if (argv[optind] && argv[optind][0] != '-')
370         r = display_command (argv[optind++]);
371       else
372         list_commands ();
373
374       exit (r == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
375     }
376
377     case 'i':
378       inspector = 1;
379       break;
380
381     case 'm':
382       mp = malloc (sizeof (struct mp));
383       if (!mp) {
384         perror ("malloc");
385         exit (EXIT_FAILURE);
386       }
387       p = strchr (optarg, ':');
388       if (p) {
389         *p = '\0';
390         mp->mountpoint = p+1;
391       } else
392         mp->mountpoint = bad_cast ("/");
393       mp->device = optarg;
394       mp->next = mps;
395       mps = mp;
396       break;
397
398     case 'n':
399       guestfs_set_autosync (g, 0);
400       break;
401
402     case 'r':
403       read_only = 1;
404       break;
405
406     case 'v':
407       verbose++;
408       guestfs_set_verbose (g, verbose);
409       break;
410
411     case 'V': {
412       struct guestfs_version *v = guestfs_version (g);
413       printf ("%s %"PRIi64".%"PRIi64".%"PRIi64"%s\n", program_name,
414               v->major, v->minor, v->release, v->extra);
415       exit (EXIT_SUCCESS);
416     }
417
418     case 'x':
419       guestfs_set_trace (g, 1);
420       break;
421
422     case HELP_OPTION:
423       usage (EXIT_SUCCESS);
424
425     default:
426       usage (EXIT_FAILURE);
427     }
428   }
429
430   /* Old-style -i syntax?  Since -a/-d/-N and -i was disallowed
431    * previously, if we have -i without any drives but with something
432    * on the command line, it must be old-style syntax.
433    */
434   if (inspector && drvs == NULL && optind < argc) {
435     while (optind < argc) {
436       if (strchr (argv[optind], '/') ||
437           access (argv[optind], F_OK) == 0) { /* simulate -a option */
438         drv = malloc (sizeof (struct drv));
439         if (!drv) {
440           perror ("malloc");
441           exit (EXIT_FAILURE);
442         }
443         drv->type = drv_a;
444         drv->a.filename = argv[optind];
445         drv->next = drvs;
446         drvs = drv;
447       } else {                  /* simulate -d option */
448         drv = malloc (sizeof (struct drv));
449         if (!drv) {
450           perror ("malloc");
451           exit (EXIT_FAILURE);
452         }
453         drv->type = drv_d;
454         drv->d.guest = argv[optind];
455         drv->next = drvs;
456         drvs = drv;
457       }
458
459       optind++;
460     }
461   }
462
463   /* If we've got drives to add, add them now. */
464   add_drives (drvs, 'a');
465
466   /* If we've got mountpoints or prepared drives or -i option, we must
467    * launch the guest and mount them.
468    */
469   if (next_prepared_drive > 1 || mps != NULL || inspector) {
470     /* RHBZ#612178: If --listen flag is given, then we will fork into
471      * the background in rc_listen().  However you can't do this while
472      * holding a libguestfs handle open because the recovery process
473      * will think the main program has died and kill qemu.  Therefore
474      * don't use the recovery process for this case.  (A better
475      * solution would be to call launch () etc after the fork, but
476      * that greatly complicates the code here).
477      */
478     if (remote_control_listen)
479       guestfs_set_recovery_proc (g, 0);
480
481     if (launch () == -1) exit (EXIT_FAILURE);
482
483     if (inspector)
484       inspect_mount ();
485
486     prepare_drives (drvs);
487     mount_mps (mps);
488   }
489
490   /* Free up data structures, no longer needed after this point. */
491   free_drives (drvs);
492   free_mps (mps);
493
494   /* Remote control? */
495   if (remote_control_listen && remote_control) {
496     fprintf (stderr,
497              _("%s: cannot use --listen and --remote options at the same time\n"),
498              program_name);
499     exit (EXIT_FAILURE);
500   }
501
502   if (remote_control_listen) {
503     if (optind < argc) {
504       fprintf (stderr,
505                _("%s: extra parameters on the command line with --listen flag\n"),
506                program_name);
507       exit (EXIT_FAILURE);
508     }
509     if (file) {
510       fprintf (stderr,
511                _("%s: cannot use --listen and --file options at the same time\n"),
512                program_name);
513       exit (EXIT_FAILURE);
514     }
515     rc_listen ();
516   }
517
518   /* -f (file) parameter? */
519   if (file) {
520     close (0);
521     if (open (file, O_RDONLY) == -1) {
522       perror (file);
523       exit (EXIT_FAILURE);
524     }
525   }
526
527   /* Decide if we display progress bars. */
528   progress_bars =
529     override_progress_bars >= 0
530     ? override_progress_bars
531     : (optind >= argc && isatty (0));
532
533   if (progress_bars)
534     guestfs_set_progress_callback (g, progress_callback, NULL);
535
536   /* Interactive, shell script, or command(s) on the command line? */
537   if (optind >= argc) {
538     if (isatty (0))
539       interactive ();
540     else
541       shell_script ();
542   }
543   else
544     cmdline (argv, optind, argc);
545
546   cleanup_readline ();
547
548   exit (EXIT_SUCCESS);
549 }
550
551 /* The <term.h> header file which defines this has "issues". */
552 extern int tgetent (char *, const char *);
553
554 static void
555 set_up_terminal (void)
556 {
557   /* http://www.cl.cam.ac.uk/~mgk25/unicode.html#activate */
558   utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
559
560   char *term = getenv ("TERM");
561   if (term == NULL) {
562     //fprintf (stderr, _("guestfish: TERM (terminal type) not defined.\n"));
563     return;
564   }
565
566   int r = tgetent (NULL, term);
567   if (r == -1) {
568     fprintf (stderr, _("guestfish: could not access termcap or terminfo database.\n"));
569     return;
570   }
571   if (r == 0) {
572     fprintf (stderr, _("guestfish: terminal type \"%s\" not defined.\n"),
573              term);
574     return;
575   }
576
577   have_terminfo = 1;
578 }
579
580 void
581 pod2text (const char *name, const char *shortdesc, const char *str)
582 {
583   FILE *fp;
584
585   fp = popen ("pod2text", "w");
586   if (fp == NULL) {
587     /* pod2text failed, maybe not found, so let's just print the
588      * source instead, since that's better than doing nothing.
589      */
590     printf ("%s - %s\n\n%s\n", name, shortdesc, str);
591     return;
592   }
593   fprintf (fp, "=head1 NAME\n\n%s - %s\n\n", name, shortdesc);
594   fputs (str, fp);
595   pclose (fp);
596 }
597
598 /* List is built in reverse order, so mount them in reverse order. */
599 static void
600 mount_mps (struct mp *mp)
601 {
602   int r;
603
604   if (mp) {
605     mount_mps (mp->next);
606
607     /* Don't use guestfs_mount here because that will default to mount
608      * options -o sync,noatime.  For more information, see guestfs(3)
609      * section "LIBGUESTFS GOTCHAS".
610      */
611     const char *options = read_only ? "ro" : "";
612     r = guestfs_mount_options (g, options, mp->device, mp->mountpoint);
613     if (r == -1) {
614       /* Display possible mountpoints before exiting. */
615       char **fses = guestfs_list_filesystems (g);
616       if (fses == NULL || fses[0] == NULL)
617         goto out;
618       fprintf (stderr,
619                _("guestfish: '%s' could not be mounted.  Did you mean one of these?\n"),
620                mp->device);
621       size_t i;
622       for (i = 0; fses[i] != NULL; i += 2)
623         fprintf (stderr, "\t%s (%s)\n", fses[i], fses[i+1]);
624
625     out:
626       exit (EXIT_FAILURE);
627     }
628   }
629 }
630
631 static char
632 add_drives (struct drv *drv, char next_drive)
633 {
634   int r;
635
636   if (next_drive > 'z') {
637     fprintf (stderr,
638              _("guestfish: too many drives added on the command line\n"));
639     exit (EXIT_FAILURE);
640   }
641
642   if (drv) {
643     next_drive = add_drives (drv->next, next_drive);
644
645     switch (drv->type) {
646     case drv_a:
647       if (!read_only)
648         r = guestfs_add_drive (g, drv->a.filename);
649       else
650         r = guestfs_add_drive_ro (g, drv->a.filename);
651       if (r == -1)
652         exit (EXIT_FAILURE);
653
654       next_drive++;
655       break;
656
657     case drv_d:
658       r = add_libvirt_drives (drv->d.guest);
659       if (r == -1)
660         exit (EXIT_FAILURE);
661
662       next_drive += r;
663       break;
664
665     case drv_N:
666       /* -N option is not affected by --ro */
667       r = guestfs_add_drive (g, drv->N.filename);
668       if (r == -1)
669         exit (EXIT_FAILURE);
670
671       if (asprintf (&drv->N.device, "/dev/sd%c", next_drive) == -1) {
672         perror ("asprintf");
673         exit (EXIT_FAILURE);
674       }
675
676       next_drive++;
677       break;
678
679     default: /* keep GCC happy */
680       abort ();
681     }
682   }
683
684   return next_drive;
685 }
686
687 static void
688 prepare_drives (struct drv *drv)
689 {
690   if (drv) {
691     prepare_drives (drv->next);
692     if (drv->type == drv_N)
693       prepare_drive (drv->N.filename, drv->N.data, drv->N.device);
694   }
695 }
696
697 static void
698 free_drives (struct drv *drv)
699 {
700   if (!drv) return;
701   free_drives (drv->next);
702
703   switch (drv->type) {
704   case drv_a: free (drv->a.filename); break;
705   case drv_d: free (drv->d.guest); break;
706   case drv_N:
707     free (drv->N.filename);
708     free (drv->N.device);
709     free_prep_data (drv->N.data);
710     break;
711   default: ;                    /* keep GCC happy */
712   }
713   free (drv);
714 }
715
716 static void
717 free_mps (struct mp *mp)
718 {
719   if (!mp) return;
720   free_mps (mp->next);
721
722   /* The drive and mountpoint fields are not allocated
723    * from the heap, so we should not free them here.
724    */
725
726   free (mp);
727 }
728
729 static int
730 launch (void)
731 {
732   if (guestfs_is_config (g)) {
733     if (guestfs_launch (g) == -1)
734       return -1;
735   }
736   return 0;
737 }
738
739 static void
740 interactive (void)
741 {
742   script (1);
743 }
744
745 static void
746 shell_script (void)
747 {
748   script (0);
749 }
750
751 #define FISH "><fs> "
752
753 static char *line_read = NULL;
754
755 static char *
756 rl_gets (int prompt)
757 {
758 #ifdef HAVE_LIBREADLINE
759
760   if (prompt) {
761     if (line_read) {
762       free (line_read);
763       line_read = NULL;
764     }
765
766     line_read = readline (prompt ? FISH : "");
767
768     if (line_read && *line_read)
769       add_history_line (line_read);
770
771     return line_read;
772   }
773
774 #endif /* HAVE_LIBREADLINE */
775
776   static char buf[8192];
777   int len;
778
779   if (prompt) printf (FISH);
780   line_read = fgets (buf, sizeof buf, stdin);
781
782   if (line_read) {
783     len = strlen (line_read);
784     if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0';
785   }
786
787   return line_read;
788 }
789
790 static void
791 script (int prompt)
792 {
793   char *buf;
794   char *cmd;
795   char *p, *pend;
796   char *argv[64];
797   int len;
798   int global_exit_on_error = !prompt;
799   int tilde_candidate;
800
801   if (prompt) {
802     printf (_("\n"
803               "Welcome to guestfish, the libguestfs filesystem interactive shell for\n"
804               "editing virtual machine filesystems.\n"
805               "\n"
806               "Type: 'help' for a list of commands\n"
807               "      'man' to read the manual\n"
808               "      'quit' to quit the shell\n"
809               "\n"));
810
811     if (inspector) {
812       print_inspect_prompt ();
813       printf ("\n");
814     }
815   }
816
817   while (!quit) {
818     char *pipe = NULL;
819
820     exit_on_error = global_exit_on_error;
821
822     buf = rl_gets (prompt);
823     if (!buf) {
824       quit = 1;
825       break;
826     }
827
828     /* Skip any initial whitespace before the command. */
829   again:
830     while (*buf && c_isspace (*buf))
831       buf++;
832
833     if (!*buf) continue;
834
835     /* If the next character is '#' then this is a comment. */
836     if (*buf == '#') continue;
837
838     /* If the next character is '!' then pass the whole lot to system(3). */
839     if (*buf == '!') {
840       int r;
841
842       r = system (buf+1);
843       if (exit_on_error) {
844         if (r == -1 ||
845             (WIFSIGNALED (r) &&
846              (WTERMSIG (r) == SIGINT || WTERMSIG (r) == SIGQUIT)) ||
847             WEXITSTATUS (r) != 0)
848           exit (EXIT_FAILURE);
849       }
850       continue;
851     }
852
853     /* If the next character is '-' allow the command to fail without
854      * exiting on error (just for this one command though).
855      */
856     if (*buf == '-') {
857       exit_on_error = 0;
858       buf++;
859       goto again;
860     }
861
862     /* Get the command (cannot be quoted). */
863     len = strcspn (buf, " \t");
864
865     if (len == 0) continue;
866
867     cmd = buf;
868     unsigned int i = 0;
869     if (buf[len] == '\0') {
870       argv[0] = NULL;
871       goto got_command;
872     }
873
874     buf[len] = '\0';
875     p = &buf[len+1];
876     p += strspn (p, " \t");
877
878     /* Get the parameters. */
879     while (*p && i < sizeof argv / sizeof argv[0]) {
880       tilde_candidate = 0;
881
882       /* Parameters which start with quotes or pipes are treated
883        * specially.  Bare parameters are delimited by whitespace.
884        */
885       if (*p == '"') {
886         p++;
887         len = strcspn (p, "\"");
888         if (p[len] == '\0') {
889           fprintf (stderr, _("%s: unterminated double quote\n"), program_name);
890           if (exit_on_error) exit (EXIT_FAILURE);
891           goto next_command;
892         }
893         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
894           fprintf (stderr,
895                    _("%s: command arguments not separated by whitespace\n"),
896                    program_name);
897           if (exit_on_error) exit (EXIT_FAILURE);
898           goto next_command;
899         }
900         p[len] = '\0';
901         pend = p[len+1] ? &p[len+2] : &p[len+1];
902       } else if (*p == '\'') {
903         p++;
904         len = strcspn (p, "'");
905         if (p[len] == '\0') {
906           fprintf (stderr, _("%s: unterminated single quote\n"), program_name);
907           if (exit_on_error) exit (EXIT_FAILURE);
908           goto next_command;
909         }
910         if (p[len+1] && (p[len+1] != ' ' && p[len+1] != '\t')) {
911           fprintf (stderr,
912                    _("%s: command arguments not separated by whitespace\n"),
913                    program_name);
914           if (exit_on_error) exit (EXIT_FAILURE);
915           goto next_command;
916         }
917         p[len] = '\0';
918         pend = p[len+1] ? &p[len+2] : &p[len+1];
919       } else if (*p == '|') {
920         *p = '\0';
921         pipe = p+1;
922         continue;
923         /*
924       } else if (*p == '[') {
925         int c = 1;
926         p++;
927         pend = p;
928         while (*pend && c != 0) {
929           if (*pend == '[') c++;
930           else if (*pend == ']') c--;
931           pend++;
932         }
933         if (c != 0) {
934           fprintf (stderr,
935                    _("%s: unterminated \"[...]\" sequence\n"), program_name);
936           if (exit_on_error) exit (EXIT_FAILURE);
937           goto next_command;
938         }
939         if (*pend && (*pend != ' ' && *pend != '\t')) {
940           fprintf (stderr,
941                    _("%s: command arguments not separated by whitespace\n"),
942                    program_name);
943           if (exit_on_error) exit (EXIT_FAILURE);
944           goto next_command;
945         }
946         *(pend-1) = '\0';
947         */
948       } else if (*p != ' ' && *p != '\t') {
949         /* If the first character is a ~ then note that this parameter
950          * is a candidate for ~username expansion.  NB this does not
951          * apply to quoted parameters.
952          */
953         tilde_candidate = *p == '~';
954         len = strcspn (p, " \t");
955         if (p[len]) {
956           p[len] = '\0';
957           pend = &p[len+1];
958         } else
959           pend = &p[len];
960       } else {
961         fprintf (stderr, _("%s: internal error parsing string at '%s'\n"),
962                  program_name, p);
963         abort ();
964       }
965
966       if (!tilde_candidate)
967         argv[i] = p;
968       else
969         argv[i] = try_tilde_expansion (p);
970       i++;
971       p = pend;
972
973       if (*p)
974         p += strspn (p, " \t");
975     }
976
977     if (i == sizeof argv / sizeof argv[0]) {
978       fprintf (stderr, _("%s: too many arguments\n"), program_name);
979       if (exit_on_error) exit (EXIT_FAILURE);
980       goto next_command;
981     }
982
983     argv[i] = NULL;
984
985   got_command:
986     if (issue_command (cmd, argv, pipe) == -1) {
987       if (exit_on_error) exit (EXIT_FAILURE);
988     }
989
990   next_command:;
991   }
992   if (prompt) printf ("\n");
993 }
994
995 static void
996 cmdline (char *argv[], int optind, int argc)
997 {
998   const char *cmd;
999   char **params;
1000
1001   exit_on_error = 1;
1002
1003   if (optind >= argc) return;
1004
1005   cmd = argv[optind++];
1006   if (STREQ (cmd, ":")) {
1007     fprintf (stderr, _("%s: empty command on command line\n"), program_name);
1008     exit (EXIT_FAILURE);
1009   }
1010
1011   /* Allow -cmd on the command line to mean (temporarily) override
1012    * the normal exit on error (RHBZ#578407).
1013    */
1014   if (cmd[0] == '-') {
1015     exit_on_error = 0;
1016     cmd++;
1017   }
1018
1019   params = &argv[optind];
1020
1021   /* Search for end of command list or ":" ... */
1022   while (optind < argc && STRNEQ (argv[optind], ":"))
1023     optind++;
1024
1025   if (optind == argc) {
1026     if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
1027         exit (EXIT_FAILURE);
1028   } else {
1029     argv[optind] = NULL;
1030     if (issue_command (cmd, params, NULL) == -1 && exit_on_error)
1031       exit (EXIT_FAILURE);
1032     cmdline (argv, optind+1, argc);
1033   }
1034 }
1035
1036 int
1037 issue_command (const char *cmd, char *argv[], const char *pipecmd)
1038 {
1039   int argc;
1040   int stdout_saved_fd = -1;
1041   int pid = 0;
1042   int i, 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, exit_on_error);
1101
1102   /* Otherwise execute it locally. */
1103   else if (STRCASEEQ (cmd, "help")) {
1104     if (argc == 0) {
1105       list_commands ();
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.
1473  * This always returns a newly allocated string which is freed by the
1474  * caller function in "cmds.c".
1475  */
1476 char *
1477 resolve_win_path (const char *path)
1478 {
1479   char *ret;
1480   size_t i;
1481
1482   if (STRCASENEQLEN (path, "win:", 4)) {
1483     ret = strdup (path);
1484     if (ret == NULL)
1485       perror ("strdup");
1486     return ret;
1487   }
1488
1489   path += 4;
1490
1491   /* Drop drive letter, if it's "C:". */
1492   if (STRCASEEQLEN (path, "c:", 2))
1493     path += 2;
1494
1495   if (!*path) {
1496     ret = strdup ("/");
1497     if (ret == NULL)
1498       perror ("strdup");
1499     return ret;
1500   }
1501
1502   ret = strdup (path);
1503   if (ret == NULL) {
1504     perror ("strdup");
1505     return NULL;
1506   }
1507
1508   /* Blindly convert any backslashes into forward slashes.  Is this good? */
1509   for (i = 0; i < strlen (ret); ++i)
1510     if (ret[i] == '\\')
1511       ret[i] = '/';
1512
1513   char *t = guestfs_case_sensitive_path (g, ret);
1514   free (ret);
1515   ret = t;
1516
1517   return ret;
1518 }
1519
1520 /* Resolve the special FileIn paths ("-" or "-<<END" or filename).
1521  * The caller (cmds.c) will call free_file_in after the command has
1522  * run which should clean up resources.
1523  */
1524 static char *file_in_heredoc (const char *endmarker);
1525 static char *file_in_tmpfile = NULL;
1526
1527 char *
1528 file_in (const char *arg)
1529 {
1530   char *ret;
1531
1532   if (STREQ (arg, "-")) {
1533     ret = strdup ("/dev/stdin");
1534     if (!ret) {
1535       perror ("strdup");
1536       return NULL;
1537     }
1538   }
1539   else if (STRPREFIX (arg, "-<<")) {
1540     const char *endmarker = &arg[3];
1541     if (*endmarker == '\0') {
1542       fprintf (stderr, "%s: missing end marker in -<< expression\n",
1543                program_name);
1544       return NULL;
1545     }
1546     ret = file_in_heredoc (endmarker);
1547     if (ret == NULL)
1548       return NULL;
1549   }
1550   else {
1551     ret = strdup (arg);
1552     if (!ret) {
1553       perror ("strdup");
1554       return NULL;
1555     }
1556   }
1557
1558   return ret;
1559 }
1560
1561 static char *
1562 file_in_heredoc (const char *endmarker)
1563 {
1564   static const char template[] = "/tmp/heredocXXXXXX";
1565   file_in_tmpfile = strdup (template);
1566   if (file_in_tmpfile == NULL) {
1567     perror ("strdup");
1568     return NULL;
1569   }
1570
1571   int fd = mkstemp (file_in_tmpfile);
1572   if (fd == -1) {
1573     perror ("mkstemp");
1574     goto error1;
1575   }
1576
1577   size_t markerlen = strlen (endmarker);
1578
1579   char buffer[BUFSIZ];
1580   int write_error = 0;
1581   while (fgets (buffer, sizeof buffer, stdin) != NULL) {
1582     /* Look for "END"<EOF> or "END\n" in input. */
1583     size_t blen = strlen (buffer);
1584     if (STREQLEN (buffer, endmarker, markerlen) &&
1585         (blen == markerlen ||
1586          (blen == markerlen+1 && buffer[markerlen] == '\n')))
1587       goto found_end;
1588
1589     if (xwrite (fd, buffer, blen) == -1) {
1590       if (!write_error) perror ("write");
1591       write_error = 1;
1592       /* continue reading up to the end marker */
1593     }
1594   }
1595
1596   /* Reached EOF of stdin without finding the end marker, which
1597    * is likely to be an error.
1598    */
1599   fprintf (stderr, "%s: end of input reached without finding '%s'\n",
1600            program_name, endmarker);
1601   goto error2;
1602
1603  found_end:
1604   if (write_error) {
1605     close (fd);
1606     goto error2;
1607   }
1608
1609   if (close (fd) == -1) {
1610     perror ("close");
1611     goto error2;
1612   }
1613
1614   return file_in_tmpfile;
1615
1616  error2:
1617   unlink (file_in_tmpfile);
1618
1619  error1:
1620   free (file_in_tmpfile);
1621   file_in_tmpfile = NULL;
1622   return NULL;
1623 }
1624
1625 void
1626 free_file_in (char *s)
1627 {
1628   if (file_in_tmpfile) {
1629     if (unlink (file_in_tmpfile) == -1)
1630       perror (file_in_tmpfile);
1631     file_in_tmpfile = NULL;
1632   }
1633
1634   /* Free the device or file name which was strdup'd in file_in().
1635    * Note it's not immediately clear, but for -<< heredocs,
1636    * s == file_in_tmpfile, so this frees up that buffer.
1637    */
1638   free (s);
1639 }
1640
1641 /* Resolve the special FileOut paths ("-" or filename).
1642  * The caller (cmds.c) will call free (str) after the command has run.
1643  */
1644 char *
1645 file_out (const char *arg)
1646 {
1647   char *ret;
1648
1649   if (STREQ (arg, "-"))
1650     ret = strdup ("/dev/stdout");
1651   else
1652     ret = strdup (arg);
1653
1654   if (!ret) {
1655     perror ("strdup");
1656     return NULL;
1657   }
1658   return ret;
1659 }
1660
1661 /* Read a passphrase ('Key') from /dev/tty with echo off.
1662  * The caller (cmds.c) will call free on the string afterwards.
1663  * Based on the code in cryptsetup file lib/utils.c.
1664  */
1665 char *
1666 read_key (const char *param)
1667 {
1668   FILE *infp, *outfp;
1669   struct termios orig, temp;
1670   char *ret = NULL;
1671
1672   /* Read and write to /dev/tty if available. */
1673   if (keys_from_stdin ||
1674       (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
1675     infp = stdin;
1676     outfp = stdout;
1677   }
1678
1679   /* Print the prompt and set no echo. */
1680   int tty = isatty (fileno (infp));
1681   int tcset = 0;
1682   if (tty) {
1683     fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
1684
1685     if (!echo_keys) {
1686       if (tcgetattr (fileno (infp), &orig) == -1) {
1687         perror ("tcgetattr");
1688         goto error;
1689       }
1690       memcpy (&temp, &orig, sizeof temp);
1691       temp.c_lflag &= ~ECHO;
1692
1693       tcsetattr (fileno (infp), TCSAFLUSH, &temp);
1694       tcset = 1;
1695     }
1696   }
1697
1698   size_t n = 0;
1699   ssize_t len;
1700   len = getline (&ret, &n, infp);
1701   if (len == -1) {
1702     perror ("getline");
1703     ret = NULL;
1704     goto error;
1705   }
1706
1707   /* Remove the terminating \n if there is one. */
1708   if (len > 0 && ret[len-1] == '\n')
1709     ret[len-1] = '\0';
1710
1711  error:
1712   /* Restore echo, close file descriptor. */
1713   if (tty && tcset) {
1714     printf ("\n");
1715     tcsetattr (fileno (infp), TCSAFLUSH, &orig);
1716   }
1717
1718   if (infp != stdin)
1719     fclose (infp); /* outfp == infp, so this is closed also */
1720
1721   return ret;
1722 }