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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26