Version 1.11.17.
[libguestfs.git] / fish / keys.c
1 /* libguestfs - guestfish and guestmount shared option parsing
2  * Copyright (C) 2010-2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <termios.h>
25 #include <string.h>
26
27 #include "guestfs.h"
28
29 #include "options.h"
30
31 /* Read a passphrase ('Key') from /dev/tty with echo off.
32  * The caller (cmds.c) will call free on the string afterwards.
33  * Based on the code in cryptsetup file lib/utils.c.
34  */
35 char *
36 read_key (const char *param)
37 {
38   FILE *infp, *outfp;
39   struct termios orig, temp;
40   char *ret = NULL;
41
42   /* Read and write to /dev/tty if available. */
43   if (keys_from_stdin ||
44       (infp = outfp = fopen ("/dev/tty", "w+")) == NULL) {
45     infp = stdin;
46     outfp = stdout;
47   }
48
49   /* Print the prompt and set no echo. */
50   int tty = isatty (fileno (infp));
51   int tcset = 0;
52   if (tty) {
53     fprintf (outfp, _("Enter key or passphrase (\"%s\"): "), param);
54
55     if (!echo_keys) {
56       if (tcgetattr (fileno (infp), &orig) == -1) {
57         perror ("tcgetattr");
58         goto error;
59       }
60       memcpy (&temp, &orig, sizeof temp);
61       temp.c_lflag &= ~ECHO;
62
63       tcsetattr (fileno (infp), TCSAFLUSH, &temp);
64       tcset = 1;
65     }
66   }
67
68   size_t n = 0;
69   ssize_t len;
70   len = getline (&ret, &n, infp);
71   if (len == -1) {
72     perror ("getline");
73     ret = NULL;
74     goto error;
75   }
76
77   /* Remove the terminating \n if there is one. */
78   if (len > 0 && ret[len-1] == '\n')
79     ret[len-1] = '\0';
80
81  error:
82   /* Restore echo, close file descriptor. */
83   if (tty && tcset) {
84     printf ("\n");
85     tcsetattr (fileno (infp), TCSAFLUSH, &orig);
86   }
87
88   if (infp != stdin)
89     fclose (infp); /* outfp == infp, so this is closed also */
90
91   return ret;
92 }