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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26