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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26