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

Legend:
Removed from v.22  
changed lines
  Added in v.179

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26