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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26