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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26