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

Legend:
Removed from v.32  
changed lines
  Added in v.304

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26