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

Legend:
Removed from v.24  
changed lines
  Added in v.138

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26