chiark / gitweb /
asshelp.c: add a lot of debug logging
[gnupg2.git] / sm / passphrase.c
1 /* passphrase.c -  Get a passphrase
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3  *               2005, 2006, 2007, 2009, 2011 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <unistd.h>
23
24 #include "passphrase.h"
25 #include "gpgsm.h"
26 #include "../common/shareddefs.h"
27 #include "../common/ttyio.h"
28
29 static char *fd_passwd = NULL;
30
31 int
32 have_static_passphrase ()
33 {
34   return (!!fd_passwd
35           && (opt.batch || opt.pinentry_mode == PINENTRY_MODE_LOOPBACK));
36 }
37
38 /* Return a static passphrase.  The returned value is only valid as
39    long as no other passphrase related function is called.  NULL may
40    be returned if no passphrase has been set; better use
41    have_static_passphrase first.  */
42 const char *
43 get_static_passphrase (void)
44 {
45   return fd_passwd;
46 }
47
48 void
49 read_passphrase_from_fd (int fd)
50 {
51   int i, len;
52   char *pw;
53
54   if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
55     { /* Not used but we have to do a dummy read, so that it won't end
56          up at the begin of the message if the quite usual trick to
57          prepend the passphtrase to the message is used. */
58       char buf[1];
59
60       while (!(read (fd, buf, 1) != 1 || *buf == '\n'))
61         ;
62       *buf = 0;
63       return;
64     }
65
66   for (pw = NULL, i = len = 100; ; i++)
67     {
68       if (i >= len-1)
69         {
70           char *pw2 = pw;
71           len += 100;
72           pw = xmalloc_secure (len);
73           if (pw2)
74             {
75               memcpy (pw, pw2, i);
76               xfree (pw2);
77             }
78           else
79             i = 0;
80         }
81       if (read (fd, pw+i, 1) != 1 || pw[i] == '\n')
82         break;
83     }
84   pw[i] = 0;
85   if (!opt.batch && opt.pinentry_mode != PINENTRY_MODE_LOOPBACK)
86     tty_printf("\b\b\b   \n" );
87
88   xfree (fd_passwd);
89   fd_passwd = pw;
90 }