/[winpt]/trunk/Src/wptGPG.cpp
ViewVC logotype

Diff of /trunk/Src/wptGPG.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26