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