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

Legend:
Removed from v.2  
changed lines
  Added in v.200

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26