/[winpt]/trunk/Src/wptGPG.cpp
ViewVC logotype

Diff of /trunk/Src/wptGPG.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2 by twoaday, Mon Jan 31 11:02:21 2005 UTC revision 214 by twoaday, Sun May 14 18:40:36 2006 UTC
# Line 1  Line 1 
1  /* wptGPG.cpp - GnuPG configuration  /* wptGPG.cpp - GnuPG configuration
2   *      Copyright (C) 2001-2004 Timo Schulz   *      Copyright (C) 2001-2006 Timo Schulz
3   *   *
4   * This file is part of WinPT.   * This file is part of WinPT.
5   *   *
6   * WinPT is free software; you can redistribute it and/or   * WinPT is free software; you can redistribute it and/or
7   * modify it under the terms of the GNU General Public License   * modify it under the terms of the GNU General Public License
8   * as published by the Free Software Foundation; either version 2   * as published by the Free Software Foundation; either version 2
9   * of the License, or (at your option) any later version.   * of the License, or (at your option) any later version.
10   *     *  
11   * WinPT is distributed in the hope that it will be useful,   * WinPT is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   * General Public License for more details.   * General Public License for more details.
15   *   *
16   * You should have received a copy of the GNU General Public License   * You should have received a copy of the GNU General Public License
17   * along with WinPT; if not, write to the Free Software Foundation,   * along with WinPT; if not, write to the Free Software Foundation,
18   * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA   * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19   */   */
20    #ifdef HAVE_CONFIG_H
21  #include <string.h>  #include <config.h>
22  #include <stdio.h>  #endif
23  #include <windows.h>  
24  #include <shlobj.h>  #include <windows.h>
25  #include <ctype.h>  #include <string.h>
26  #include <io.h>  #include <stdio.h>
27    #include <shlobj.h>
28  #include "wptGPG.h"  #include <ctype.h>
29  #include "wptGPGCmds.h"  #include <io.h>
30  #include "wptGPGOptSkel.h"  #include <time.h>
31  #include "wptTypes.h"  
32  #include "wptNLS.h"  #include "wptGPG.h"
33  #include "wptRegistry.h"  #include "wptGpgCmds.h"
34  #include "wptErrors.h"  #include "wptGPGOptSkel.h"
35  #include "wptW32API.h"  #include "wptTypes.h"
36    #include "wptNLS.h"
37  #define GPG_CONF "gpg.conf"  #include "wptRegistry.h"
38    #include "wptErrors.h"
39  struct gpg_watcher_s {  #include "wptW32API.h"
40      FILETIME last_access;  #include "wptCrypto.h"
41      FILETIME access;  
42      char * object;  #define GPG_CONF        "gpg.conf"
43      int modified;  #define GPG_REG_EXE     "gpgProgram"    /* registry name for the binary. */
44  };  #define GPG_REG_HOME    "HomeDir"       /* registry name of the home dir. */
45    
46  /* XXX need to watch for gpg.conf due to the fact keyring entries could be changed */  struct gpg_watcher_s {
47  static const char * gpg_objs[] = {"pubring.gpg", "secring.gpg", "trustdb.gpg"};      FILETIME    last_access;
48  static gpg_watcher_s gpg_table[3];      FILETIME    access;
49  static int gpg_table_count = DIM (gpg_table);      char        *object;
50        int         modified;
51  int idea_available = 0;  };
52    
53  static int check_keyring (char ** r_path);  
54    /* XXX need to watch for gpg.conf due to the fact keyring entries could be changed */
55    static const char * gpg_objs[] = {"pubring.gpg", "secring.gpg", "trustdb.gpg"};
56  static char*  static gpg_watcher_s gpg_table[3];
57  multi_gnupg_path (void)  static int gpg_table_count = DIM (gpg_table);
58  {  
59      static char buf[256+64];  int idea_available = 0;
60      BOOL ec;  
61    static int check_keyring (char ** r_path);
62      memset (buf, 0, sizeof (buf));  
63      ec = SHGetSpecialFolderPath (HWND_DESKTOP, buf, CSIDL_APPDATA, TRUE);  
64      if (ec != 1)  /* Return the application data folder of the current user. */
65          return NULL;  char*
66      strcat (buf, "\\gnupg");  multi_gnupg_path (int strict)
67      if (access (buf, 00))  {
68          return NULL;      static char buf[256+64];
69      return buf;      BOOL ec;
70  }  
71        /* MSDN: buf must be at least MAX_PATH=256 bytes */
72  /*      memset (buf, 0, sizeof (buf));
73   * Return the full path of the GnuPG application. First the registry is scanned      /* XXX: ec should be NOERROR (MSDN) but NOERROR is defined as '0' !? */
74   * for the entry 'HomeDir'. If it wasn't set, the default dir C:\GNUPG is used.      ec = SHGetSpecialFolderPath (HWND_DESKTOP, buf, CSIDL_APPDATA, TRUE);
75   */      if (ec != 1) {
76  char*          log_debug ("multi_gnupg_path: SHGetSpecialFolderPath() failed\r\n",
77  get_gnupg_path (void)                     (int)GetLastError ());
78  {          return NULL;
79      char *p = NULL, *path = NULL;          }
80            strcat (buf, "\\gnupg");
81      p = get_reg_entry_gpg ("HomeDir");      if (strict && access (buf, 00))
82      if (p) {          return NULL;
83          path = m_strdup (p);      return m_strdup (buf);
84          free_if_alloc (p);  }
85          return path;  
86      }  
87      else {  /* Return the full path to the GPG home directory. First the 'HomeDir' entry
88          p = multi_gnupg_path ();     from the registry is used. Then the default $APPDATA\gnupg path. */
89          if (p)  char*
90              return m_strdup (p);  get_gnupg_path (void)
91      }  {
92      return m_strdup ("c:\\gnupg");      char *path;
93  } /* get_gnupg_path */  
94        path = get_reg_entry_gpg (GPG_REG_HOME);
95        if (path) {
96  char*          if (dir_exist_check (path) == 0)
97  get_gnupg_cfgfile (void)              return path;
98  {              free_if_alloc (path);
99      char *p = NULL, *optfile = NULL, *path = NULL;      }
100      size_t nlen = 0;      path = multi_gnupg_path (1);
101        return path;
102      path = get_gnupg_path ();  }
103      if (path == NULL)  
104          return NULL;  
105      p = get_reg_entry_gpg ("OptFile");  /* Return the full path of the gpg config file.
106      if (p && !strcmp (p, ""))     A value of NULL indicates an error. */
107      {  char*
108          nlen = strlen (path) + 64;  get_gnupg_cfgfile (void)
109          optfile = new char[nlen + 1];  {    
110          if (optfile == NULL)      char *p = NULL;
111              BUG (0);      char *optfile = NULL;
112          _snprintf (optfile, nlen, "%s\\"GPG_CONF, path);      char *path = NULL;
113      }      size_t nlen = 0;
114      else if( p ) {  
115          nlen = strlen( p ) + 4;      path = get_gnupg_path ();
116          optfile = new char[nlen + 1];      if (!path)
117          if( optfile == NULL )          return NULL;
118              BUG( NULL );      nlen = strlen (path) + 64;
119          _snprintf( optfile, nlen, "%s", p );      optfile = new char[nlen + 1];
120      }      if (!optfile)
121      else {          BUG (NULL);    
122          nlen = strlen( path ) + 64;      _snprintf (optfile, nlen, "%s\\"GPG_CONF, path);
123          optfile = new char[nlen + 1];  
124          if( optfile == NULL )      free_if_alloc (path);
125              BUG( NULL );      free_if_alloc (p);
126          _snprintf( optfile, nlen, "%s\\"GPG_CONF, path );      return optfile;
127      }  }
128      free_if_alloc (path);  
129      free_if_alloc (p);  
130    /* Return the full path of the keyring. If @pub is 1, the public
131      return optfile;     keyring is return, otherwise the secret keyring. */
132  } /* get_gnupg_cfgfile */  char*
133    get_gnupg_keyring (int pub, int strict)
134    {    
135  char *      char *optfile = NULL;
136  get_gnupg_keyring (int pub, int strict)      char *path = NULL;
137  {          char *keyring = NULL;
138      char * optfile = NULL, * path = NULL;  
139      char * keyring = NULL;      path = get_gnupg_path ();
140        if (!path)
141      path = get_gnupg_path ();          return NULL;
142      if (!path)      keyring = make_filename (path, pub? "pubring" : "secring", "gpg");
143          return NULL;      if (strict && !file_exist_check (keyring)) {
144      keyring = make_filename (path, pub? "pubring" : "secring", "gpg");          free_if_alloc (path);
145      if (!strict && !file_exist_check (keyring)) {          return keyring;
146          free_if_alloc (path);      }
147          return keyring;      else if (!strict) {
148      }          free_if_alloc (path);
149      if (file_exist_check (keyring) || get_file_size (keyring) == 0) {          return keyring;
150          free_if_alloc (keyring);      }
151          optfile = make_filename (path, GPG_CONF, NULL);      if (file_exist_check (keyring) || pub && get_file_size (keyring) == 0) {
152          keyring = get_gnupg_keyring_from_options (optfile, pub);          free_if_alloc (keyring);
153      }          optfile = make_filename (path, GPG_CONF, NULL);
154      free_if_alloc (path);          keyring = get_gnupg_keyring_from_options (optfile, pub);
155      free_if_alloc (optfile);      }
156      return keyring;      free_if_alloc (path);
157  } /* get_gnupg_keyring */      free_if_alloc (optfile);
158        return keyring;
159    }
160  /*  
161   * Return the full path (with the gpg exe name). First the registry is scanned  
162   * for the entry 'gpgProgram'. If it wasn't set, the default path is the  /* Return the full path (with the gpg exe name). First the registry is scanned
163   * appended string 'gpg.exe' is used.     for the entry 'gpgProgram'. If it wasn't set, the default path is the
164   */     appended string 'gpg.exe' is used. */
165  char*  
166  get_gnupg_prog( void )  /* FIXME:  Use gpgme's engine info here. */
167  {      char*
168      char *p, *path, *pgm = NULL;  get_gnupg_prog (void)
169      size_t nlen = 0;  {    
170                char *p;
171      path = get_gnupg_path ();      char *pgm = NULL;
172      if (path == NULL)  
173          return NULL;      p = get_reg_entry_gpg (GPG_REG_EXE);
174        if (!p) {
175      p = get_reg_entry_gpg ("gpgProgram");          char *path = get_gnupg_path ();
176      if (p == NULL)          if (!path)
177          pgm = make_filename (path, "gpg", "exe");              return NULL;
178      else {          pgm = make_filename (path, "gpg", "exe");
179          pgm = m_strdup (p);          free_if_alloc (path);
180          free_if_alloc (p);      }
181      }      else {
182      free_if_alloc (path);          pgm = m_strdup (p);
183      return pgm;          free_if_alloc (p);
184  } /* get_gnupg_prog */      }
185        return pgm;
186    }
187  static char *  
188  default_key_from_cache (int * ret_no_useable)  
189  {  /* Retrieve the first usable secret key from cache.
190      const char * s;     If no usable was found, @ret_no_useable is 1.
191      char * keyid = NULL;     Return value: the keyid of the secret key. */
192      gpgme_key_t key;  static char *
193      gpgme_keycache_t sec = keycache_get_ctx (0);  default_key_from_cache (int *ret_no_useable)
194    {    
195      if (!sec)      gpgme_key_t key, pk;
196          BUG (0);      gpg_keycache_t sec, pub;
197      gpgme_keycache_rewind (sec);      const char *s;
198      while (!gpgme_keycache_next_key (sec, 1, &key))      char *keyid = NULL;
199      {  
200          if (gpgme_key_get_ulong_attr (key, GPGME_ATTR_KEY_USABLE, NULL, 0))      sec = keycache_get_ctx (0);
201          {      if (!sec)
202              s = gpgme_key_get_string_attr (key, GPGME_ATTR_KEYID, NULL, 0);          BUG (0);
203              if (s)          pub = keycache_get_ctx (1);
204                  keyid = m_strdup (s+8);      gpg_keycache_rewind (sec);
205              break;      while (!gpg_keycache_next_key (sec, 1, &key)) {
206          }          if (key_is_useable (key) && !get_pubkey (key->subkeys->keyid, &pk)) {
207      }              s = key->subkeys->keyid;
208      if (!keyid)              if (s)
209      {                  keyid = m_strdup (s+8);
210          *ret_no_useable = 1;              break;
211          msg_box( NULL, _("No useable secret key found."), _("GPG Error"), MB_ERR);          }
212      }      }
213      return keyid;      if (!keyid)
214  } /* default_key_from_cache */          *ret_no_useable = 1;    
215        return keyid;
216    }
217  char *  
218  get_gnupg_default_key (void)  
219  {      /* Load the gpg.conf and search for some options
220      gpg_optfile_t opt = NULL;     and store the result in the global preference context.
221      gpg_option_t e;     Return value: 0 on success. */
222      char * keyid = NULL, * optfile = NULL;  int
223      int no_usable=0, rc = 0;  gnupg_load_config (void)
224    {
225      optfile = get_gnupg_cfgfile ();      int rc;
226      if (!optfile)      gpg_optfile_t opt;
227          return default_key_from_cache( &no_usable );      gpg_option_t o;
228      rc = parse_gpg_options( optfile, &opt );      char *conf;
229      if( rc ) {      
230          free_if_alloc( optfile );      conf = get_gnupg_cfgfile ();
231          return default_key_from_cache( &no_usable );      if (!conf)
232      }          return -1;
233      e = find_option( opt, "default-key" );      rc = parse_gpg_options (conf, &opt);
234      if ( e )      if (rc) {
235          keyid = m_strdup( e->val );          free_if_alloc (conf);
236      if( !e ) {          return -1;
237          e = find_option( opt, "local-user" );      }
238          if( e )      o = find_option (opt, "ask-cert-level");
239              keyid = m_strdup( e->val );      if (o)
240      }          reg_prefs.gpg.ask_cert_level = 1;
241      if( !e ) {      o = find_option (opt, "ask-cert-expire");
242          e = find_option( opt, "encrypt-to" );      if (o)
243          if( e )          reg_prefs.gpg.ask_cert_expire = 1;
244              keyid = m_strdup( e->val );      release_gpg_options (opt);
245      }      free_if_alloc (conf);
246      free_if_alloc( optfile );      return 0;
247      release_gpg_options( opt );      }
248    
249      if( !keyid )  
250          keyid = default_key_from_cache( &no_usable );  /* handle the case the user added a '!' to force a subkey. */
251      return keyid;  static char*
252  } /* get_gnupg_default_key */  extract_keyid (const char *val)
253    {    
254  /*      size_t len = strlen (val);
255   * Check if the gpg application (exe file) is available.  
256   */      if (len > 1 && val[len-1] == '!') {
257  int          char *p = new char[len+1];
258  check_gnupg_prog( void )          if (!p)
259  {              BUG (0);
260      char *pgm = NULL;          memset (p, 0, len+1);
261      int rc = 0;          memcpy (p, val, len-1);
262            return p;
263      pgm = get_gnupg_prog( );      }
264      if( pgm == NULL )      return m_strdup (val);
265          rc = WPTERR_GPG_EXEFILE;  }
266      if( file_exist_check( pgm ) )  
267          rc = WPTERR_GPG_EXEFILE;  
268      free_if_alloc( pgm );  char*
269      return rc;  get_gnupg_default_key (void)
270  } /* check_gpg_prog */  {    
271        gpg_optfile_t opt = NULL;
272        gpg_option_t e;
273  static int      char *keyid = NULL, *optfile = NULL;
274  parse_version_nr( const char * buf, int *major, int *minor, int *patch )      int no_usable=0, rc = 0;
275  {  
276      char tmp[8];      optfile = get_gnupg_cfgfile ();
277      int i;      if (!optfile)
278                return default_key_from_cache (&no_usable);
279      if( strncmp( buf, "gpg ", 4 ) )      rc = parse_gpg_options (optfile, &opt);
280          return -1;          if (rc) {
281      buf += 4;          free_if_alloc (optfile);
282      if( strncmp( buf, "(GnuPG) ", 8 ) )          return default_key_from_cache (&no_usable);
283          return -1;          }
284      buf += 8;      e = find_option (opt, "default-key");
285      i=0;      if (!e)
286      while( buf && *buf != '.' && i < 8 )          e = find_option (opt, "local-user");
287          tmp[i++] = *buf++;      if (e)
288      tmp[i] = 0; buf++;          keyid = extract_keyid (e->val);
289      *major = atol( tmp );  
290      i=0;      free_if_alloc (optfile);
291      while( buf && *buf != '.' && i < 8 )      release_gpg_options (opt);
292          tmp[i++] = *buf++;      if (!keyid)
293      tmp[i] = 0; buf++;          keyid = default_key_from_cache (&no_usable);
294      *minor = atol( tmp );      return keyid;
295      i=0;  }
296      while( buf && isdigit( *buf ) && i < 8 )  
297          tmp[i++] = *buf++;  
298      tmp[i] = 0;  /* Check if GPG4WIN is available and if so, use the
299      *patch = atol( tmp );     install path to figure out where the gpg.exe is. */
300      return 0;  char*
301  }  check_for_gpg4win (void)
302    {
303        return get_reg_entry_gpg4win ("gpg.exe");
304  int  }
305  check_gnupg_engine (int * r_major, int * r_minor, int * r_patch)  
306  {  
307      gpgme_error_t err;  /* Check if the gpg application (exe file) is available. */
308      char * eng = NULL;  int
309      int major=0, minor=0, patch=0;  check_gnupg_prog (void)
310      int rc;  {
311                char *gpgexe = NULL;
312      err = gpgme_op_version( &eng );      int rc = 0;
313      if( err )  
314          return -1;      gpgexe = get_gnupg_prog ();
315      if( strstr( eng, "IDEA" ) )      if (!gpgexe || file_exist_check (gpgexe)) {
316          idea_available = 1;          free_if_alloc (gpgexe);
317      rc = parse_version_nr( eng, &major, &minor, &patch );          gpgexe = check_for_gpg4win ();
318      free( eng ); eng = NULL;          if (!gpgexe || file_exist_check (gpgexe))
319      if( rc )              rc = WPTERR_GPG_EXEFILE;
320          return rc;          else
321      if( major < *r_major              set_reg_entry_gpg (GPG_REG_EXE, gpgexe);
322       || minor < *r_minor)      }
323          rc = 1;      free_if_alloc (gpgexe);
324      else {      return rc;
325          if (patch < *r_patch )  }
326              rc = 1;  
327          rc = 0;  
328      }  static int
329      *r_major = major;  parse_version_nr (const char *buf, int *major, int *minor, int *patch)
330      *r_minor = minor;  {
331      *r_patch = patch;      char tmp[8];
332      return rc;      int i;
333  } /* check_gnupg_engine */      
334        i=0;
335        while (buf && *buf != '.' && i < 8)
336  int          tmp[i++] = *buf++;
337  check_gnupg_cfgfile (const char *fname, int *r_secrings, int *r_pubrings)      tmp[i] = 0; buf++;
338  {      *major = atoi (tmp);
339      gpg_optfile_t opt;          i=0;
340      gpg_option_t e;      while (buf && *buf != '.' && i < 8)
341      int rc = 0;          tmp[i++] = *buf++;
342        tmp[i] = 0; buf++;
343      if( r_secrings )      *minor = atoi (tmp);
344          *r_secrings = 0;      i=0;
345      if( r_pubrings )      while (buf && isdigit (*buf) && i < 8)
346          *r_pubrings = 0;          tmp[i++] = *buf++;
347      rc = parse_gpg_options( fname, &opt );      tmp[i] = 0;
348      if( rc )      *patch = atoi (tmp);
349          return WPTERR_FILE_OPEN;      return 0;
350    }
351      for( e = opt->list; e; e = e->next ) {  
352          if( !strcmp( e->name, "secret-keyring" ) ) {  
353              if( !file_exist_check( e->val ) )  /* Check if the gnupg engine fullfills the minimum requirement
354                  r_secrings[0]++;     version given in @r_major.@r_minor.@r_patch. On success these
355          }     variables contain the GPG version which is installed. */
356          else if( !strcmp( e->name, "keyring" ) ) {  int
357              if( !file_exist_check( e->val ) )  check_gnupg_engine (const char *need_gpg_ver,
358                  r_pubrings[0]++;                      int *r_major, int *r_minor, int *r_patch)
359          }  {
360      }      gpgme_ctx_t ctx;
361      release_gpg_options( opt );      gpgme_engine_info_t inf;
362      return 0;      char *eng = NULL;
363  } /* check_gnupg_cfgfile */      int major=0, minor=0, patch=0;
364        int need_major = 0, need_minor = 0, need_patch = 0;
365  /*      int rc = 1;
366   * Check if both keyrings are located in the gnupg home directory.  
367   */      /* Convert the needed GPG version to the integer format. */
368  int      if (parse_version_nr (need_gpg_ver,
369  gnupg_access_files (void)                            &need_major, &need_minor, &need_patch))
370  {          return 1;
371      int rc = 0;      
372      int pubring_ok = 0, secring_ok = 0;      gpgme_new (&ctx);
373      int secrings = 0, pubrings = 0;      inf = gpgme_ctx_get_engine_info (ctx);
374      char *optfile;      if (!inf) {
375            gpgme_release (ctx);
376      if (gnupg_access_keyring (1))          return -1;
377          rc = WPTERR_GPG_KEYRINGS;      }
378      else  
379          pubring_ok = 1;      /* We need to exec GPG again to find out if IDEA is available. */
380        if (gpg_get_version (&eng))
381      if (gnupg_access_keyring (0))          return -1;
382          rc = WPTERR_GPG_KEYRINGS;      if (strstr (eng, "IDEA"))
383      else          idea_available = 1;
384          secring_ok = 1;      safe_free (eng);
385      if (!pubring_ok || !secring_ok) {      if (parse_version_nr (inf->version, &major, &minor, &patch)) {
386          optfile = get_gnupg_cfgfile ();          gpgme_release (ctx);
387          if (!optfile)          return 1;
388              return WPTERR_GPG_KEYRINGS;      }
389          rc = file_exist_check (optfile);      gpgme_release (ctx);
390          if (!rc && get_file_size(optfile) > 0) {  
391              rc = check_gnupg_cfgfile (optfile, &secrings, &pubrings);      if (major > need_major)
392              if (!rc && secrings && pubrings) {          rc = 0;
393                  free_if_alloc (optfile);      else if (major == need_major && minor > need_minor)      
394                  return 0; /* found two keyrings in the option file */          rc = 0;
395              }      else if (major == need_major && minor == need_minor &&
396              else if ((!rc && pubrings && secring_ok)               patch >= need_patch)
397                    || (!rc && secrings && pubring_ok)) {          rc = 0;
398                  free_if_alloc (optfile);  
399                  return 0; /* found one keyring and one entry in the options file */      /* Return the current GPG version. */
400              }      *r_major = major;
401              else      *r_minor = minor;
402                  return WPTERR_GPG_OPT_KEYRINGS;      *r_patch = patch;
403          }      return rc;
404          free_if_alloc (optfile);  }
405          rc = WPTERR_GPG_KEYRINGS;  
406      }  
407      return rc;  int
408  } /* gnupg_access_files */  check_gnupg_cfgfile (const char *fname, int *r_secrings, int *r_pubrings)
409    {
410        gpg_optfile_t opt;    
411  static int      gpg_option_t e;
412  create_gpg_options( void )  
413  {      *r_secrings = 0;
414      FILE *fp;      *r_pubrings = 0;
415      char *s, *optfile;      if (parse_gpg_options (fname, &opt))
416            return WPTERR_FILE_OPEN;
417      s = get_gnupg_path( );  
418      if( s == NULL )      for (e = opt->list; e; e = e->next) {
419          return WPTERR_FILE_CREAT;          if (!strcmp( e->name, "secret-keyring")) {
420      optfile = make_filename( s, GPG_CONF, NULL );              if (!file_exist_check (e->val))
421      fp = fopen( optfile, "wb" );                  r_secrings[0]++;
422      if( fp == NULL ) {            }
423          return WPTERR_FILE_CREAT;          else if (!strcmp (e->name, "keyring")) {
424          goto fail;              if (!file_exist_check (e->val))
425      }                  r_pubrings[0]++;
426      fwrite( options_skel, 1, strlen( options_skel ), fp );          }
427      fclose( fp );      }
428        release_gpg_options (opt);
429  fail:      return 0;
430      free_if_alloc( s );  }
431      free_if_alloc( optfile );  
432      return 0;  
433  } /* create_gpg_options */  /* Usually GPG creates the pubring.gpg, secring.gpg on
434       the first start, but to make sure they always exist
435       create them empty if needed. */
436  /*  static void
437   * Return the contents of the options file as a char buf.  create_empty_keyring (int _pub)
438   */  {
439  char *      char *name;
440  get_gnupg_config( void )      FILE *fp;
441  {  
442      FILE * fp;      name = get_gnupg_keyring (_pub, 0);
443      char * p = NULL, * optfile = NULL;      if (name && file_exist_check (name) != 0) {
444      int fsize, rc = 0;          fp = fopen (name, "ab");
445                    if (fp != NULL)
446      optfile = get_gnupg_cfgfile( );              fclose (fp);
447      if( optfile == NULL )      }
448          return NULL;      free_if_alloc (name);
449      fsize = get_file_size( optfile );  }
450      if( !fsize ) {  
451          rc = create_gpg_options( );  
452          if ( rc )  /* Check if both keyrings are located in the gnupg home directory. */
453              return NULL;  int
454          fsize = get_file_size( optfile );  gnupg_access_files (void)
455      }  {
456      if( fsize > 100000 )      int rc = 0;
457          goto leave; /* too large */      int pubring_ok = 0, secring_ok = 0;
458      p = new char[fsize+1];      int secrings = 0, pubrings = 0;
459      if( p == NULL )      char *optfile;
460          BUG( NULL );  
461      fp = fopen( optfile, "rb" );      create_empty_keyring (1);
462      if( fp == NULL ) {      if (gnupg_access_keyring (1))
463          free_if_alloc( p );          rc = WPTERR_GPG_KEYRINGS;
464          return NULL;      else
465      }          pubring_ok = 1;
466      fread( p, 1, fsize, fp );  
467      fclose( fp );      create_empty_keyring (0);
468      p[fsize] = '\0';      if (gnupg_access_keyring (0))
469      free_if_alloc( optfile );          rc = WPTERR_GPG_KEYRINGS;
470        else
471  leave:          secring_ok = 1;
472      return p;  
473  } /* get_gnupg_config */      if (!pubring_ok || !secring_ok) {
474            optfile = get_gnupg_cfgfile ();
475            if (!optfile)
476  int              return WPTERR_GPG_KEYRINGS;
477  set_gnupg_default_key (const char * key)          rc = file_exist_check (optfile);
478  {          if (!rc && get_file_size (optfile) > 0) {
479      gpg_optfile_t opt;              rc = check_gnupg_cfgfile (optfile, &secrings, &pubrings);
480      gpg_option_t e;              if (!rc && secrings > 0 && pubrings > 0) {
481      char *optfile = NULL;                  free_if_alloc (optfile);
482      int rc = 0;                  return 0; /* found two keyrings in the option file */
483                }
484      optfile = get_gnupg_cfgfile ();              else if ((!rc && pubrings && secring_ok)
485      if (!optfile)                    || (!rc && secrings && pubring_ok)) {
486          return -1;                  free_if_alloc (optfile);
487      rc = parse_gpg_options (optfile, &opt);                  return 0; /* found one keyring and one entry in the options file */
488      if( rc ) {              }
489          free_if_alloc (optfile);              else
490          return -1;                  return WPTERR_GPG_OPT_KEYRINGS;
491      }          }
492      e = find_option (opt, "default-key");          free_if_alloc (optfile);
493      if (e) {          rc = WPTERR_GPG_KEYRINGS;
494          free_if_alloc (e->val);      }
495          e->val = m_strdup (key);      return rc;
496          e->used = 1;  }
497      }  
498      else  
499          add_entry (opt, ENTRY_MULTI, "default-key", key);  static int
500      rc = commit_gpg_options (optfile, opt);  create_gpg_options (void)
501    {
502      free_if_alloc (optfile);      FILE *fp;
503      release_gpg_options (opt);      char *s, *optfile;
504    
505      return rc;      s = get_gnupg_path ();
506  } /* set_gnupg_default_key */      if (!s)
507            return WPTERR_FILE_CREAT;
508        optfile = make_filename (s, GPG_CONF, NULL);
509  /*      fp = fopen (optfile, "wb");
510   * Set the contents of the options file.      if (!fp) {
511   */          return WPTERR_FILE_CREAT;
512  int          goto fail;
513  set_gnupg_options( const char *buf, size_t buflen )      }
514  {      fwrite (options_skel, 1, strlen (options_skel), fp);
515      FILE *fp;        fclose (fp);
516      char *optfile = NULL;  
517    fail:
518      optfile = get_gnupg_cfgfile( );      free_if_alloc (s);
519      if( optfile == NULL )      free_if_alloc (optfile);
520          return WPTERR_FILE_CREAT;      return 0;
521    }
522      fp = fopen( optfile, "wb" );  
523      if( fp == NULL ) {  
524          free_if_alloc( optfile );  /* Return the contents of the options file as a char buf. */
525          return WPTERR_FILE_CREAT;  char*
526      }  get_gnupg_config (void)
527      fwrite( buf, 1, buflen, fp );  {
528      fclose( fp );      FILE *fp;
529      free_if_alloc( optfile );      char *p = NULL, *optfile = NULL;
530      return 0;      int fsize, rc = 0;
531  } /* set_gnupg_options */          
532        optfile = get_gnupg_cfgfile ();
533  /*      if (optfile == NULL)
534   * Check if the line contains a valid GPG argument.          return NULL;
535   */      fsize = get_file_size (optfile);
536  static int      if (!fsize) {
537  check_line( const char *buf )          rc = create_gpg_options ();
538  {          if (rc)
539      int j, len;              return NULL;
540      int rc = 0;          fsize = get_file_size (optfile);
541        }
542      if( *buf == '#' || *buf == '\r' || *buf == '\n' )      if (fsize > 100000)
543          return 1;          goto leave; /* too large */
544      rc = 0;      p = new char[fsize+1];
545      for ( j = 0; valid_gpg_args[j]; j++ ) {      if (!p)
546          len = strlen( valid_gpg_args[j] );          BUG (NULL);
547          if( !strncmp( valid_gpg_args[j], buf, len ) )      fp = fopen( optfile, "rb" );
548              rc = 1;          if (!fp) {
549      }          free_if_alloc (p);
550            return NULL;
551      return rc;      }
552  } /* check_line */      fread (p, 1, fsize, fp);
553        fclose (fp);
554        p[fsize] = '\0';
555  int      free_if_alloc (optfile);
556  check_gnupg_options( const char *buf )  
557  {  leave:
558      char line[1024];      return p;
559      int nbytes = 0;  }
560      unsigned j;  
561            
562      for ( j = 0; j<strlen( buf ) && j < sizeof(line); j++ ) {  /* Set the default key in the gpg.conf.
563          line[nbytes++] = buf[j];     If @key is NULL, the entry will be deleted. */
564          if ( buf[j] == '\n' || j == ( strlen( buf ) - 1 ) ) {  int
565              line[nbytes] = '\0';  set_gnupg_default_key (const char *key)
566              if( !check_line( line ) ) {  {
567                  msg_box( NULL, line, "options", MB_OK );      gpg_optfile_t opt;
568                  return 1;            gpg_option_t e;
569              }      char *optfile = NULL;
570              nbytes = 0;      int rc = 0;
571          }        
572      }      optfile = get_gnupg_cfgfile ();
573        if (!optfile)
574      return 0;          return WPTERR_FILE_OPEN;
575  } /* check_gnupg_options */      rc = parse_gpg_options (optfile, &opt);
576        if (rc) {
577            free_if_alloc (optfile);
578  static int          return WPTERR_GENERAL;
579  get_last_gnupg_access (gpg_watcher_s * ctx)      }
580  {      e = find_option (opt, "default-key");
581      HANDLE fd;      if (e && !key)
582      char *path = NULL, *file = NULL;          e->used = 0;
583        else if (e) {
584      path = get_gnupg_path ();          free_if_alloc (e->val);
585      file =  make_filename (path, ctx->object, NULL);          e->val = m_strdup (key);
586      fd = CreateFile (file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL);          e->used = 1;
587      if( fd == INVALID_HANDLE_VALUE ) {      }
588          free_if_alloc (path);      else if (key)
589          free_if_alloc (file);          add_entry (opt, ENTRY_MULTI, "default-key", key);
590          return WPTERR_FILE_OPEN;      rc = commit_gpg_options (optfile, opt);
591      }  
592      GetFileTime (fd, NULL, NULL, &ctx->access);      free_if_alloc (optfile);
593      CloseHandle (fd);      release_gpg_options (opt);
594      free_if_alloc (path);        
595      free_if_alloc (file);      return rc;
596      return 0;  }
597  } /* get_last_gnupg_access */  
598    
599    /* Set the contents of the options file. */
600  static void  int
601  check_last_gnupg_access( gpg_watcher_s *ctx )  set_gnupg_options( const char *buf, size_t buflen )
602  {                {
603      ctx->modified = 0;      FILE *fp;  
604        char *optfile = NULL;
605      if( ctx->last_access.dwHighDateTime != ctx->access.dwHighDateTime &&  
606          ctx->last_access.dwLowDateTime != ctx->access.dwLowDateTime )        optfile = get_gnupg_cfgfile( );
607          ctx->modified = 1;      if( optfile == NULL )
608            return WPTERR_FILE_CREAT;
609      ctx->last_access.dwLowDateTime = ctx->access.dwLowDateTime;  
610      ctx->last_access.dwHighDateTime = ctx->access.dwHighDateTime;      fp = fopen( optfile, "wb" );
611  } /* check_last_gnupg_access */      if( fp == NULL ) {
612            free_if_alloc( optfile );
613            return WPTERR_FILE_CREAT;
614  void      }
615  init_gnupg_table (void)      fwrite( buf, 1, buflen, fp );
616  {            fclose( fp );
617      int j;      free_if_alloc( optfile );
618        return 0;
619      for (j = 0; j < gpg_table_count; j++) {  } /* set_gnupg_options */
620          gpg_table[j].object = m_strdup (gpg_objs[j]);  
621          memset (&gpg_table[j].access, 0, sizeof (FILETIME));  /*
622          memset (&gpg_table[j].last_access, 0, sizeof (FILETIME));   * Check if the line contains a valid GPG argument.
623          gpg_table[j].modified = 0;   */
624      }  static int
625  } /* init_gnupg_table */  check_line( const char *buf )
626    {
627        int j, len;
628  void      int rc = 0;
629  free_gnupg_table (void)  
630  {      if( *buf == '#' || *buf == '\r' || *buf == '\n' )
631      int j;          return 1;
632        rc = 0;
633      for (j=0; j < gpg_table_count; j++)      for ( j = 0; valid_gpg_args[j]; j++ ) {
634          free_if_alloc (gpg_table[j].object);          len = strlen( valid_gpg_args[j] );
635  } /* free_gnupg_table */          if( !strncmp( valid_gpg_args[j], buf, len ) )
636                rc = 1;    
637        }
638  int  
639  keyring_check_last_access (void)      return rc;
640  {        } /* check_line */
641      int rc, j;  
642    
643      rc = 0;  int
644      for (j = 0; j < gpg_table_count; j++) {  check_gnupg_options( const char *buf )
645          get_last_gnupg_access( &gpg_table[j] );  {
646          check_last_gnupg_access( &gpg_table[j] );      char line[1024];
647          if ( gpg_table[j].modified )      int nbytes = 0;
648              rc++;            unsigned j;
649      }          
650        for ( j = 0; j<strlen( buf ) && j < sizeof(line); j++ ) {
651      return rc;          line[nbytes++] = buf[j];
652  } /* keyring_check_last_access */          if ( buf[j] == '\n' || j == ( strlen( buf ) - 1 ) ) {
653                line[nbytes] = '\0';
654                if( !check_line( line ) ) {
655  const char *                  msg_box( NULL, line, "options", MB_OK );
656  gnupg_check_file_ext (const char * fname)                  return 1;      
657  {                            }
658      char file_ext[5];              nbytes = 0;
659            }      
660      if (!strchr( fname, '.' ))      }
661          return "UNKNOWN";  
662        return 0;
663      strncpy (file_ext, fname + strlen (fname) - 4, 4);  } /* check_gnupg_options */
664      file_ext[4] = '\0';  
665      if (!stricmp (file_ext, ".asc"))  
666          return "ARMORED";  /* Store the last access of the file inside the watcher @ctx. */
667      else if (!stricmp (file_ext, ".sig"))  static int
668          return "SIGNED";  get_last_gnupg_access (gpg_watcher_s *ctx)
669      else if  (!stricmp (file_ext, ".gpg")  {
670          || !stricmp (file_ext, ".pgp"))      HANDLE fd;
671          return "ENCRYPTED";      char *path;
672      else      char *file;
673          return "UNKNOWN";  
674                path = get_gnupg_path ();
675      return "UNKNOWN";      file =  make_filename (path, ctx->object, NULL);
676  } /* gnupg_check_file_ext */      fd = CreateFile (file, GENERIC_READ, FILE_SHARE_READ, NULL,
677                         OPEN_ALWAYS, 0, NULL);
678        if (fd == INVALID_HANDLE_VALUE) {
679  char *          free_if_alloc (path);
680  get_gnupg_keyring_from_options (const char * fname, int pub)          free_if_alloc (file);
681  {          return WPTERR_FILE_OPEN;
682      gpg_optfile_t opt;      }
683      gpg_option_t e;      GetFileTime (fd, NULL, NULL, &ctx->access);
684      char * kring = NULL;      CloseHandle (fd);
685      int rc = 0;      free_if_alloc (path);
686        free_if_alloc (file);
687      rc = parse_gpg_options (fname, &opt);      return 0;
688      if (rc)  }
689          return NULL;  
690      if (pub)  
691          e = find_option (opt, "keyring");  /* Check if the file inside watcher @ctx was modified. */
692      else  static void
693          e = find_option (opt, "secret-keyring");  check_last_gnupg_access (gpg_watcher_s *ctx)
694      if (e)  {              
695          kring = m_strdup (e->val);      ctx->modified = 0;
696      release_gpg_options (opt);  
697        if (ctx->last_access.dwHighDateTime != ctx->access.dwHighDateTime &&
698      return kring;          ctx->last_access.dwLowDateTime != ctx->access.dwLowDateTime)
699  } /* get_gnupg_keyring_from_options */          ctx->modified = 1;
700        
701        /* XXX: find a better way. without it, winpt --keymanager loads
702                the key cache twice. */
703  /* XXX: does not work with write-protected floppies */      if (ctx->last_access.dwLowDateTime == 0)
704  static int          ctx->modified = 0;
705  my_access (const char * fname)  
706  {      ctx->last_access.dwLowDateTime = ctx->access.dwLowDateTime;
707      HANDLE hd;      ctx->last_access.dwHighDateTime = ctx->access.dwHighDateTime;
708      hd = CreateFile (fname, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);  }
709      if (hd == INVALID_HANDLE_VALUE)  
710          return -1;  
711      CloseHandle (hd);  /* Init GPG watcher table for all monitored files. */
712      return 0;  void
713  } /* my_access */  init_gnupg_table (void)
714    {      
715        char *p;
716  int      int j;
717  gpg_check_permissions (int showmsg)  
718  {      for (j = 0; j < gpg_table_count; j++) {
719      char * p, * name = NULL;          p = gpg_table[j].object = m_strdup (gpg_objs[j]);
720      int failed = 0, ans=0, attrs=0;          if (!p)
721                BUG (NULL);
722      p = get_gnupg_path ();          memset (&gpg_table[j].access, 0, sizeof (FILETIME));
723      check_keyring (&p);          memset (&gpg_table[j].last_access, 0, sizeof (FILETIME));
724      if (p) {          gpg_table[j].modified = 0;
725          name = make_filename (p, "pubring", "gpg");      }
726          free_if_alloc (p);  }
727          if ((attrs=GetFileAttributes (name)) & FILE_ATTRIBUTE_READONLY) {  
728              ans = msg_box (NULL,  
729                             _("The selected keyring has the read-only file\n"  void
730                               "attribute. In this state you do not have write\n"  free_gnupg_table (void)
731                               "access. Do you want to remove the attribute?"),  {
732                       _("GPG Information"), MB_YESNO);      int j;
733              if (ans == IDYES) {  
734                  attrs &= ~FILE_ATTRIBUTE_READONLY;      for (j=0; j < gpg_table_count; j++)
735                  if (!SetFileAttributes (name, attrs)) {          free_if_alloc (gpg_table[j].object);
736                      msg_box (NULL, _("Could not reset read-only state."),  }
737                               _("GPG Error"), MB_ERR);  
738                      failed = 1;  
739                  }  /* Return the amount of files modified since the last call. */
740              }  int
741              else if (ans == IDNO) {  keyring_check_last_access (void)
742                  /*  {      
743                  msg_box (NULL, _("All commands with write access to the keyring\n"      int rc, j;
744                                   "will be disabled."), _("GPG Information"), MB_INFO);  
745                  */      rc = 0;
746                  failed = 1;      for (j = 0; j < gpg_table_count; j++) {
747              }          get_last_gnupg_access (&gpg_table[j]);
748          }          check_last_gnupg_access (&gpg_table[j]);
749          if (my_access (name)) {          if (gpg_table[j].modified)
750              if (showmsg)              rc++;      
751                  msg_box (NULL,      }
752                  _("You do not have file access to modify the contents of\n"  
753                    "one or both of the selected keyrings.\n"      return rc;
754                    "\n"  }
755                    "The keyrings are in a read-only state which is propably\n"  
756                    "caused by another program which already opened the files.\n"),  
757                     _("GPG Warning"), MB_WARN);  const char*
758              failed = 2;  gnupg_check_file_ext (const char *fname, int *r_type)
759          }  {              
760      }      char file_ext[5];
761      free_if_alloc (name);  
762      return failed;      if (r_type)
763  } /* gpg_check_permissions */          *r_type = PGP_NONE;
764        if (!strchr (fname, '.' ))
765            return "UNKNOWN";
766  static int  
767  check_homedir (void)      strncpy (file_ext, fname + strlen (fname) - 4, 4);
768  {            file_ext[4] = '\0';
769      char * homedir = NULL;      if (!stricmp (file_ext, ".asc"))
770      int yes = 0;          return "ARMORED";
771        else if (!stricmp (file_ext, ".sig")) {
772      homedir = get_reg_entry_gpg ("HomeDir");          if (r_type)
773      if (!homedir)              *r_type = PGP_SIG;
774          homedir = multi_gnupg_path ();          return "SIGNED";
775      if (!homedir)      }
776          homedir = m_strdup ("c:\\gnupg");      else if  (!stricmp (file_ext, ".gpg") || !stricmp (file_ext, ".pgp")) {
777      if (homedir) {          if (r_type)
778          if (GetFileAttributes (homedir) == 0xFFFFFFFF) {              *r_type = PGP_MESSAGE;
779              yes = log_box (_("Preferences"), MB_YESNO,          return "ENCRYPTED";
780                             _("%s does not exit.\n"      }
781                               "Do you want to create this directory?"), homedir);      return "UNKNOWN";
782              if (yes == IDYES) {  }
783                  if (CreateDirectory (homedir, NULL) == FALSE) {  
784                      free_if_alloc (homedir);  
785                      return WPTERR_DIR_CREAT;  char*
786                  }  get_gnupg_keyring_from_options (const char * fname, int pub)
787              }  {
788              return WPTERR_DIR_OPEN;      gpg_optfile_t opt;
789          }      gpg_option_t e;
790          free_if_alloc (homedir);      char * kring = NULL;
791      }      int rc = 0;
792      return 0;  
793  } /* check_homedir */      rc = parse_gpg_options (fname, &opt);
794        if (rc)
795            return NULL;
796  int      if (pub)
797  gnupg_check_homedir (void)          e = find_option (opt, "keyring");
798  {            else
799      char *homedir = NULL, *prog = NULL;          e = find_option (opt, "secret-keyring");
800      int rc = 0, ec = 0;      if (e)
801                kring = m_strdup (e->val);
802      rc = check_homedir ();      release_gpg_options (opt);
803      if (rc)  
804          return rc;      return kring;
805      if ((homedir = get_reg_entry_gpg ("HomeDir")) &&  }
806          !(prog = get_reg_entry_gpg ("gpgProgram" ))) {  
807          prog = make_filename (homedir, "gpg", "exe");  
808          if (file_exist_check (prog) == 0) {  
809              rc = set_reg_entry_gpg ("gpgProgram", prog);  /* XXX: does not work with write-protected floppies */
810              if (rc)  static int
811                  goto fail;  my_access (const char *fname)
812          }  {
813          free_if_alloc (homedir);      HANDLE hd;
814          free_if_alloc (prog);      hd = CreateFile (fname, GENERIC_WRITE, FILE_SHARE_WRITE,
815          return rc;                       NULL, OPEN_EXISTING, 0, NULL);
816      }      if (hd == INVALID_HANDLE_VALUE)
817      if ((prog = get_reg_entry_gpg ("gpgProgram"))          return -1;
818          && file_exist_check (prog)) {      CloseHandle (hd);
819          free_if_alloc (prog);      return 0;
820          homedir = get_reg_entry_gpg ("HomeDir");  }
821          if (!homedir) {  
822              rc = WPTERR_GENERAL;  
823              goto fail;  /* Check the file permissions of the public keyring.
824          }     If @showmsg is 1 output a message in case of errors.
825          prog = make_filename (homedir, "gpg", "exe");     Return value: 1 if read-only attribute
826          if (file_exist_check (prog) == 0) {                   2 if file is opened by another process exclusively. */
827              rc = set_reg_entry_gpg ("gpgProgram", prog);  int
828              if (rc)  gpg_check_permissions (int showmsg)
829                  goto fail;  {
830              free_if_alloc (prog);      char *p = NULL;
831              return rc;      char *name = NULL;
832          }      int failed = 0, ans=0, attrs=0;
833      }  
834            p = get_gnupg_path ();
835      /* Change the return code if homedir doesn't exist or if the program      if (p && check_keyring (&p)) {
836         doesn't exist. Note that exist_checks return 0 to suggest existance. */          name = make_filename (p, "pubring", "gpg");
837      if ((!homedir || dir_exist_check (homedir)))          if ((attrs=GetFileAttributes (name)) & FILE_ATTRIBUTE_READONLY) {
838          rc = WPTERR_GENERAL;              ans = msg_box (NULL,
839                                   _("The selected keyring has the read-only file\n"
840  fail:                               "attribute. In this state you do not have write\n"
841      free_if_alloc (homedir);                               "access. Do you want to remove the attribute?"),
842      free_if_alloc (prog);                       _("GPG Information"), MB_YESNO);
843      return rc;              if (ans == IDYES) {
844  } /* gnupg_check_homedir */                  attrs &= ~FILE_ATTRIBUTE_READONLY;
845                    if (!SetFileAttributes (name, attrs)) {
846                        msg_box (NULL, _("Could not reset read-only state."),
847  int                               _("GPG Error"), MB_ERR);
848  gnupg_copy_keyrings (void)                      failed = 1;
849  {                  }
850      const char * pring, * sring;              }
851      char * file = NULL, * path = NULL;              else if (ans == IDNO) {
852      int id = 0, rc = 0;                  /* All commands with write access will be disabled. */
853      HWND hwnd;                  failed = 1;
854                    }
855      path = get_gnupg_path ();          }
856      if (!path)          if (my_access (name)) {
857          return WPTERR_GENERAL;              if (showmsg)
858      hwnd = GetDesktopWindow ();                  msg_box (NULL,
859                    _("You do not have file access to modify the contents of\n"
860      pring = get_filename_dlg (hwnd, FILE_OPEN, _("Please choose your public keyring"),                    "one or both of the selected keyrings.\n"
861                                _("GPG Keyrings (*.gpg)\0*.gpg\0\0"),NULL);                    "\n"
862      if (!pring) {                    "The keyrings are in a read-only state which is propably\n"
863          msg_box (hwnd, _("No keyring was chosen. Exit."), _("WinPT Error"), MB_ERR);                    "caused by another program which already opened the files.\n"),
864          free_if_alloc (path);                     _("GPG Warning"), MB_WARN);
865          return WPTERR_GENERAL;              failed = 2;
866      }          }
867      file = make_filename (path, "pubring", "gpg");      }
868      if (file_exist_check (file) == 0) {      free_if_alloc (p);
869          id = msg_box (hwnd, _("Overwrite old public keyring?"), "WinPT", MB_INFO|MB_YESNO);      free_if_alloc (name);
870          if (id == IDNO)      return failed;
871              goto fail;  }
872      }  
873      if (!CopyFile (pring, file, FALSE)) {  
874          msg_box (hwnd, _("Could not copy file."), _("WinPT Error"), MB_ERR);  /* Check the GPG home dir. First try to read the 'HomeDir' registry entry,
875          rc = WPTERR_FILE_READ;     then check for $APPDATA\gnupg. Create the dir if it does not exists. */
876          goto fail;  int
877      }  gnupg_check_homedir (void)
878      free_if_alloc (file);  {      
879        char *homedir = NULL;
880      sring = get_filename_dlg (hwnd, FILE_OPEN, _("Please choose your secret keyring"),      int val = 0;
881                                _("GPG Keyrings (*.gpg)\0*.gpg\0\0"), NULL);      int rc = 0;
882      if (!sring) {  
883          msg_box( NULL, _("No keyring was chosen. Exit."), _("WinPT Error"), MB_ERR );      homedir = get_reg_entry_gpg (GPG_REG_HOME);
884          return WPTERR_GENERAL;      if (!homedir)
885      }          homedir = multi_gnupg_path (0);
886      file = make_filename (path, "secring", "gpg");      if (homedir) {
887      if (file_exist_check (file) == 0) {          if (GetFileAttributes (homedir) == 0xFFFFFFFF) {
888          id = msg_box (hwnd, _("Overwrite old secret keyring?"), "WinPT", MB_INFO|MB_YESNO);              val = log_box (_("Preferences"), MB_YESNO,
889          if( id == IDNO )                             _("%s does not exit.\n"
890              goto fail;                               "Do you want to create this directory?"), homedir);
891      }              if (val == IDYES) {
892      if (!CopyFile (sring, file, FALSE)) {                  if (!CreateDirectory (homedir, NULL))
893          msg_box( NULL, _("Could not copy file."), _("WinPT Error"), MB_ERR);                      rc = WPTERR_DIR_CREAT;
894          rc = WPTERR_FILE_READ;              }
895      }              else
896                    rc = WPTERR_DIR_OPEN;
897  fail:          }
898      free_if_alloc (file);          free_if_alloc (homedir);
899      free_if_alloc (path);      }
900      return rc;      return rc;
901  } /* gnupg_import_keyrings */  }
902    
903    
904  void  int
905  gnupg_backup_options (int keep)  gnupg_copy_keyrings (void)
906  {  {
907      char *optfile = NULL;      const char * pring, * sring;
908      char bak[1024];      char * file = NULL, * path = NULL;
909        int id = 0, rc = 0;
910      optfile = get_gnupg_cfgfile ();      HWND hwnd;
911      if (optfile == NULL)      
912          return;      path = get_gnupg_path ();
913      if (keep)      if (!path)
914          _snprintf (bak, DIM (bak)-1, "%s.old", optfile);          return WPTERR_GENERAL;
915      else      hwnd = GetDesktopWindow ();
916          _snprintf (bak, DIM (bak)-1, "%s.O", optfile);  
917      CopyFile (optfile, bak, keep);      pring = get_fileopen_dlg (hwnd, _("Please choose your Public Keyring"),
918      free_if_alloc (optfile);                                "GPG Keyrings (*.gpg)\0*.gpg\0\0",NULL);
919  } /* gnupg_backup_options */      if (!pring) {
920            msg_box (hwnd, _("No keyring was chosen. Exit."),
921                     _("WinPT Error"), MB_ERR);
922            free_if_alloc (path);
923  static int          return WPTERR_GENERAL;
924  backup_one_file (const char * srcpath, const char * srcn,      }
925                   const char * dstpath, const char * dstn)      file = make_filename (path, "pubring", "gpg");
926  {      if (file_exist_check (file) == 0) {
927      char * src, * dst;          id = msg_box (hwnd, _("Overwrite old public keyring?"),
928      BOOL rc;                        "WinPT", MB_INFO|MB_YESNO);
929            if (id == IDNO)
930      src = make_filename (srcpath, srcn, "gpg");              goto fail;
931      if (!src)      }
932          BUG (NULL);      if (!CopyFile (pring, file, FALSE)) {
933      dst = make_filename (dstpath, dstn, "gpg");          msg_box (hwnd, _("Could not copy file."), _("WinPT Error"), MB_ERR);
934      if (!dst)          rc = WPTERR_FILE_READ;
935          BUG (NULL);          goto fail;
936      rc = CopyFile (src, dst, FALSE);      }
937      free_if_alloc (src);      free_if_alloc (file);
938      free_if_alloc (dst);  
939      if (!rc)      sring = get_fileopen_dlg (hwnd, _("Please choose your Secret Keyring"),
940      {                                "GPG Keyrings (*.gpg)\0*.gpg\0\0", NULL);
941          log_box (_("Backup"), MB_ERR, _("Backup keyring \"%s\" failed"), srcn);      if (!sring) {
942          return WPTERR_GENERAL;          msg_box (NULL, _("No keyring was chosen. Exit."),
943      }                   _("WinPT Error"), MB_ERR);
944      return 0;          return WPTERR_GENERAL;
945  } /* backup_one_file */      }
946        file = make_filename (path, "secring", "gpg");
947        if (file_exist_check (file) == 0) {
948  static int          id = msg_box (hwnd, _("Overwrite old secret keyring?"),
949  check_keyring (char ** r_path)                        "WinPT", MB_INFO|MB_YESNO);
950  {          if (id == IDNO)
951      char * p;              goto fail;
952      char * opt, * name;      }
953        if (!CopyFile (sring, file, FALSE)) {
954      if (!*r_path)          msg_box (NULL, _("Could not copy file."), _("WinPT Error"), MB_ERR);
955          return 0;          rc = WPTERR_FILE_READ;
956      p = make_filename (*r_path, "pubring", "gpg");      }
957      if (!p || get_file_size (p) > 0)  
958          return 0;  fail:
959        free_if_alloc (file);
960      opt = get_gnupg_cfgfile ();      free_if_alloc (path);
961      if (!opt)      return rc;
962          BUG (0);  }
963      name = get_gnupg_keyring_from_options (opt, 1);  
964      free_if_alloc (opt);  
965      free_if_alloc (p);  /* Backup the gpg.conf file. */
966      if (!name)  void
967          return 0;  gnupg_backup_options (void)
968      p = strrchr (name, '\\');  {
969      if (!p)      char *cfgfile = NULL;
970      {      char bak[512];
971          free_if_alloc (name);  
972          return 0;            cfgfile = get_gnupg_cfgfile ();
973      }      if (!cfgfile)
974      free_if_alloc (*r_path);          return;
975      *r_path = new char [strlen (name)+1];      _snprintf (bak, DIM (bak)-1, "%s.bak", cfgfile);
976      memset (*r_path, 0, strlen (name));      CopyFile (cfgfile, bak, FALSE);
977      strncpy (*r_path, name, (p-name));      free_if_alloc (cfgfile);
978      free_if_alloc (name);  }
979      return 1;  
980  }  
981    static int
982    backup_one_file (const char *srcpath, const char *srcn,
983  void                   const char *dstpath, const char *dstn)
984  gnupg_backup_keyrings (void)  {
985  {      char *src, *dst;
986      char * srcpath = NULL, * dstpath = NULL;      BOOL rc;
987      int rc, bakmode=0;  
988        src = make_filename (srcpath, srcn, "gpg");
989      if (!reg_prefs.auto_backup)      if (!src)
990          return;          BUG (NULL);
991      bakmode = reg_prefs.backup.mode;      dst = make_filename (dstpath, dstn, "gpg");
992      srcpath =  get_gnupg_path ();      if (!dst)
993      check_keyring (&srcpath);          BUG (NULL);
994      if (bakmode == 1)      rc = CopyFile (src, dst, FALSE);
995      {      free_if_alloc (src);
996          dstpath = get_gnupg_path ();      free_if_alloc (dst);
997          check_keyring (&dstpath);      if (!rc) {
998      }          log_box (_("Backup"), MB_ERR, _("Backup keyring \"%s\" failed"), srcn);
999      else if (bakmode == 2)          return WPTERR_GENERAL;
1000      {      }
1001          char * tmpfile;      return 0;
1002          FILE * fp;  }
1003    
1004          dstpath = m_strdup (reg_prefs.backup.path);  
1005          if (!dstpath)  /* Figure out first public keyring which is not empty.
1006              BUG (0);     Return value: 1 on success. */
1007          tmpfile = make_filename (reg_prefs.backup.path, "test", "tmp");  static int
1008          fp = fopen (tmpfile, "wb");  check_keyring (char **r_path)
1009          if (!fp)  {
1010              rc = log_box (_("Backup"), MB_WARN|MB_RETRYCANCEL, _("The backup drive '%s' does not seems to accessable.\n"      char *p;
1011                                                                   "Please insert/check the drive to continue."), dstpath);      char *opt;
1012          else      char *name;
1013          {  
1014              rc = 0;      if (!*r_path)
1015              fclose (fp);          return 0;
1016              unlink (tmpfile);      p = make_filename (*r_path, "pubring", "gpg");
1017          }      if (!p || get_file_size (p) <= 0)
1018          free_if_alloc (tmpfile);          return 0;
1019          if (!fp || rc == IDCANCEL)  
1020              return;      opt = get_gnupg_cfgfile ();
1021      }      if (!opt)
1022      else          BUG (0);
1023      {      name = get_gnupg_keyring_from_options (opt, 1);
1024          log_box (_("Backup"), MB_ERR, _("Invalid backup mode %d"), bakmode);      free_if_alloc (opt);
1025          return;      free_if_alloc (p);
1026      }      if (!name)
1027      rc = backup_one_file (srcpath, "pubring", dstpath, "pubring-bak");          return 0;
1028      if (!rc)      p = strrchr (name, '\\');
1029          rc = backup_one_file (srcpath, "secring", dstpath, "secring-bak");      if (!p) {
1030      free_if_alloc (srcpath);          free_if_alloc (name);
1031      free_if_alloc (dstpath);          return 0;      
1032  } /* gnupg_backup_keyrings */      }
1033        free_if_alloc (*r_path);
1034        *r_path = new char [strlen (name)+1];
1035  void      memset (*r_path, 0, strlen (name));
1036  gnupg_display_error (void)      strncpy (*r_path, name, (p-name));
1037  {            free_if_alloc (name);
1038      char tmpath[512], * errstr;      return 1;
1039      size_t size = 0;  }
1040      FILE * fp;  
1041    
1042      GetTempPath (sizeof tmpath - 32, (tmpath));  /* Return a temp name based on the day of the week. */
1043      strcat (tmpath, "gpg_stderr");  static char*
1044      size = get_file_size (tmpath);  get_backup_name (const char *templ)
1045      if (file_exist_check (tmpath) || size <= 0)  {
1046          return;      struct tm *tm;
1047      fp = fopen( tmpath, "rb" );      char *p;
1048      if (!fp) {      time_t t;
1049          msg_box( NULL, _("No GPG error description available."), _("GPG Error"), MB_INFO );  
1050          return;      t = time (NULL);
1051      }      tm = localtime (&t);
1052      errstr = new char[size+1];      p = new char [strlen (templ) + 8 + 1];
1053      if (!errstr)      if (!p)
1054          BUG (0);          BUG (0);
1055      fread (errstr, 1, size, fp);      sprintf (p, "%s-%d", templ, tm->tm_wday % 3);
1056      errstr[size] = '\0';      return p;
1057      fclose (fp);  }
1058      msg_box (NULL, errstr, _("GPG Error"), MB_INFO);  
1059      free_if_alloc (errstr);  
1060  } /* gnupg_display_error */  /* Make backups of all keyrings. The public key ring is
1061       rotated like this pubring-%d.gpg. */
1062    void
1063  int  gnupg_backup_keyrings (int auto_backup, int backup_mode)
1064  gnupg_access_keyring (int _pub)  {
1065  {      char *srcpath = NULL, *dstpath = NULL;
1066      int rc = 0;      char *name=NULL;
1067      char * name = get_gnupg_keyring (_pub, 1);      int rc;
1068      if (file_exist_check (name))  
1069          rc = -1;      if (!auto_backup)
1070      free_if_alloc (name);          return;
1071      return rc;      srcpath = get_gnupg_path ();
1072  }      check_keyring (&srcpath);
1073        if (backup_mode == 1) {
1074            dstpath = multi_gnupg_path (1);
1075            check_keyring (&dstpath);
1076        }
1077        else if (backup_mode == 2) {
1078            char *tmpfile;
1079            FILE *fp;
1080    
1081            dstpath = m_strdup (reg_prefs.backup.path);
1082            if (!dstpath)
1083                BUG (0);
1084            tmpfile = make_filename (reg_prefs.backup.path, "test", "tmp");
1085            fp = fopen (tmpfile, "wb");
1086            if (!fp)
1087                rc = log_box (_("Backup"), MB_WARN|MB_RETRYCANCEL,
1088                              _("The backup drive '%s' does not seems to accessable.\n"
1089                                "Please insert/check the drive to continue."), dstpath);
1090            else {
1091                rc = 0;
1092                fclose (fp);
1093                remove (tmpfile);
1094            }
1095            free_if_alloc (tmpfile);
1096            if (!fp || rc == IDCANCEL)
1097                return;
1098        }
1099        else {
1100            log_box (_("Backup"), MB_ERR, _("Invalid backup mode %d"), backup_mode);
1101            return;
1102        }
1103        name = get_backup_name ("pubring-bak");
1104        rc = backup_one_file (srcpath, "pubring", dstpath, name);
1105        if (!rc)
1106            rc = backup_one_file (srcpath, "secring", dstpath, "secring-bak");
1107        free_if_alloc (name);
1108        free_if_alloc (srcpath);
1109        free_if_alloc (dstpath);
1110    }
1111    
1112    
1113    /* Display GPG error from file if possible. */
1114    void
1115    gnupg_display_error (void)
1116    {      
1117        char tmpath[512], *errstr;
1118        size_t size = 0;
1119        FILE *fp;
1120    
1121        get_temp_name (tmpath, sizeof (tmpath), "gpg_stderr");
1122        size = get_file_size (tmpath);
1123        if (file_exist_check (tmpath) || size <= 0)
1124            return;
1125        fp = fopen( tmpath, "rb" );
1126        if (!fp) {
1127            msg_box (NULL, _("No GPG error description available."),
1128                     _("GPG Error"), MB_INFO);
1129            return;
1130        }
1131        errstr = new char[size+1];
1132        if (!errstr)
1133            BUG (0);
1134        fread (errstr, 1, size, fp);
1135        errstr[size] = '\0';
1136        fclose (fp);
1137        msg_box (NULL, errstr, _("GPG Error"), MB_INFO);
1138        free_if_alloc (errstr);
1139    }
1140    
1141    
1142    
1143    /* check that the requested GPG keyring exist and.
1144       Return value: 0 for success. */
1145    int
1146    gnupg_access_keyring (int _pub)
1147    {
1148        int rc = 0;
1149        char *name = get_gnupg_keyring (_pub, 1);
1150        if (!name || file_exist_check (name))
1151            rc = -1;
1152        free_if_alloc (name);
1153        return rc;
1154    }

Legend:
Removed from v.2  
changed lines
  Added in v.214

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26