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

Diff of /trunk/Src/wptGPG.cpp

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26