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

Legend:
Removed from v.2  
changed lines
  Added in v.248

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26