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

Diff of /trunk/Src/wptGPG.cpp

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26