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

Legend:
Removed from v.25  
changed lines
  Added in v.407

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26