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

Diff of /trunk/Src/wptGPG.cpp

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26