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

Diff of /trunk/Src/wptGPG.cpp

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26