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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26