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

Diff of /trunk/Src/wptGPG.cpp

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26