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

Legend:
Removed from v.23  
changed lines
  Added in v.273

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26