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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26