/[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 175 by twoaday, Tue Feb 7 08:58:04 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;  int
558      unsigned j;  set_gnupg_default_key (const char * key)
559            {
560      for ( j = 0; j<strlen( buf ) && j < sizeof(line); j++ ) {      gpg_optfile_t opt;
561          line[nbytes++] = buf[j];      gpg_option_t e;
562          if ( buf[j] == '\n' || j == ( strlen( buf ) - 1 ) ) {      char *optfile = NULL;
563              line[nbytes] = '\0';      int rc = 0;
564              if( !check_line( line ) ) {  
565                  msg_box( NULL, line, "options", MB_OK );      optfile = get_gnupg_cfgfile ();
566                  return 1;            if (!optfile)
567              }          return -1;
568              nbytes = 0;      rc = parse_gpg_options (optfile, &opt);
569          }            if( rc ) {
570      }          free_if_alloc (optfile);
571            return -1;
572      return 0;      }
573  } /* check_gnupg_options */      e = find_option (opt, "default-key");
574        if (e) {
575            free_if_alloc (e->val);
576  static int          e->val = m_strdup (key);
577  get_last_gnupg_access (gpg_watcher_s * ctx)          e->used = 1;
578  {      }
579      HANDLE fd;      else
580      char *path = NULL, *file = NULL;          add_entry (opt, ENTRY_MULTI, "default-key", key);
581        rc = commit_gpg_options (optfile, opt);
582      path = get_gnupg_path ();  
583      file =  make_filename (path, ctx->object, NULL);      free_if_alloc (optfile);
584      fd = CreateFile (file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL);      release_gpg_options (opt);
585      if( fd == INVALID_HANDLE_VALUE ) {  
586          free_if_alloc (path);      return rc;
587          free_if_alloc (file);  } /* set_gnupg_default_key */
588          return WPTERR_FILE_OPEN;  
589      }  
590      GetFileTime (fd, NULL, NULL, &ctx->access);  /*
591      CloseHandle (fd);   * Set the contents of the options file.
592      free_if_alloc (path);         */
593      free_if_alloc (file);  int
594      return 0;  set_gnupg_options( const char *buf, size_t buflen )
595  } /* get_last_gnupg_access */  {
596        FILE *fp;  
597        char *optfile = NULL;
598  static void  
599  check_last_gnupg_access( gpg_watcher_s *ctx )      optfile = get_gnupg_cfgfile( );
600  {                    if( optfile == NULL )
601      ctx->modified = 0;          return WPTERR_FILE_CREAT;
602    
603      if( ctx->last_access.dwHighDateTime != ctx->access.dwHighDateTime &&      fp = fopen( optfile, "wb" );
604          ctx->last_access.dwLowDateTime != ctx->access.dwLowDateTime )        if( fp == NULL ) {
605          ctx->modified = 1;          free_if_alloc( optfile );
606            return WPTERR_FILE_CREAT;
607      ctx->last_access.dwLowDateTime = ctx->access.dwLowDateTime;      }
608      ctx->last_access.dwHighDateTime = ctx->access.dwHighDateTime;      fwrite( buf, 1, buflen, fp );
609  } /* check_last_gnupg_access */      fclose( fp );
610        free_if_alloc( optfile );
611        return 0;
612  void  } /* set_gnupg_options */
613  init_gnupg_table (void)  
614  {        /*
615      int j;   * Check if the line contains a valid GPG argument.
616     */
617      for (j = 0; j < gpg_table_count; j++) {  static int
618          gpg_table[j].object = m_strdup (gpg_objs[j]);  check_line( const char *buf )
619          memset (&gpg_table[j].access, 0, sizeof (FILETIME));  {
620          memset (&gpg_table[j].last_access, 0, sizeof (FILETIME));      int j, len;
621          gpg_table[j].modified = 0;      int rc = 0;
622      }  
623  } /* init_gnupg_table */      if( *buf == '#' || *buf == '\r' || *buf == '\n' )
624            return 1;
625        rc = 0;
626  void      for ( j = 0; valid_gpg_args[j]; j++ ) {
627  free_gnupg_table (void)          len = strlen( valid_gpg_args[j] );
628  {          if( !strncmp( valid_gpg_args[j], buf, len ) )
629      int j;              rc = 1;    
630        }
631      for (j=0; j < gpg_table_count; j++)  
632          free_if_alloc (gpg_table[j].object);      return rc;
633  } /* free_gnupg_table */  } /* check_line */
634    
635    
636  int  int
637  keyring_check_last_access (void)  check_gnupg_options( const char *buf )
638  {        {
639      int rc, j;      char line[1024];
640        int nbytes = 0;
641      rc = 0;      unsigned j;
642      for (j = 0; j < gpg_table_count; j++) {          
643          get_last_gnupg_access( &gpg_table[j] );      for ( j = 0; j<strlen( buf ) && j < sizeof(line); j++ ) {
644          check_last_gnupg_access( &gpg_table[j] );          line[nbytes++] = buf[j];
645          if ( gpg_table[j].modified )          if ( buf[j] == '\n' || j == ( strlen( buf ) - 1 ) ) {
646              rc++;                    line[nbytes] = '\0';
647      }              if( !check_line( line ) ) {
648                    msg_box( NULL, line, "options", MB_OK );
649      return rc;                  return 1;      
650  } /* keyring_check_last_access */              }
651                nbytes = 0;
652            }      
653  const char *      }
654  gnupg_check_file_ext (const char * fname)  
655  {                    return 0;
656      char file_ext[5];  } /* check_gnupg_options */
657    
658      if (!strchr( fname, '.' ))  
659          return "UNKNOWN";  /* Store the last access of the file inside the watcher @ctx. */
660    static int
661      strncpy (file_ext, fname + strlen (fname) - 4, 4);  get_last_gnupg_access (gpg_watcher_s *ctx)
662      file_ext[4] = '\0';  {
663      if (!stricmp (file_ext, ".asc"))      HANDLE fd;
664          return "ARMORED";      char *path;
665      else if (!stricmp (file_ext, ".sig"))      char *file;
666          return "SIGNED";  
667      else if  (!stricmp (file_ext, ".gpg")      path = get_gnupg_path ();
668          || !stricmp (file_ext, ".pgp"))      file =  make_filename (path, ctx->object, NULL);
669          return "ENCRYPTED";      fd = CreateFile (file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL);
670      else      if (fd == INVALID_HANDLE_VALUE) {
671          return "UNKNOWN";          free_if_alloc (path);
672                    free_if_alloc (file);
673      return "UNKNOWN";          return WPTERR_FILE_OPEN;
674  } /* gnupg_check_file_ext */      }
675        GetFileTime (fd, NULL, NULL, &ctx->access);
676        CloseHandle (fd);
677  char *      free_if_alloc (path);
678  get_gnupg_keyring_from_options (const char * fname, int pub)      free_if_alloc (file);
679  {      return 0;
680      gpg_optfile_t opt;  }
681      gpg_option_t e;  
682      char * kring = NULL;  
683      int rc = 0;  /* Check if the file inside watcher @ctx was modified. */
684    static void
685      rc = parse_gpg_options (fname, &opt);  check_last_gnupg_access (gpg_watcher_s *ctx)
686      if (rc)  {              
687          return NULL;      ctx->modified = 0;
688      if (pub)  
689          e = find_option (opt, "keyring");      if (ctx->last_access.dwHighDateTime != ctx->access.dwHighDateTime &&
690      else          ctx->last_access.dwLowDateTime != ctx->access.dwLowDateTime)
691          e = find_option (opt, "secret-keyring");          ctx->modified = 1;
692      if (e)      
693          kring = m_strdup (e->val);      /* XXX: find a better way. without it, winpt --keymanager loads
694      release_gpg_options (opt);              the key cache twice. */
695        if (ctx->last_access.dwLowDateTime == 0)
696      return kring;          ctx->modified = 0;
697  } /* get_gnupg_keyring_from_options */  
698        ctx->last_access.dwLowDateTime = ctx->access.dwLowDateTime;
699        ctx->last_access.dwHighDateTime = ctx->access.dwHighDateTime;
700    }
701  /* XXX: does not work with write-protected floppies */  
702  static int  
703  my_access (const char * fname)  /* Init GPG watcher table for all monitored files. */
704  {  void
705      HANDLE hd;  init_gnupg_table (void)
706      hd = CreateFile (fname, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);  {      
707      if (hd == INVALID_HANDLE_VALUE)      char *p;
708          return -1;      int j;
709      CloseHandle (hd);  
710      return 0;      for (j = 0; j < gpg_table_count; j++) {
711  } /* my_access */          p = gpg_table[j].object = m_strdup (gpg_objs[j]);
712            if (!p)
713                BUG (NULL);
714  int          memset (&gpg_table[j].access, 0, sizeof (FILETIME));
715  gpg_check_permissions (int showmsg)          memset (&gpg_table[j].last_access, 0, sizeof (FILETIME));
716  {          gpg_table[j].modified = 0;
717      char * p, * name = NULL;      }
718      int failed = 0, ans=0, attrs=0;  }
719    
720      p = get_gnupg_path ();  
721      check_keyring (&p);  void
722      if (p) {  free_gnupg_table (void)
723          name = make_filename (p, "pubring", "gpg");  {
724          free_if_alloc (p);      int j;
725          if ((attrs=GetFileAttributes (name)) & FILE_ATTRIBUTE_READONLY) {  
726              ans = msg_box (NULL,      for (j=0; j < gpg_table_count; j++)
727                             _("The selected keyring has the read-only file\n"          free_if_alloc (gpg_table[j].object);
728                               "attribute. In this state you do not have write\n"  }
729                               "access. Do you want to remove the attribute?"),  
730                       _("GPG Information"), MB_YESNO);  
731              if (ans == IDYES) {  /* Return the amount of files modified since the last call. */
732                  attrs &= ~FILE_ATTRIBUTE_READONLY;  int
733                  if (!SetFileAttributes (name, attrs)) {  keyring_check_last_access (void)
734                      msg_box (NULL, _("Could not reset read-only state."),  {      
735                               _("GPG Error"), MB_ERR);      int rc, j;
736                      failed = 1;  
737                  }      rc = 0;
738              }      for (j = 0; j < gpg_table_count; j++) {
739              else if (ans == IDNO) {          get_last_gnupg_access (&gpg_table[j]);
740                  /*          check_last_gnupg_access (&gpg_table[j]);
741                  msg_box (NULL, _("All commands with write access to the keyring\n"          if (gpg_table[j].modified)
742                                   "will be disabled."), _("GPG Information"), MB_INFO);              rc++;      
743                  */      }
744                  failed = 1;  
745              }      return rc;
746          }  }
747          if (my_access (name)) {  
748              if (showmsg)  
749                  msg_box (NULL,  const char*
750                  _("You do not have file access to modify the contents of\n"  gnupg_check_file_ext (const char *fname, int *r_type)
751                    "one or both of the selected keyrings.\n"  {              
752                    "\n"      char file_ext[5];
753                    "The keyrings are in a read-only state which is propably\n"  
754                    "caused by another program which already opened the files.\n"),      if (r_type)
755                     _("GPG Warning"), MB_WARN);          *r_type = PGP_NONE;
756              failed = 2;      if (!strchr (fname, '.' ))
757          }          return "UNKNOWN";
758      }  
759      free_if_alloc (name);      strncpy (file_ext, fname + strlen (fname) - 4, 4);
760      return failed;      file_ext[4] = '\0';
761  } /* gpg_check_permissions */      if (!stricmp (file_ext, ".asc"))
762            return "ARMORED";
763        else if (!stricmp (file_ext, ".sig")) {
764  static int          if (r_type)
765  check_homedir (void)              *r_type = PGP_SIG;
766  {                return "SIGNED";
767      char * homedir = NULL;      }
768      int yes = 0;      else if  (!stricmp (file_ext, ".gpg") || !stricmp (file_ext, ".pgp")) {
769            if (r_type)
770      homedir = get_reg_entry_gpg ("HomeDir");              *r_type = PGP_MESSAGE;
771      if (!homedir)          return "ENCRYPTED";
772          homedir = multi_gnupg_path ();      }
773      if (!homedir)      return "UNKNOWN";
774          homedir = m_strdup ("c:\\gnupg");  }
775      if (homedir) {  
776          if (GetFileAttributes (homedir) == 0xFFFFFFFF) {  
777              yes = log_box (_("Preferences"), MB_YESNO,  char*
778                             _("%s does not exit.\n"  get_gnupg_keyring_from_options (const char * fname, int pub)
779                               "Do you want to create this directory?"), homedir);  {
780              if (yes == IDYES) {      gpg_optfile_t opt;
781                  if (CreateDirectory (homedir, NULL) == FALSE) {      gpg_option_t e;
782                      free_if_alloc (homedir);      char * kring = NULL;
783                      return WPTERR_DIR_CREAT;      int rc = 0;
784                  }  
785              }      rc = parse_gpg_options (fname, &opt);
786              return WPTERR_DIR_OPEN;      if (rc)
787          }          return NULL;
788          free_if_alloc (homedir);      if (pub)
789      }          e = find_option (opt, "keyring");
790      return 0;      else
791  } /* check_homedir */          e = find_option (opt, "secret-keyring");
792        if (e)
793            kring = m_strdup (e->val);
794  int      release_gpg_options (opt);
795  gnupg_check_homedir (void)  
796  {            return kring;
797      char *homedir = NULL, *prog = NULL;  }
798      int rc = 0, ec = 0;  
799        
800      rc = check_homedir ();  
801      if (rc)  /* XXX: does not work with write-protected floppies */
802          return rc;  static int
803      if ((homedir = get_reg_entry_gpg ("HomeDir")) &&  my_access (const char *fname)
804          !(prog = get_reg_entry_gpg ("gpgProgram" ))) {  {
805          prog = make_filename (homedir, "gpg", "exe");      HANDLE hd;
806          if (file_exist_check (prog) == 0) {      hd = CreateFile (fname, GENERIC_WRITE, FILE_SHARE_WRITE,
807              rc = set_reg_entry_gpg ("gpgProgram", prog);                       NULL, OPEN_EXISTING, 0, NULL);
808              if (rc)      if (hd == INVALID_HANDLE_VALUE)
809                  goto fail;          return -1;
810          }      CloseHandle (hd);
811          free_if_alloc (homedir);      return 0;
812          free_if_alloc (prog);  }
813          return rc;  
814      }  
815      if ((prog = get_reg_entry_gpg ("gpgProgram"))  /* Check the file permissions of the public keyring.
816          && file_exist_check (prog)) {     If @showmsg is 1 output a message in case of errors.
817          free_if_alloc (prog);     Return value: 1 if read-only attribute
818          homedir = get_reg_entry_gpg ("HomeDir");                   2 if file is opened by another process exclusively. */
819          if (!homedir) {  int
820              rc = WPTERR_GENERAL;  gpg_check_permissions (int showmsg)
821              goto fail;  {
822          }      char *p = NULL;
823          prog = make_filename (homedir, "gpg", "exe");      char *name = NULL;
824          if (file_exist_check (prog) == 0) {      int failed = 0, ans=0, attrs=0;
825              rc = set_reg_entry_gpg ("gpgProgram", prog);  
826              if (rc)      p = get_gnupg_path ();
827                  goto fail;      if (check_keyring (&p) && p) {
828              free_if_alloc (prog);          name = make_filename (p, "pubring", "gpg");
829              return rc;          if ((attrs=GetFileAttributes (name)) & FILE_ATTRIBUTE_READONLY) {
830          }              ans = msg_box (NULL,
831      }                             _("The selected keyring has the read-only file\n"
832                                     "attribute. In this state you do not have write\n"
833      /* Change the return code if homedir doesn't exist or if the program                               "access. Do you want to remove the attribute?"),
834         doesn't exist. Note that exist_checks return 0 to suggest existance. */                       _("GPG Information"), MB_YESNO);
835      if ((!homedir || dir_exist_check (homedir)))              if (ans == IDYES) {
836          rc = WPTERR_GENERAL;                  attrs &= ~FILE_ATTRIBUTE_READONLY;
837                        if (!SetFileAttributes (name, attrs)) {
838  fail:                      msg_box (NULL, _("Could not reset read-only state."),
839      free_if_alloc (homedir);                               _("GPG Error"), MB_ERR);
840      free_if_alloc (prog);                      failed = 1;
841      return rc;                  }
842  } /* gnupg_check_homedir */              }
843                else if (ans == IDNO) {
844                    /* All commands with write access will be disabled. */
845  int                  failed = 1;
846  gnupg_copy_keyrings (void)              }
847  {          }
848      const char * pring, * sring;          if (my_access (name)) {
849      char * file = NULL, * path = NULL;              if (showmsg)
850      int id = 0, rc = 0;                  msg_box (NULL,
851      HWND hwnd;                  _("You do not have file access to modify the contents of\n"
852                          "one or both of the selected keyrings.\n"
853      path = get_gnupg_path ();                    "\n"
854      if (!path)                    "The keyrings are in a read-only state which is propably\n"
855          return WPTERR_GENERAL;                    "caused by another program which already opened the files.\n"),
856      hwnd = GetDesktopWindow ();                     _("GPG Warning"), MB_WARN);
857                failed = 2;
858      pring = get_filename_dlg (hwnd, FILE_OPEN, _("Please choose your public keyring"),          }
859                                _("GPG Keyrings (*.gpg)\0*.gpg\0\0"),NULL);      }
860      if (!pring) {      free_if_alloc (p);
861          msg_box (hwnd, _("No keyring was chosen. Exit."), _("WinPT Error"), MB_ERR);      free_if_alloc (name);
862          free_if_alloc (path);      return failed;
863          return WPTERR_GENERAL;  }
864      }  
865      file = make_filename (path, "pubring", "gpg");  
866      if (file_exist_check (file) == 0) {  /* Check the GPG home dir. First try to read the 'HomeDir' registry entry,
867          id = msg_box (hwnd, _("Overwrite old public keyring?"), "WinPT", MB_INFO|MB_YESNO);     then check for $APPDATA\gnupg. Create the dir if it does not exists. */
868          if (id == IDNO)  int
869              goto fail;  gnupg_check_homedir (void)
870      }  {      
871      if (!CopyFile (pring, file, FALSE)) {      char *homedir = NULL;
872          msg_box (hwnd, _("Could not copy file."), _("WinPT Error"), MB_ERR);      int val = 0;
873          rc = WPTERR_FILE_READ;      int rc = 0;
874          goto fail;  
875      }      homedir = get_reg_entry_gpg (GPG_REG_HOME);
876      free_if_alloc (file);      if (!homedir)
877            homedir = multi_gnupg_path (0);
878      sring = get_filename_dlg (hwnd, FILE_OPEN, _("Please choose your secret keyring"),      if (homedir) {
879                                _("GPG Keyrings (*.gpg)\0*.gpg\0\0"), NULL);          if (GetFileAttributes (homedir) == 0xFFFFFFFF) {
880      if (!sring) {              val = log_box (_("Preferences"), MB_YESNO,
881          msg_box( NULL, _("No keyring was chosen. Exit."), _("WinPT Error"), MB_ERR );                             _("%s does not exit.\n"
882          return WPTERR_GENERAL;                               "Do you want to create this directory?"), homedir);
883      }              if (val == IDYES) {
884      file = make_filename (path, "secring", "gpg");                  if (!CreateDirectory (homedir, NULL))
885      if (file_exist_check (file) == 0) {                      rc = WPTERR_DIR_CREAT;
886          id = msg_box (hwnd, _("Overwrite old secret keyring?"), "WinPT", MB_INFO|MB_YESNO);              }
887          if( id == IDNO )              else
888              goto fail;                  rc = WPTERR_DIR_OPEN;
889      }          }
890      if (!CopyFile (sring, file, FALSE)) {          free_if_alloc (homedir);
891          msg_box( NULL, _("Could not copy file."), _("WinPT Error"), MB_ERR);      }
892          rc = WPTERR_FILE_READ;      return rc;
893      }  }
894    
895  fail:  
896      free_if_alloc (file);  int
897      free_if_alloc (path);  gnupg_copy_keyrings (void)
898      return rc;  {
899  } /* gnupg_import_keyrings */      const char * pring, * sring;
900        char * file = NULL, * path = NULL;
901        int id = 0, rc = 0;
902  void      HWND hwnd;
903  gnupg_backup_options (int keep)      
904  {      path = get_gnupg_path ();
905      char *optfile = NULL;      if (!path)
906      char bak[1024];          return WPTERR_GENERAL;
907        hwnd = GetDesktopWindow ();
908      optfile = get_gnupg_cfgfile ();  
909      if (optfile == NULL)      pring = get_fileopen_dlg (hwnd, _("Please choose your public keyring"),
910          return;                                "GPG Keyrings (*.gpg)\0*.gpg\0\0",NULL);
911      if (keep)      if (!pring) {
912          _snprintf (bak, DIM (bak)-1, "%s.old", optfile);          msg_box (hwnd, _("No keyring was chosen. Exit."), _("WinPT Error"), MB_ERR);
913      else          free_if_alloc (path);
914          _snprintf (bak, DIM (bak)-1, "%s.O", optfile);          return WPTERR_GENERAL;
915      CopyFile (optfile, bak, keep);      }
916      free_if_alloc (optfile);      file = make_filename (path, "pubring", "gpg");
917  } /* gnupg_backup_options */      if (file_exist_check (file) == 0) {
918            id = msg_box (hwnd, _("Overwrite old public keyring?"), "WinPT", MB_INFO|MB_YESNO);
919            if (id == IDNO)
920                goto fail;
921  static int      }
922  backup_one_file (const char * srcpath, const char * srcn,      if (!CopyFile (pring, file, FALSE)) {
923                   const char * dstpath, const char * dstn)          msg_box (hwnd, _("Could not copy file."), _("WinPT Error"), MB_ERR);
924  {          rc = WPTERR_FILE_READ;
925      char * src, * dst;          goto fail;
926      BOOL rc;      }
927        free_if_alloc (file);
928      src = make_filename (srcpath, srcn, "gpg");  
929      if (!src)      sring = get_fileopen_dlg (hwnd, _("Please choose your secret keyring"),
930          BUG (NULL);                                "GPG Keyrings (*.gpg)\0*.gpg\0\0", NULL);
931      dst = make_filename (dstpath, dstn, "gpg");      if (!sring) {
932      if (!dst)          msg_box( NULL, _("No keyring was chosen. Exit."), _("WinPT Error"), MB_ERR );
933          BUG (NULL);          return WPTERR_GENERAL;
934      rc = CopyFile (src, dst, FALSE);      }
935      free_if_alloc (src);      file = make_filename (path, "secring", "gpg");
936      free_if_alloc (dst);      if (file_exist_check (file) == 0) {
937      if (!rc)          id = msg_box (hwnd, _("Overwrite old secret keyring?"), "WinPT", MB_INFO|MB_YESNO);
938      {          if( id == IDNO )
939          log_box (_("Backup"), MB_ERR, _("Backup keyring \"%s\" failed"), srcn);              goto fail;
940          return WPTERR_GENERAL;      }
941      }      if (!CopyFile (sring, file, FALSE)) {
942      return 0;          msg_box( NULL, _("Could not copy file."), _("WinPT Error"), MB_ERR);
943  } /* backup_one_file */          rc = WPTERR_FILE_READ;
944        }
945    
946  static int  fail:
947  check_keyring (char ** r_path)      free_if_alloc (file);
948  {      free_if_alloc (path);
949      char * p;      return rc;
950      char * opt, * name;  } /* gnupg_import_keyrings */
951    
952      if (!*r_path)  
953          return 0;  /* Backup the gpg.conf file. */
954      p = make_filename (*r_path, "pubring", "gpg");  void
955      if (!p || get_file_size (p) > 0)  gnupg_backup_options (void)
956          return 0;  {
957        char *cfgfile = NULL;
958      opt = get_gnupg_cfgfile ();      char bak[512];
959      if (!opt)  
960          BUG (0);      cfgfile = get_gnupg_cfgfile ();
961      name = get_gnupg_keyring_from_options (opt, 1);      if (!cfgfile)
962      free_if_alloc (opt);          return;
963      free_if_alloc (p);      _snprintf (bak, DIM (bak)-1, "%s.bak", cfgfile);
964      if (!name)      CopyFile (cfgfile, bak, FALSE);
965          return 0;      free_if_alloc (cfgfile);
966      p = strrchr (name, '\\');  }
967      if (!p)  
968      {  
969          free_if_alloc (name);  static int
970          return 0;        backup_one_file (const char *srcpath, const char *srcn,
971      }                   const char *dstpath, const char *dstn)
972      free_if_alloc (*r_path);  {
973      *r_path = new char [strlen (name)+1];      char * src, * dst;
974      memset (*r_path, 0, strlen (name));      BOOL rc;
975      strncpy (*r_path, name, (p-name));  
976      free_if_alloc (name);      src = make_filename (srcpath, srcn, "gpg");
977      return 1;      if (!src)
978  }          BUG (NULL);
979        dst = make_filename (dstpath, dstn, "gpg");
980        if (!dst)
981  static char*          BUG (NULL);
982  get_backup_name (const char *templ)      rc = CopyFile (src, dst, FALSE);
983  {      free_if_alloc (src);
984      struct tm *tm;      free_if_alloc (dst);
985      char *p;      if (!rc)
986        {
987      time_t t = time (NULL);          log_box (_("Backup"), MB_ERR, _("Backup keyring \"%s\" failed"), srcn);
988      tm = localtime (&t);          return WPTERR_GENERAL;
989      p = new char [strlen (templ) + 8 + 1];      }
990      if (!p)      return 0;
991          BUG (0);  } /* backup_one_file */
992      sprintf (p, "%s-%d", templ, tm->tm_wday % 3);  
993      return p;  
994  }  /* Figure out first public keyring which is not empty.
995       Return value: 1 on success. */
996    static int
997  void  check_keyring (char **r_path)
998  gnupg_backup_keyrings (void)  {
999  {      char *p;
1000      char *srcpath = NULL, *dstpath = NULL;      char *opt;
1001      char *name=NULL;      char *name;
1002      int rc, bakmode=0;  
1003        if (!*r_path)
1004      if (!reg_prefs.auto_backup)          return 0;
1005          return;      p = make_filename (*r_path, "pubring", "gpg");
1006      bakmode = reg_prefs.backup.mode;      if (!p || get_file_size (p) <= 0)
1007      srcpath =  get_gnupg_path ();          return 0;
1008      check_keyring (&srcpath);  
1009      if (bakmode == 1) {      opt = get_gnupg_cfgfile ();
1010          dstpath = get_gnupg_path ();      if (!opt)
1011          check_keyring (&dstpath);          BUG (0);
1012      }      name = get_gnupg_keyring_from_options (opt, 1);
1013      else if (bakmode == 2) {      free_if_alloc (opt);
1014          char * tmpfile;      free_if_alloc (p);
1015          FILE * fp;      if (!name)
1016            return 0;
1017          dstpath = m_strdup (reg_prefs.backup.path);      p = strrchr (name, '\\');
1018          if (!dstpath)      if (!p) {
1019              BUG (0);          free_if_alloc (name);
1020          tmpfile = make_filename (reg_prefs.backup.path, "test", "tmp");          return 0;      
1021          fp = fopen (tmpfile, "wb");      }
1022          if (!fp)      free_if_alloc (*r_path);
1023              rc = log_box (_("Backup"), MB_WARN|MB_RETRYCANCEL, _("The backup drive '%s' does not seems to accessable.\n"      *r_path = new char [strlen (name)+1];
1024                                                                   "Please insert/check the drive to continue."), dstpath);      memset (*r_path, 0, strlen (name));
1025          else {      strncpy (*r_path, name, (p-name));
1026              rc = 0;      free_if_alloc (name);
1027              fclose (fp);      return 1;
1028              unlink (tmpfile);  }
1029          }  
1030          free_if_alloc (tmpfile);  
1031          if (!fp || rc == IDCANCEL)  /* Return a temp name based on the day of the week. */
1032              return;  static char*
1033      }  get_backup_name (const char *templ)
1034      else {  {
1035          log_box (_("Backup"), MB_ERR, _("Invalid backup mode %d"), bakmode);      struct tm *tm;
1036          return;      char *p;
1037      }      time_t t;
1038      name = get_backup_name ("pubring-bak");  
1039      rc = backup_one_file (srcpath, "pubring", dstpath, name);      t = time (NULL);
1040      if (!rc)      tm = localtime (&t);
1041          rc = backup_one_file (srcpath, "secring", dstpath, "secring-bak");      p = new char [strlen (templ) + 8 + 1];
1042      free_if_alloc (name);      if (!p)
1043      free_if_alloc (srcpath);          BUG (0);
1044      free_if_alloc (dstpath);      sprintf (p, "%s-%d", templ, tm->tm_wday % 3);
1045  } /* gnupg_backup_keyrings */      return p;
1046    }
1047    
1048  void  
1049  gnupg_display_error (void)  /* Make backups of all keyrings. The public key ring is
1050  {           rotated like this pubring-%d.gpg. */
1051      char tmpath[512], * errstr;  void
1052      size_t size = 0;  gnupg_backup_keyrings (void)
1053      FILE * fp;  {
1054        char *srcpath = NULL, *dstpath = NULL;
1055      GetTempPath (sizeof tmpath - 32, (tmpath));      char *name=NULL;
1056      strcat (tmpath, "gpg_stderr");      int rc, bakmode=0;
1057      size = get_file_size (tmpath);  
1058      if (file_exist_check (tmpath) || size <= 0)      if (!reg_prefs.auto_backup)
1059          return;          return;
1060      fp = fopen( tmpath, "rb" );      bakmode = reg_prefs.backup.mode;
1061      if (!fp) {      srcpath = get_gnupg_path ();
1062          msg_box( NULL, _("No GPG error description available."), _("GPG Error"), MB_INFO );      check_keyring (&srcpath);
1063          return;      if (bakmode == 1) {
1064      }          dstpath = multi_gnupg_path (1);
1065      errstr = new char[size+1];          check_keyring (&dstpath);
1066      if (!errstr)      }
1067          BUG (0);      else if (bakmode == 2) {
1068      fread (errstr, 1, size, fp);          char *tmpfile;
1069      errstr[size] = '\0';          FILE *fp;
1070      fclose (fp);  
1071      msg_box (NULL, errstr, _("GPG Error"), MB_INFO);          dstpath = m_strdup (reg_prefs.backup.path);
1072      free_if_alloc (errstr);          if (!dstpath)
1073  } /* gnupg_display_error */              BUG (0);
1074            tmpfile = make_filename (reg_prefs.backup.path, "test", "tmp");
1075            fp = fopen (tmpfile, "wb");
1076  int          if (!fp)
1077  gnupg_access_keyring (int _pub)              rc = log_box (_("Backup"), MB_WARN|MB_RETRYCANCEL,
1078  {                            _("The backup drive '%s' does not seems to accessable.\n"
1079      int rc = 0;                              "Please insert/check the drive to continue."), dstpath);
1080      char * name = get_gnupg_keyring (_pub, 1);          else {
1081      if (file_exist_check (name))              rc = 0;
1082          rc = -1;              fclose (fp);
1083      free_if_alloc (name);              remove (tmpfile);
1084      return rc;          }
1085  }          free_if_alloc (tmpfile);
1086            if (!fp || rc == IDCANCEL)
1087                return;
1088        }
1089        else {
1090            log_box (_("Backup"), MB_ERR, _("Invalid backup mode %d"), bakmode);
1091            return;
1092        }
1093        name = get_backup_name ("pubring-bak");
1094        rc = backup_one_file (srcpath, "pubring", dstpath, name);
1095        if (!rc)
1096            rc = backup_one_file (srcpath, "secring", dstpath, "secring-bak");
1097        free_if_alloc (name);
1098        free_if_alloc (srcpath);
1099        free_if_alloc (dstpath);
1100    }
1101    
1102    
1103    /* Display GPG error from file if possible. */
1104    void
1105    gnupg_display_error (void)
1106    {      
1107        char tmpath[512], *errstr;
1108        size_t size = 0;
1109        FILE *fp;
1110    
1111        get_temp_name (tmpath, sizeof (tmpath), "gpg_stderr");
1112        size = get_file_size (tmpath);
1113        if (file_exist_check (tmpath) || size <= 0)
1114            return;
1115        fp = fopen( tmpath, "rb" );
1116        if (!fp) {
1117            msg_box (NULL, _("No GPG error description available."),
1118                     _("GPG Error"), MB_INFO);
1119            return;
1120        }
1121        errstr = new char[size+1];
1122        if (!errstr)
1123            BUG (0);
1124        fread (errstr, 1, size, fp);
1125        errstr[size] = '\0';
1126        fclose (fp);
1127        msg_box (NULL, errstr, _("GPG Error"), MB_INFO);
1128        free_if_alloc (errstr);
1129    }
1130    
1131    
1132    
1133    /* check that the requested GPG keyring exist and.
1134       Return value: 0 for success. */
1135    int
1136    gnupg_access_keyring (int _pub)
1137    {
1138        int rc = 0;
1139        char *name = get_gnupg_keyring (_pub, 1);
1140        if (!name || file_exist_check (name))
1141            rc = -1;
1142        free_if_alloc (name);
1143        return rc;
1144    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26