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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26