Generate a dummy 'Fedora' fedora.img in images directory for use by tests.
[libguestfs.git] / fish / keys.c
1 /* libguestfs - guestfish and guestmount shared option parsing
2  * Copyright (C) 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 <unistd.h>
24 #include <termios.h>
25
26 #include "guestfs.h"
27
28 #include "options.h"
29
30 /* Read a passphrase ('Key') from /dev/tty with echo off.
31  * The caller (cmds.c) will call free on the string afterwards.
32  * Based on the code in cryptsetup file lib/utils.c.
33  */
34 char *
35 read_key (const char *param)
36 {
37   FILE *infp, *outfp;
38   struct termios orig, temp;
39   char *ret = NULL;
40
41   /* Read and write to /dev/tty if available. */
42   if (keys_from_stdin ||
43       (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
44     infp = stdin;
45     outfp = stdout;
46   }
47
48   /* Print the prompt and set no echo. */
49   int tty = isatty (fileno (infp));
50   int tcset = 0;
51   if (tty) {
52     fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
53
54     if (!echo_keys) {
55       if (tcgetattr (fileno (infp), &orig) == -1) {
56         perror ("tcgetattr");
57         goto error;
58       }
59       memcpy (&temp, &orig, sizeof temp);
60       temp.c_lflag &= ~ECHO;
61
62       tcsetattr (fileno (infp), TCSAFLUSH, &temp);
63       tcset = 1;
64     }
65   }
66
67   size_t n = 0;
68   ssize_t len;
69   len = getline (&ret, &n, infp);
70   if (len == -1) {
71     perror ("getline");
72     ret = NULL;
73     goto error;
74   }
75
76   /* Remove the terminating \n if there is one. */
77   if (len > 0 && ret[len-1] == '\n')
78     ret[len-1] = '\0';
79
80  error:
81   /* Restore echo, close file descriptor. */
82   if (tty && tcset) {
83     printf ("\n");
84     tcsetattr (fileno (infp), TCSAFLUSH, &orig);
85   }
86
87   if (infp != stdin)
88     fclose (infp); /* outfp == infp, so this is closed also */
89
90   return ret;
91 }