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

Legend:
Removed from v.12  
changed lines
  Added in v.270

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26