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

Diff of /trunk/Src/wptGPG.cpp

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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26