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

Legend:
Removed from v.24  
changed lines
  Added in v.271

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26