92c1ca50af25ec4f7c3da154797bfd8fa037e371
[platform/upstream/gpg2.git] / g10 / trustdb.c
1 /* trustdb.c
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3  *               2008, 2012 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25
26 #ifndef DISABLE_REGEX
27 #include <sys/types.h>
28 #include <regex.h>
29 #endif /* !DISABLE_REGEX */
30
31 #include "gpg.h"
32 #include "../common/status.h"
33 #include "../common/iobuf.h"
34 #include "keydb.h"
35 #include "../common/util.h"
36 #include "options.h"
37 #include "packet.h"
38 #include "main.h"
39 #include "../common/mbox-util.h"
40 #include "../common/i18n.h"
41 #include "tdbio.h"
42 #include "trustdb.h"
43 #include "tofu.h"
44
45
46 typedef struct key_item **KeyHashTable; /* see new_key_hash_table() */
47
48 /*
49  * Structure to keep track of keys, this is used as an array wherre
50  * the item right after the last one has a keyblock set to NULL.
51  * Maybe we can drop this thing and replace it by key_item
52  */
53 struct key_array
54 {
55   KBNODE keyblock;
56 };
57
58
59 /* Control information for the trust DB.  */
60 static struct
61 {
62   int init;
63   int level;
64   char *dbname;
65   int no_trustdb;
66 } trustdb_args;
67
68 /* Some globals.  */
69 static struct key_item *user_utk_list; /* temp. used to store --trusted-keys */
70 static struct key_item *utk_list;      /* all ultimately trusted keys */
71
72 static int pending_check_trustdb;
73
74 static int validate_keys (ctrl_t ctrl, int interactive);
75
76 \f
77 /**********************************************
78  ************* some helpers *******************
79  **********************************************/
80
81 static struct key_item *
82 new_key_item (void)
83 {
84   struct key_item *k;
85
86   k = xmalloc_clear (sizeof *k);
87   return k;
88 }
89
90 static void
91 release_key_items (struct key_item *k)
92 {
93   struct key_item *k2;
94
95   for (; k; k = k2)
96     {
97       k2 = k->next;
98       xfree (k->trust_regexp);
99       xfree (k);
100     }
101 }
102
103 #define KEY_HASH_TABLE_SIZE 1024
104
105 /*
106  * For fast keylook up we need a hash table.  Each byte of a KeyID
107  * should be distributed equally over the 256 possible values (except
108  * for v3 keyIDs but we consider them as not important here). So we
109  * can just use 10 bits to index a table of KEY_HASH_TABLE_SIZE key items.
110  * Possible optimization: Do not use key_items but other hash_table when the
111  * duplicates lists get too large.
112  */
113 static KeyHashTable
114 new_key_hash_table (void)
115 {
116   struct key_item **tbl;
117
118   tbl = xmalloc_clear (KEY_HASH_TABLE_SIZE * sizeof *tbl);
119   return tbl;
120 }
121
122 static void
123 release_key_hash_table (KeyHashTable tbl)
124 {
125   int i;
126
127   if (!tbl)
128     return;
129   for (i=0; i < KEY_HASH_TABLE_SIZE; i++)
130     release_key_items (tbl[i]);
131   xfree (tbl);
132 }
133
134 /*
135  * Returns: True if the keyID is in the given hash table
136  */
137 static int
138 test_key_hash_table (KeyHashTable tbl, u32 *kid)
139 {
140   struct key_item *k;
141
142   for (k = tbl[(kid[1] % KEY_HASH_TABLE_SIZE)]; k; k = k->next)
143     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
144       return 1;
145   return 0;
146 }
147
148 /*
149  * Add a new key to the hash table.  The key is identified by its key ID.
150  */
151 static void
152 add_key_hash_table (KeyHashTable tbl, u32 *kid)
153 {
154   int i = kid[1] % KEY_HASH_TABLE_SIZE;
155   struct key_item *k, *kk;
156
157   for (k = tbl[i]; k; k = k->next)
158     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
159       return; /* already in table */
160
161   kk = new_key_item ();
162   kk->kid[0] = kid[0];
163   kk->kid[1] = kid[1];
164   kk->next = tbl[i];
165   tbl[i] = kk;
166 }
167
168 /*
169  * Release a key_array
170  */
171 static void
172 release_key_array ( struct key_array *keys )
173 {
174     struct key_array *k;
175
176     if (keys) {
177         for (k=keys; k->keyblock; k++)
178             release_kbnode (k->keyblock);
179         xfree (keys);
180     }
181 }
182
183 \f
184 /*********************************************
185  **********  Initialization  *****************
186  *********************************************/
187
188
189
190 /*
191  * Used to register extra ultimately trusted keys - this has to be done
192  * before initializing the validation module.
193  * FIXME: Should be replaced by a function to add those keys to the trustdb.
194  */
195 void
196 tdb_register_trusted_keyid (u32 *keyid)
197 {
198   struct key_item *k;
199
200   k = new_key_item ();
201   k->kid[0] = keyid[0];
202   k->kid[1] = keyid[1];
203   k->next = user_utk_list;
204   user_utk_list = k;
205 }
206
207 void
208 tdb_register_trusted_key( const char *string )
209 {
210   gpg_error_t err;
211   KEYDB_SEARCH_DESC desc;
212
213   err = classify_user_id (string, &desc, 1);
214   if (err || desc.mode != KEYDB_SEARCH_MODE_LONG_KID )
215     {
216       log_error(_("'%s' is not a valid long keyID\n"), string );
217       return;
218     }
219
220   register_trusted_keyid(desc.u.kid);
221 }
222
223 /*
224  * Helper to add a key to the global list of ultimately trusted keys.
225  * Returns: true = inserted, false = already in list.
226  */
227 static int
228 add_utk (u32 *kid)
229 {
230   struct key_item *k;
231
232   if (tdb_keyid_is_utk (kid))
233     return 0;
234
235   k = new_key_item ();
236   k->kid[0] = kid[0];
237   k->kid[1] = kid[1];
238   k->ownertrust = TRUST_ULTIMATE;
239   k->next = utk_list;
240   utk_list = k;
241   if( opt.verbose > 1 )
242     log_info(_("key %s: accepted as trusted key\n"), keystr(kid));
243   return 1;
244 }
245
246
247 /****************
248  * Verify that all our secret keys are usable and put them into the utk_list.
249  */
250 static void
251 verify_own_keys (ctrl_t ctrl)
252 {
253   TRUSTREC rec;
254   ulong recnum;
255   int rc;
256   struct key_item *k;
257
258   if (utk_list)
259     return;
260
261   /* scan the trustdb to find all ultimately trusted keys */
262   for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
263     {
264       if ( rec.rectype == RECTYPE_TRUST
265            && (rec.r.trust.ownertrust & TRUST_MASK) == TRUST_ULTIMATE)
266         {
267             byte *fpr = rec.r.trust.fingerprint;
268             int fprlen;
269             u32 kid[2];
270
271             /* Problem: We do only use fingerprints in the trustdb but
272              * we need the keyID here to indetify the key; we can only
273              * use that ugly hack to distinguish between 16 and 20
274              * butes fpr - it does not work always so we better change
275              * the whole validation code to only work with
276              * fingerprints */
277             fprlen = (!fpr[16] && !fpr[17] && !fpr[18] && !fpr[19])? 16:20;
278             keyid_from_fingerprint (ctrl, fpr, fprlen, kid);
279             if (!add_utk (kid))
280               log_info(_("key %s occurs more than once in the trustdb\n"),
281                        keystr(kid));
282         }
283     }
284
285   /* Put any --trusted-key keys into the trustdb */
286   for (k = user_utk_list; k; k = k->next)
287     {
288       if ( add_utk (k->kid) )
289         { /* not yet in trustDB as ultimately trusted */
290           PKT_public_key pk;
291
292           memset (&pk, 0, sizeof pk);
293           rc = get_pubkey (ctrl, &pk, k->kid);
294           if (rc)
295             log_info(_("key %s: no public key for trusted key - skipped\n"),
296                      keystr(k->kid));
297           else
298             {
299               tdb_update_ownertrust
300                 (ctrl, &pk, ((tdb_get_ownertrust (ctrl, &pk, 0) & ~TRUST_MASK)
301                              | TRUST_ULTIMATE ));
302               release_public_key_parts (&pk);
303             }
304
305           log_info (_("key %s marked as ultimately trusted\n"),keystr(k->kid));
306         }
307     }
308
309   /* release the helper table table */
310   release_key_items (user_utk_list);
311   user_utk_list = NULL;
312   return;
313 }
314
315 /* Returns whether KID is on the list of ultimately trusted keys.  */
316 int
317 tdb_keyid_is_utk (u32 *kid)
318 {
319   struct key_item *k;
320
321   for (k = utk_list; k; k = k->next)
322     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
323       return 1;
324
325   return 0;
326 }
327
328 /* Return the list of ultimately trusted keys.  */
329 struct key_item *
330 tdb_utks (void)
331 {
332   return utk_list;
333 }
334 \f
335 /*********************************************
336  *********** TrustDB stuff *******************
337  *********************************************/
338
339 /*
340  * Read a record but die if it does not exist
341  */
342 static void
343 read_record (ulong recno, TRUSTREC *rec, int rectype )
344 {
345   int rc = tdbio_read_record (recno, rec, rectype);
346   if (rc)
347     {
348       log_error(_("trust record %lu, req type %d: read failed: %s\n"),
349                 recno, rec->rectype, gpg_strerror (rc) );
350       tdbio_invalid();
351     }
352   if (rectype != rec->rectype)
353     {
354       log_error(_("trust record %lu is not of requested type %d\n"),
355                 rec->recnum, rectype);
356       tdbio_invalid();
357     }
358 }
359
360 /*
361  * Write a record and die on error
362  */
363 static void
364 write_record (ctrl_t ctrl, TRUSTREC *rec)
365 {
366   int rc = tdbio_write_record (ctrl, rec);
367   if (rc)
368     {
369       log_error(_("trust record %lu, type %d: write failed: %s\n"),
370                             rec->recnum, rec->rectype, gpg_strerror (rc) );
371       tdbio_invalid();
372     }
373 }
374
375 /*
376  * sync the TrustDb and die on error
377  */
378 static void
379 do_sync(void)
380 {
381     int rc = tdbio_sync ();
382     if(rc)
383       {
384         log_error (_("trustdb: sync failed: %s\n"), gpg_strerror (rc) );
385         g10_exit(2);
386       }
387 }
388
389 const char *
390 trust_model_string (int model)
391 {
392   switch (model)
393     {
394     case TM_CLASSIC:  return "classic";
395     case TM_PGP:      return "pgp";
396     case TM_EXTERNAL: return "external";
397     case TM_TOFU:     return "tofu";
398     case TM_TOFU_PGP: return "tofu+pgp";
399     case TM_ALWAYS:   return "always";
400     case TM_DIRECT:   return "direct";
401     default:          return "unknown";
402     }
403 }
404
405 /****************
406  * Perform some checks over the trustdb
407  *  level 0: only open the db
408  *        1: used for initial program startup
409  */
410 int
411 setup_trustdb( int level, const char *dbname )
412 {
413     /* just store the args */
414     if( trustdb_args.init )
415         return 0;
416     trustdb_args.level = level;
417     trustdb_args.dbname = dbname? xstrdup(dbname): NULL;
418     return 0;
419 }
420
421 void
422 how_to_fix_the_trustdb ()
423 {
424   const char *name = trustdb_args.dbname;
425
426   if (!name)
427     name = "trustdb.gpg";
428
429   log_info (_("You may try to re-create the trustdb using the commands:\n"));
430   log_info ("  cd %s\n", default_homedir ());
431   log_info ("  %s --export-ownertrust > otrust.tmp\n", GPG_NAME);
432 #ifdef HAVE_W32_SYSTEM
433   log_info ("  del %s\n", name);
434 #else
435   log_info ("  rm %s\n", name);
436 #endif
437   log_info ("  %s --import-ownertrust < otrust.tmp\n", GPG_NAME);
438   log_info (_("If that does not work, please consult the manual\n"));
439 }
440
441
442 /* Initialize the trustdb.  With NO_CREATE set a missing trustdb is
443  * not an error and the function won't terminate the process on error;
444  * in that case 0 is returned if there is a trustdb or an error code
445  * if no trustdb is available.  */
446 gpg_error_t
447 init_trustdb (ctrl_t ctrl, int no_create)
448 {
449   int level = trustdb_args.level;
450   const char* dbname = trustdb_args.dbname;
451
452   if( trustdb_args.init )
453     return 0;
454
455   trustdb_args.init = 1;
456
457   if(level==0 || level==1)
458     {
459       int rc = tdbio_set_dbname (ctrl, dbname, (!no_create && level),
460                                  &trustdb_args.no_trustdb);
461       if (no_create && trustdb_args.no_trustdb)
462         {
463           /* No trustdb found and the caller asked us not to create
464            * it.  Return an error and set the initialization state
465            * back so that we always test for an existing trustdb.  */
466           trustdb_args.init = 0;
467           return gpg_error (GPG_ERR_ENOENT);
468         }
469       if (rc)
470         log_fatal("can't init trustdb: %s\n", gpg_strerror (rc) );
471     }
472   else
473     BUG();
474
475   if(opt.trust_model==TM_AUTO)
476     {
477       /* Try and set the trust model off of whatever the trustdb says
478          it is. */
479       opt.trust_model=tdbio_read_model();
480
481       /* Sanity check this ;) */
482       if(opt.trust_model != TM_CLASSIC
483          && opt.trust_model != TM_PGP
484          && opt.trust_model != TM_TOFU_PGP
485          && opt.trust_model != TM_TOFU
486          && opt.trust_model != TM_EXTERNAL)
487         {
488           log_info(_("unable to use unknown trust model (%d) - "
489                      "assuming %s trust model\n"),opt.trust_model,"pgp");
490           opt.trust_model = TM_PGP;
491         }
492
493       if(opt.verbose)
494         log_info(_("using %s trust model\n"),
495                  trust_model_string (opt.trust_model));
496     }
497
498   if (opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC
499       || opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP)
500     {
501       /* Verify the list of ultimately trusted keys and move the
502          --trusted-keys list there as well. */
503       if(level==1)
504         verify_own_keys (ctrl);
505
506       if(!tdbio_db_matches_options())
507         pending_check_trustdb=1;
508     }
509
510   return 0;
511 }
512
513
514 /* Check whether we have a trust database, initializing it if
515    necessary if the trust model is not 'always trust'.  Returns true
516    if we do have a usable trust database.  */
517 int
518 have_trustdb (ctrl_t ctrl)
519 {
520   return !init_trustdb (ctrl, opt.trust_model == TM_ALWAYS);
521 }
522
523
524 /****************
525  * Recreate the WoT but do not ask for new ownertrusts.  Special
526  * feature: In batch mode and without a forced yes, this is only done
527  * when a check is due.  This can be used to run the check from a crontab
528  */
529 void
530 check_trustdb (ctrl_t ctrl)
531 {
532   init_trustdb (ctrl, 0);
533   if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
534       || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU)
535     {
536       if (opt.batch && !opt.answer_yes)
537         {
538           ulong scheduled;
539
540           scheduled = tdbio_read_nextcheck ();
541           if (!scheduled)
542             {
543               log_info (_("no need for a trustdb check\n"));
544               return;
545             }
546
547           if (scheduled > make_timestamp ())
548             {
549               log_info (_("next trustdb check due at %s\n"),
550                         strtimestamp (scheduled));
551               return;
552             }
553         }
554
555       validate_keys (ctrl, 0);
556     }
557   else
558     log_info (_("no need for a trustdb check with '%s' trust model\n"),
559               trust_model_string(opt.trust_model));
560 }
561
562
563 /*
564  * Recreate the WoT.
565  */
566 void
567 update_trustdb (ctrl_t ctrl)
568 {
569   init_trustdb (ctrl, 0);
570   if (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
571       || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU)
572     validate_keys (ctrl, 1);
573   else
574     log_info (_("no need for a trustdb update with '%s' trust model\n"),
575               trust_model_string(opt.trust_model));
576 }
577
578 void
579 tdb_revalidation_mark (ctrl_t ctrl)
580 {
581   init_trustdb (ctrl, 0);
582   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
583     return;
584
585   /* We simply set the time for the next check to 1 (far back in 1970)
586      so that a --update-trustdb will be scheduled.  */
587   if (tdbio_write_nextcheck (ctrl, 1))
588     do_sync ();
589   pending_check_trustdb = 1;
590 }
591
592 int
593 trustdb_pending_check(void)
594 {
595   return pending_check_trustdb;
596 }
597
598 /* If the trustdb is dirty, and we're interactive, update it.
599    Otherwise, check it unless no-auto-check-trustdb is set. */
600 void
601 tdb_check_or_update (ctrl_t ctrl)
602 {
603   if (trustdb_pending_check ())
604     {
605       if (opt.interactive)
606         update_trustdb (ctrl);
607       else if (!opt.no_auto_check_trustdb)
608         check_trustdb (ctrl);
609     }
610 }
611
612 void
613 read_trust_options (ctrl_t ctrl,
614                     byte *trust_model, ulong *created, ulong *nextcheck,
615                     byte *marginals, byte *completes, byte *cert_depth,
616                     byte *min_cert_level)
617 {
618   TRUSTREC opts;
619
620   init_trustdb (ctrl, 0);
621   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
622     memset (&opts, 0, sizeof opts);
623   else
624     read_record (0, &opts, RECTYPE_VER);
625
626   if(trust_model)
627     *trust_model=opts.r.ver.trust_model;
628   if(created)
629     *created=opts.r.ver.created;
630   if(nextcheck)
631     *nextcheck=opts.r.ver.nextcheck;
632   if(marginals)
633     *marginals=opts.r.ver.marginals;
634   if(completes)
635     *completes=opts.r.ver.completes;
636   if(cert_depth)
637     *cert_depth=opts.r.ver.cert_depth;
638   if(min_cert_level)
639     *min_cert_level=opts.r.ver.min_cert_level;
640 }
641
642 /***********************************************
643  ***********  Ownertrust et al. ****************
644  ***********************************************/
645
646 static int
647 read_trust_record (ctrl_t ctrl, PKT_public_key *pk, TRUSTREC *rec)
648 {
649   int rc;
650
651   init_trustdb (ctrl, 0);
652   rc = tdbio_search_trust_bypk (pk, rec);
653   if (rc)
654     {
655       if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
656         log_error ("trustdb: searching trust record failed: %s\n",
657                    gpg_strerror (rc));
658       return rc;
659     }
660
661   if (rec->rectype != RECTYPE_TRUST)
662     {
663       log_error ("trustdb: record %lu is not a trust record\n",
664                  rec->recnum);
665       return GPG_ERR_TRUSTDB;
666     }
667
668   return 0;
669 }
670
671
672 /*
673  * Return the assigned ownertrust value for the given public key.  The
674  * key should be the primary key.  If NO_CREATE is set a missing
675  * trustdb will not be created.  This comes for example handy when we
676  * want to print status lines (DECRYPTION_KEY) which carry ownertrust
677  * values but we usually use --always-trust.
678  */
679 unsigned int
680 tdb_get_ownertrust (ctrl_t ctrl, PKT_public_key *pk, int no_create)
681 {
682   TRUSTREC rec;
683   gpg_error_t err;
684
685   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
686     return TRUST_UNKNOWN;
687
688   /* If the caller asked not to create a trustdb we call init_trustdb
689    * directly and allow it to fail with an error code for a
690    * non-existing trustdb.  */
691   if (no_create && init_trustdb (ctrl, 1))
692     return TRUST_UNKNOWN;
693
694   err = read_trust_record (ctrl, pk, &rec);
695   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
696     return TRUST_UNKNOWN; /* no record yet */
697   if (err)
698     {
699       tdbio_invalid ();
700       return TRUST_UNKNOWN; /* actually never reached */
701     }
702
703   return rec.r.trust.ownertrust;
704 }
705
706
707 unsigned int
708 tdb_get_min_ownertrust (ctrl_t ctrl, PKT_public_key *pk, int no_create)
709 {
710   TRUSTREC rec;
711   gpg_error_t err;
712
713   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
714     return TRUST_UNKNOWN;
715
716   /* If the caller asked not to create a trustdb we call init_trustdb
717    * directly and allow it to fail with an error code for a
718    * non-existing trustdb.  */
719   if (no_create && init_trustdb (ctrl, 1))
720     return TRUST_UNKNOWN;
721
722   err = read_trust_record (ctrl, pk, &rec);
723   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
724     return TRUST_UNKNOWN; /* no record yet */
725   if (err)
726     {
727       tdbio_invalid ();
728       return TRUST_UNKNOWN; /* actually never reached */
729     }
730
731   return rec.r.trust.min_ownertrust;
732 }
733
734
735 /*
736  * Set the trust value of the given public key to the new value.
737  * The key should be a primary one.
738  */
739 void
740 tdb_update_ownertrust (ctrl_t ctrl, PKT_public_key *pk, unsigned int new_trust )
741 {
742   TRUSTREC rec;
743   gpg_error_t err;
744
745   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
746     return;
747
748   err = read_trust_record (ctrl, pk, &rec);
749   if (!err)
750     {
751       if (DBG_TRUST)
752         log_debug ("update ownertrust from %u to %u\n",
753                    (unsigned int)rec.r.trust.ownertrust, new_trust );
754       if (rec.r.trust.ownertrust != new_trust)
755         {
756           rec.r.trust.ownertrust = new_trust;
757           write_record (ctrl, &rec);
758           tdb_revalidation_mark (ctrl);
759           do_sync ();
760         }
761     }
762   else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
763     { /* no record yet - create a new one */
764       size_t dummy;
765
766       if (DBG_TRUST)
767         log_debug ("insert ownertrust %u\n", new_trust );
768
769       memset (&rec, 0, sizeof rec);
770       rec.recnum = tdbio_new_recnum (ctrl);
771       rec.rectype = RECTYPE_TRUST;
772       fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
773       rec.r.trust.ownertrust = new_trust;
774       write_record (ctrl, &rec);
775       tdb_revalidation_mark (ctrl);
776       do_sync ();
777     }
778   else
779     {
780       tdbio_invalid ();
781     }
782 }
783
784 static void
785 update_min_ownertrust (ctrl_t ctrl, u32 *kid, unsigned int new_trust)
786 {
787   PKT_public_key *pk;
788   TRUSTREC rec;
789   gpg_error_t err;
790
791   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
792     return;
793
794   pk = xmalloc_clear (sizeof *pk);
795   err = get_pubkey (ctrl, pk, kid);
796   if (err)
797     {
798       log_error (_("public key %s not found: %s\n"),
799                  keystr (kid), gpg_strerror (err));
800       xfree (pk);
801       return;
802     }
803
804   err = read_trust_record (ctrl, pk, &rec);
805   if (!err)
806     {
807       if (DBG_TRUST)
808         log_debug ("key %08lX%08lX: update min_ownertrust from %u to %u\n",
809                    (ulong)kid[0],(ulong)kid[1],
810                    (unsigned int)rec.r.trust.min_ownertrust,
811                    new_trust );
812       if (rec.r.trust.min_ownertrust != new_trust)
813         {
814           rec.r.trust.min_ownertrust = new_trust;
815           write_record (ctrl, &rec);
816           tdb_revalidation_mark (ctrl);
817           do_sync ();
818         }
819     }
820   else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
821     { /* no record yet - create a new one */
822       size_t dummy;
823
824       if (DBG_TRUST)
825         log_debug ("insert min_ownertrust %u\n", new_trust );
826
827       memset (&rec, 0, sizeof rec);
828       rec.recnum = tdbio_new_recnum (ctrl);
829       rec.rectype = RECTYPE_TRUST;
830       fingerprint_from_pk (pk, rec.r.trust.fingerprint, &dummy);
831       rec.r.trust.min_ownertrust = new_trust;
832       write_record (ctrl, &rec);
833       tdb_revalidation_mark (ctrl);
834       do_sync ();
835     }
836   else
837     {
838       tdbio_invalid ();
839     }
840
841   free_public_key (pk);
842 }
843
844
845 /*
846  * Clear the ownertrust and min_ownertrust values.
847  *
848  * Return: True if a change actually happened.
849  */
850 int
851 tdb_clear_ownertrusts (ctrl_t ctrl, PKT_public_key *pk)
852 {
853   TRUSTREC rec;
854   gpg_error_t err;
855
856   init_trustdb (ctrl, 0);
857
858   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
859     return 0;
860
861   err = read_trust_record (ctrl, pk, &rec);
862   if (!err)
863     {
864       if (DBG_TRUST)
865         {
866           log_debug ("clearing ownertrust (old value %u)\n",
867                      (unsigned int)rec.r.trust.ownertrust);
868           log_debug ("clearing min_ownertrust (old value %u)\n",
869                      (unsigned int)rec.r.trust.min_ownertrust);
870         }
871       if (rec.r.trust.ownertrust || rec.r.trust.min_ownertrust)
872         {
873           rec.r.trust.ownertrust = 0;
874           rec.r.trust.min_ownertrust = 0;
875           write_record (ctrl, &rec);
876           tdb_revalidation_mark (ctrl);
877           do_sync ();
878           return 1;
879         }
880     }
881   else if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
882     {
883       tdbio_invalid ();
884     }
885   return 0;
886 }
887
888 /*
889  * Note: Caller has to do a sync
890  */
891 static void
892 update_validity (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *uid,
893                  int depth, int validity)
894 {
895   TRUSTREC trec, vrec;
896   gpg_error_t err;
897   ulong recno;
898
899   namehash_from_uid(uid);
900
901   err = read_trust_record (ctrl, pk, &trec);
902   if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
903     {
904       tdbio_invalid ();
905       return;
906     }
907   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
908     {
909       /* No record yet - create a new one. */
910       size_t dummy;
911
912       memset (&trec, 0, sizeof trec);
913       trec.recnum = tdbio_new_recnum (ctrl);
914       trec.rectype = RECTYPE_TRUST;
915       fingerprint_from_pk (pk, trec.r.trust.fingerprint, &dummy);
916       trec.r.trust.ownertrust = 0;
917       }
918
919   /* locate an existing one */
920   recno = trec.r.trust.validlist;
921   while (recno)
922     {
923       read_record (recno, &vrec, RECTYPE_VALID);
924       if ( !memcmp (vrec.r.valid.namehash, uid->namehash, 20) )
925         break;
926       recno = vrec.r.valid.next;
927     }
928
929   if (!recno) /* insert a new validity record */
930     {
931       memset (&vrec, 0, sizeof vrec);
932       vrec.recnum = tdbio_new_recnum (ctrl);
933       vrec.rectype = RECTYPE_VALID;
934       memcpy (vrec.r.valid.namehash, uid->namehash, 20);
935       vrec.r.valid.next = trec.r.trust.validlist;
936       trec.r.trust.validlist = vrec.recnum;
937     }
938   vrec.r.valid.validity = validity;
939   vrec.r.valid.full_count = uid->help_full_count;
940   vrec.r.valid.marginal_count = uid->help_marginal_count;
941   write_record (ctrl, &vrec);
942   trec.r.trust.depth = depth;
943   write_record (ctrl, &trec);
944 }
945
946
947 /***********************************************
948  *********  Query trustdb values  **************
949  ***********************************************/
950
951 /* Return true if key is disabled.  Note that this is usually used via
952    the pk_is_disabled macro.  */
953 int
954 tdb_cache_disabled_value (ctrl_t ctrl, PKT_public_key *pk)
955 {
956   gpg_error_t err;
957   TRUSTREC trec;
958   int disabled = 0;
959
960   if (pk->flags.disabled_valid)
961     return pk->flags.disabled;
962
963   init_trustdb (ctrl, 0);
964
965   if (trustdb_args.no_trustdb)
966     return 0;  /* No trustdb => not disabled.  */
967
968   err = read_trust_record (ctrl, pk, &trec);
969   if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
970     {
971       tdbio_invalid ();
972       goto leave;
973     }
974   if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
975     {
976       /* No record found, so assume not disabled.  */
977       goto leave;
978     }
979
980   if ((trec.r.trust.ownertrust & TRUST_FLAG_DISABLED))
981     disabled = 1;
982
983   /* Cache it for later so we don't need to look at the trustdb every
984      time */
985   pk->flags.disabled = disabled;
986   pk->flags.disabled_valid = 1;
987
988  leave:
989   return disabled;
990 }
991
992
993 void
994 tdb_check_trustdb_stale (ctrl_t ctrl)
995 {
996   static int did_nextcheck=0;
997
998   init_trustdb (ctrl, 0);
999
1000   if (trustdb_args.no_trustdb)
1001     return;  /* No trustdb => can't be stale.  */
1002
1003   if (!did_nextcheck
1004       && (opt.trust_model == TM_PGP || opt.trust_model == TM_CLASSIC
1005           || opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU))
1006     {
1007       ulong scheduled;
1008
1009       did_nextcheck = 1;
1010       scheduled = tdbio_read_nextcheck ();
1011       if ((scheduled && scheduled <= make_timestamp ())
1012           || pending_check_trustdb)
1013         {
1014           if (opt.no_auto_check_trustdb)
1015             {
1016               pending_check_trustdb = 1;
1017               if (!opt.quiet)
1018                 log_info (_("please do a --check-trustdb\n"));
1019             }
1020           else
1021             {
1022               if (!opt.quiet)
1023                 log_info (_("checking the trustdb\n"));
1024               validate_keys (ctrl, 0);
1025             }
1026         }
1027     }
1028 }
1029
1030 /*
1031  * Return the validity information for KB/PK (at least one of them
1032  * must be non-NULL).  This is the core of get_validity.  If SIG is
1033  * not NULL, then the trust is being evaluated in the context of the
1034  * provided signature.  This is used by the TOFU code to record
1035  * statistics.
1036  */
1037 unsigned int
1038 tdb_get_validity_core (ctrl_t ctrl,
1039                        kbnode_t kb,
1040                        PKT_public_key *pk, PKT_user_id *uid,
1041                        PKT_public_key *main_pk,
1042                        PKT_signature *sig,
1043                        int may_ask)
1044 {
1045   TRUSTREC trec, vrec;
1046   gpg_error_t err = 0;
1047   ulong recno;
1048 #ifdef USE_TOFU
1049   unsigned int tofu_validity = TRUST_UNKNOWN;
1050   int free_kb = 0;
1051 #endif
1052   unsigned int validity = TRUST_UNKNOWN;
1053
1054   if (kb && pk)
1055     log_assert (keyid_cmp (pk_main_keyid (pk),
1056                            pk_main_keyid (kb->pkt->pkt.public_key)) == 0);
1057
1058   if (! pk)
1059     {
1060       log_assert (kb);
1061       pk = kb->pkt->pkt.public_key;
1062     }
1063
1064 #ifndef USE_TOFU
1065   (void)sig;
1066   (void)may_ask;
1067 #endif
1068
1069   init_trustdb (ctrl, 0);
1070
1071   /* If we have no trustdb (which also means it has not been created)
1072      and the trust-model is always, we don't know the validity -
1073      return immediately.  If we won't do that the tdbio code would try
1074      to open the trustdb and run into a fatal error.  */
1075   if (trustdb_args.no_trustdb && opt.trust_model == TM_ALWAYS)
1076     return TRUST_UNKNOWN;
1077
1078   check_trustdb_stale (ctrl);
1079
1080   if(opt.trust_model==TM_DIRECT)
1081     {
1082       /* Note that this happens BEFORE any user ID stuff is checked.
1083          The direct trust model applies to keys as a whole. */
1084       validity = tdb_get_ownertrust (ctrl, main_pk, 0);
1085       goto leave;
1086     }
1087
1088 #ifdef USE_TOFU
1089   if (opt.trust_model == TM_TOFU || opt.trust_model == TM_TOFU_PGP)
1090     {
1091       kbnode_t n = NULL;
1092       strlist_t user_id_list = NULL;
1093       int done = 0;
1094
1095       /* If the caller didn't supply a user id then use all uids.  */
1096       if (! uid)
1097         {
1098           if (! kb)
1099             {
1100               kb = get_pubkeyblock (ctrl, main_pk->keyid);
1101               free_kb = 1;
1102             }
1103           n = kb;
1104         }
1105
1106       if (DBG_TRUST && sig && sig->signers_uid)
1107         log_debug ("TOFU: only considering user id: '%s'\n",
1108                    sig->signers_uid);
1109
1110       while (!done && (uid || (n = find_next_kbnode (n, PKT_USER_ID))))
1111         {
1112           PKT_user_id *user_id;
1113           int expired = 0;
1114
1115           if (uid)
1116             {
1117               user_id = uid;
1118               /* If the caller specified a user id, then we only
1119                  process the specified user id and are done after the
1120                  first iteration.  */
1121               done = 1;
1122             }
1123           else
1124             user_id = n->pkt->pkt.user_id;
1125
1126           if (user_id->attrib_data)
1127             /* Skip user attributes.  */
1128             continue;
1129
1130           if (sig && sig->signers_uid)
1131             /* Make sure the UID matches.  */
1132             {
1133               char *email = mailbox_from_userid (user_id->name);
1134               if (!email || !*email || strcmp (sig->signers_uid, email) != 0)
1135                 {
1136                   if (DBG_TRUST)
1137                     log_debug ("TOFU: skipping user id '%s', which does"
1138                                " not match the signer's email ('%s')\n",
1139                                email, sig->signers_uid);
1140                   xfree (email);
1141                   continue;
1142                 }
1143               xfree (email);
1144             }
1145
1146           /* If the user id is revoked or expired, then skip it.  */
1147           if (user_id->flags.revoked || user_id->flags.expired)
1148             {
1149               if (DBG_TRUST)
1150                 {
1151                   char *s;
1152                   if (user_id->flags.revoked && user_id->flags.expired)
1153                     s = "revoked and expired";
1154                   else if (user_id->flags.revoked)
1155                     s = "revoked";
1156                   else
1157                     s = "expire";
1158
1159                   log_debug ("TOFU: Ignoring %s user id (%s)\n",
1160                              s, user_id->name);
1161                 }
1162
1163               if (user_id->flags.revoked)
1164                 continue;
1165
1166               expired = 1;
1167             }
1168
1169           add_to_strlist (&user_id_list, user_id->name);
1170           user_id_list->flags = expired;
1171         }
1172
1173       /* Process the user ids in the order they appear in the key
1174          block.  */
1175       strlist_rev (&user_id_list);
1176
1177       /* It only makes sense to observe any signature before getting
1178          the validity.  This is because if the current signature
1179          results in a conflict, then we damn well want to take that
1180          into account.  */
1181       if (sig)
1182         {
1183           err = tofu_register_signature (ctrl, main_pk, user_id_list,
1184                                          sig->digest, sig->digest_len,
1185                                          sig->timestamp, "unknown");
1186           if (err)
1187             {
1188               log_error ("TOFU: error registering signature: %s\n",
1189                          gpg_strerror (err));
1190
1191               tofu_validity = TRUST_UNKNOWN;
1192             }
1193         }
1194       if (! err)
1195         tofu_validity = tofu_get_validity (ctrl, main_pk, user_id_list,
1196                                            may_ask);
1197
1198       free_strlist (user_id_list);
1199       if (free_kb)
1200         release_kbnode (kb);
1201     }
1202 #endif /*USE_TOFU*/
1203
1204   if (opt.trust_model == TM_TOFU_PGP
1205       || opt.trust_model == TM_CLASSIC
1206       || opt.trust_model == TM_PGP)
1207     {
1208       err = read_trust_record (ctrl, main_pk, &trec);
1209       if (err && gpg_err_code (err) != GPG_ERR_NOT_FOUND)
1210         {
1211           tdbio_invalid ();
1212           return 0;
1213         }
1214       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1215         {
1216           /* No record found.  */
1217           validity = TRUST_UNKNOWN;
1218           goto leave;
1219         }
1220
1221       /* Loop over all user IDs */
1222       recno = trec.r.trust.validlist;
1223       validity = 0;
1224       while (recno)
1225         {
1226           read_record (recno, &vrec, RECTYPE_VALID);
1227
1228           if(uid)
1229             {
1230               /* If a user ID is given we return the validity for that
1231                  user ID ONLY.  If the namehash is not found, then
1232                  there is no validity at all (i.e. the user ID wasn't
1233                  signed). */
1234               if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1235                 {
1236                   validity=(vrec.r.valid.validity & TRUST_MASK);
1237                   break;
1238                 }
1239             }
1240           else
1241             {
1242               /* If no user ID is given, we take the maximum validity
1243                  over all user IDs */
1244               if (validity < (vrec.r.valid.validity & TRUST_MASK))
1245                 validity = (vrec.r.valid.validity & TRUST_MASK);
1246             }
1247
1248           recno = vrec.r.valid.next;
1249         }
1250
1251       if ((trec.r.trust.ownertrust & TRUST_FLAG_DISABLED))
1252         {
1253           validity |= TRUST_FLAG_DISABLED;
1254           pk->flags.disabled = 1;
1255         }
1256       else
1257         pk->flags.disabled = 0;
1258       pk->flags.disabled_valid = 1;
1259     }
1260
1261  leave:
1262 #ifdef USE_TOFU
1263   validity = tofu_wot_trust_combine (tofu_validity, validity);
1264 #else /*!USE_TOFU*/
1265   validity &= TRUST_MASK;
1266
1267   if (validity == TRUST_NEVER)
1268     /* TRUST_NEVER trumps everything else.  */
1269     validity |= TRUST_NEVER;
1270   if (validity == TRUST_EXPIRED)
1271     /* TRUST_EXPIRED trumps everything but TRUST_NEVER.  */
1272     validity |= TRUST_EXPIRED;
1273 #endif /*!USE_TOFU*/
1274
1275   if (opt.trust_model != TM_TOFU
1276       && pending_check_trustdb)
1277     validity |= TRUST_FLAG_PENDING_CHECK;
1278
1279   return validity;
1280 }
1281
1282
1283 static void
1284 get_validity_counts (ctrl_t ctrl, PKT_public_key *pk, PKT_user_id *uid)
1285 {
1286   TRUSTREC trec, vrec;
1287   ulong recno;
1288
1289   if(pk==NULL || uid==NULL)
1290     BUG();
1291
1292   namehash_from_uid(uid);
1293
1294   uid->help_marginal_count=uid->help_full_count=0;
1295
1296   init_trustdb (ctrl, 0);
1297
1298   if(read_trust_record (ctrl, pk, &trec))
1299     return;
1300
1301   /* loop over all user IDs */
1302   recno = trec.r.trust.validlist;
1303   while (recno)
1304     {
1305       read_record (recno, &vrec, RECTYPE_VALID);
1306
1307       if(memcmp(vrec.r.valid.namehash,uid->namehash,20)==0)
1308         {
1309           uid->help_marginal_count=vrec.r.valid.marginal_count;
1310           uid->help_full_count=vrec.r.valid.full_count;
1311           /*  es_printf("Fetched marginal %d, full %d\n",uid->help_marginal_count,uid->help_full_count); */
1312           break;
1313         }
1314
1315       recno = vrec.r.valid.next;
1316     }
1317 }
1318
1319 void
1320 list_trust_path( const char *username )
1321 {
1322   (void)username;
1323 }
1324
1325 /****************
1326  * Enumerate all keys, which are needed to build all trust paths for
1327  * the given key.  This function does not return the key itself or
1328  * the ultimate key (the last point in cerificate chain).  Only
1329  * certificate chains which ends up at an ultimately trusted key
1330  * are listed.  If ownertrust or validity is not NULL, the corresponding
1331  * value for the returned LID is also returned in these variable(s).
1332  *
1333  *  1) create a void pointer and initialize it to NULL
1334  *  2) pass this void pointer by reference to this function.
1335  *     Set lid to the key you want to enumerate and pass it by reference.
1336  *  3) call this function as long as it does not return -1
1337  *     to indicate EOF. LID does contain the next key used to build the web
1338  *  4) Always call this function a last time with LID set to NULL,
1339  *     so that it can free its context.
1340  *
1341  * Returns: -1 on EOF or the level of the returned LID
1342  */
1343 int
1344 enum_cert_paths( void **context, ulong *lid,
1345                  unsigned *ownertrust, unsigned *validity )
1346 {
1347   (void)context;
1348   (void)lid;
1349   (void)ownertrust;
1350   (void)validity;
1351   return -1;
1352 }
1353
1354
1355 /****************
1356  * Print the current path
1357  */
1358 void
1359 enum_cert_paths_print (void **context, FILE *fp,
1360                        int refresh, ulong selected_lid)
1361 {
1362   (void)context;
1363   (void)fp;
1364   (void)refresh;
1365   (void)selected_lid;
1366 }
1367
1368
1369 \f
1370 /****************************************
1371  *********** NEW NEW NEW ****************
1372  ****************************************/
1373
1374 static int
1375 ask_ownertrust (ctrl_t ctrl, u32 *kid, int minimum)
1376 {
1377   PKT_public_key *pk;
1378   int rc;
1379   int ot;
1380
1381   pk = xmalloc_clear (sizeof *pk);
1382   rc = get_pubkey (ctrl, pk, kid);
1383   if (rc)
1384     {
1385       log_error (_("public key %s not found: %s\n"),
1386                  keystr(kid), gpg_strerror (rc) );
1387       return TRUST_UNKNOWN;
1388     }
1389
1390   if(opt.force_ownertrust)
1391     {
1392       log_info("force trust for key %s to %s\n",
1393                keystr(kid),trust_value_to_string(opt.force_ownertrust));
1394       tdb_update_ownertrust (ctrl, pk, opt.force_ownertrust);
1395       ot=opt.force_ownertrust;
1396     }
1397   else
1398     {
1399       ot=edit_ownertrust (ctrl, pk, 0);
1400       if(ot>0)
1401         ot = tdb_get_ownertrust (ctrl, pk, 0);
1402       else if(ot==0)
1403         ot = minimum?minimum:TRUST_UNDEFINED;
1404       else
1405         ot = -1; /* quit */
1406     }
1407
1408   free_public_key( pk );
1409
1410   return ot;
1411 }
1412
1413
1414 static void
1415 mark_keyblock_seen (KeyHashTable tbl, KBNODE node)
1416 {
1417   for ( ;node; node = node->next )
1418     if (node->pkt->pkttype == PKT_PUBLIC_KEY
1419         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1420       {
1421         u32 aki[2];
1422
1423         keyid_from_pk (node->pkt->pkt.public_key, aki);
1424         add_key_hash_table (tbl, aki);
1425       }
1426 }
1427
1428
1429 static void
1430 dump_key_array (int depth, struct key_array *keys)
1431 {
1432   struct key_array *kar;
1433
1434   for (kar=keys; kar->keyblock; kar++)
1435     {
1436       KBNODE node = kar->keyblock;
1437       u32 kid[2];
1438
1439       keyid_from_pk(node->pkt->pkt.public_key, kid);
1440       es_printf ("%d:%08lX%08lX:K::%c::::\n",
1441                  depth, (ulong)kid[0], (ulong)kid[1], '?');
1442
1443       for (; node; node = node->next)
1444         {
1445           if (node->pkt->pkttype == PKT_USER_ID)
1446             {
1447               int len = node->pkt->pkt.user_id->len;
1448
1449               if (len > 30)
1450                 len = 30;
1451               es_printf ("%d:%08lX%08lX:U:::%c:::",
1452                          depth, (ulong)kid[0], (ulong)kid[1],
1453                          (node->flag & 4)? 'f':
1454                          (node->flag & 2)? 'm':
1455                          (node->flag & 1)? 'q':'-');
1456               es_write_sanitized (es_stdout, node->pkt->pkt.user_id->name,
1457                                   len, ":", NULL);
1458               es_putc (':', es_stdout);
1459               es_putc ('\n', es_stdout);
1460             }
1461         }
1462     }
1463 }
1464
1465
1466 static void
1467 store_validation_status (ctrl_t ctrl, int depth,
1468                          kbnode_t keyblock, KeyHashTable stored)
1469 {
1470   KBNODE node;
1471   int status;
1472   int any = 0;
1473
1474   for (node=keyblock; node; node = node->next)
1475     {
1476       if (node->pkt->pkttype == PKT_USER_ID)
1477         {
1478           PKT_user_id *uid = node->pkt->pkt.user_id;
1479           if (node->flag & 4)
1480             status = TRUST_FULLY;
1481           else if (node->flag & 2)
1482             status = TRUST_MARGINAL;
1483           else if (node->flag & 1)
1484             status = TRUST_UNDEFINED;
1485           else
1486             status = 0;
1487
1488           if (status)
1489             {
1490               update_validity (ctrl, keyblock->pkt->pkt.public_key,
1491                                uid, depth, status);
1492
1493               mark_keyblock_seen(stored,keyblock);
1494
1495               any = 1;
1496             }
1497         }
1498     }
1499
1500   if (any)
1501     do_sync ();
1502 }
1503
1504
1505 /* Returns a sanitized copy of the regexp (which might be "", but not
1506    NULL). */
1507 #ifndef DISABLE_REGEX
1508 static char *
1509 sanitize_regexp(const char *old)
1510 {
1511   size_t start=0,len=strlen(old),idx=0;
1512   int escaped=0,standard_bracket=0;
1513   char *new=xmalloc((len*2)+1); /* enough to \-escape everything if we
1514                                    have to */
1515
1516   /* There are basically two commonly-used regexps here.  GPG and most
1517      versions of PGP use "<[^>]+[@.]example\.com>$" and PGP (9)
1518      command line uses "example.com" (i.e. whatever the user specifies,
1519      and we can't expect users know to use "\." instead of ".").  So
1520      here are the rules: we're allowed to start with "<[^>]+[@.]" and
1521      end with ">$" or start and end with nothing.  In between, the
1522      only legal regex character is ".", and everything else gets
1523      escaped.  Part of the gotcha here is that some regex packages
1524      allow more than RFC-4880 requires.  For example, 4880 has no "{}"
1525      operator, but GNU regex does.  Commenting removes these operators
1526      from consideration.  A possible future enhancement is to use
1527      commenting to effectively back off a given regex to the Henry
1528      Spencer syntax in 4880. -dshaw */
1529
1530   /* Are we bracketed between "<[^>]+[@.]" and ">$" ? */
1531   if(len>=12 && strncmp(old,"<[^>]+[@.]",10)==0
1532      && old[len-2]=='>' && old[len-1]=='$')
1533     {
1534       strcpy(new,"<[^>]+[@.]");
1535       idx=strlen(new);
1536       standard_bracket=1;
1537       start+=10;
1538       len-=2;
1539     }
1540
1541   /* Walk the remaining characters and ensure that everything that is
1542      left is not an operational regex character. */
1543   for(;start<len;start++)
1544     {
1545       if(!escaped && old[start]=='\\')
1546         escaped=1;
1547       else if(!escaped && old[start]!='.')
1548         new[idx++]='\\';
1549       else
1550         escaped=0;
1551
1552       new[idx++]=old[start];
1553     }
1554
1555   new[idx]='\0';
1556
1557   /* Note that the (sub)string we look at might end with a bare "\".
1558      If it does, leave it that way.  If the regexp actually ended with
1559      ">$", then it was escaping the ">" and is fine.  If the regexp
1560      actually ended with the bare "\", then it's an illegal regexp and
1561      regcomp should kick it out. */
1562
1563   if(standard_bracket)
1564     strcat(new,">$");
1565
1566   return new;
1567 }
1568 #endif /*!DISABLE_REGEX*/
1569
1570 /* Used by validate_one_keyblock to confirm a regexp within a trust
1571    signature.  Returns 1 for match, and 0 for no match or regex
1572    error. */
1573 static int
1574 check_regexp(const char *expr,const char *string)
1575 {
1576 #ifdef DISABLE_REGEX
1577   (void)expr;
1578   (void)string;
1579   /* When DISABLE_REGEX is defined, assume all regexps do not
1580      match. */
1581   return 0;
1582 #else
1583   int ret;
1584   char *regexp;
1585
1586   regexp=sanitize_regexp(expr);
1587
1588 #ifdef __riscos__
1589   ret=riscos_check_regexp(expr, string, DBG_TRUST);
1590 #else
1591   {
1592     regex_t pat;
1593
1594     ret=regcomp(&pat,regexp,REG_ICASE|REG_NOSUB|REG_EXTENDED);
1595     if(ret==0)
1596       {
1597         ret=regexec(&pat,string,0,NULL,0);
1598         regfree(&pat);
1599       }
1600     ret=(ret==0);
1601   }
1602 #endif
1603
1604   if(DBG_TRUST)
1605     log_debug("regexp '%s' ('%s') on '%s': %s\n",
1606               regexp,expr,string,ret?"YES":"NO");
1607
1608   xfree(regexp);
1609
1610   return ret;
1611 #endif
1612 }
1613
1614 /*
1615  * Return true if the key is signed by one of the keys in the given
1616  * key ID list.  User IDs with a valid signature are marked by node
1617  * flags as follows:
1618  *  flag bit 0: There is at least one signature
1619  *           1: There is marginal confidence that this is a legitimate uid
1620  *           2: There is full confidence that this is a legitimate uid.
1621  *           8: Used for internal purposes.
1622  *           9: Ditto (in mark_usable_uid_certs())
1623  *          10: Ditto (ditto)
1624  * This function assumes that all kbnode flags are cleared on entry.
1625  */
1626 static int
1627 validate_one_keyblock (ctrl_t ctrl, kbnode_t kb, struct key_item *klist,
1628                        u32 curtime, u32 *next_expire)
1629 {
1630   struct key_item *kr;
1631   KBNODE node, uidnode=NULL;
1632   PKT_user_id *uid=NULL;
1633   PKT_public_key *pk = kb->pkt->pkt.public_key;
1634   u32 main_kid[2];
1635   int issigned=0, any_signed = 0;
1636
1637   keyid_from_pk(pk, main_kid);
1638   for (node=kb; node; node = node->next)
1639     {
1640       /* A bit of discussion here: is it better for the web of trust
1641          to be built among only self-signed uids?  On the one hand, a
1642          self-signed uid is a statement that the key owner definitely
1643          intended that uid to be there, but on the other hand, a
1644          signed (but not self-signed) uid does carry trust, of a sort,
1645          even if it is a statement being made by people other than the
1646          key owner "through" the uids on the key owner's key.  I'm
1647          going with the latter.  However, if the user ID was
1648          explicitly revoked, or passively allowed to expire, that
1649          should stop validity through the user ID until it is
1650          resigned.  -dshaw */
1651
1652       if (node->pkt->pkttype == PKT_USER_ID
1653           && !node->pkt->pkt.user_id->flags.revoked
1654           && !node->pkt->pkt.user_id->flags.expired)
1655         {
1656           if (uidnode && issigned)
1657             {
1658               if (uid->help_full_count >= opt.completes_needed
1659                   || uid->help_marginal_count >= opt.marginals_needed )
1660                 uidnode->flag |= 4;
1661               else if (uid->help_full_count || uid->help_marginal_count)
1662                 uidnode->flag |= 2;
1663               uidnode->flag |= 1;
1664               any_signed = 1;
1665             }
1666           uidnode = node;
1667           uid=uidnode->pkt->pkt.user_id;
1668
1669           /* If the selfsig is going to expire... */
1670           if(uid->expiredate && uid->expiredate<*next_expire)
1671             *next_expire = uid->expiredate;
1672
1673           issigned = 0;
1674           get_validity_counts (ctrl, pk, uid);
1675           mark_usable_uid_certs (ctrl, kb, uidnode, main_kid, klist,
1676                                  curtime, next_expire);
1677         }
1678       else if (node->pkt->pkttype == PKT_SIGNATURE
1679                && (node->flag & (1<<8)) && uid)
1680         {
1681           /* Note that we are only seeing unrevoked sigs here */
1682           PKT_signature *sig = node->pkt->pkt.signature;
1683
1684           kr = is_in_klist (klist, sig);
1685           /* If the trust_regexp does not match, it's as if the sig
1686              did not exist.  This is safe for non-trust sigs as well
1687              since we don't accept a regexp on the sig unless it's a
1688              trust sig. */
1689           if (kr && (!kr->trust_regexp
1690                      || !(opt.trust_model == TM_PGP
1691                           || opt.trust_model == TM_TOFU_PGP)
1692                      || (uidnode
1693                          && check_regexp(kr->trust_regexp,
1694                                          uidnode->pkt->pkt.user_id->name))))
1695             {
1696               /* Are we part of a trust sig chain?  We always favor
1697                  the latest trust sig, rather than the greater or
1698                  lesser trust sig or value.  I could make a decent
1699                  argument for any of these cases, but this seems to be
1700                  what PGP does, and I'd like to be compatible. -dms */
1701               if ((opt.trust_model == TM_PGP
1702                    || opt.trust_model == TM_TOFU_PGP)
1703                   && sig->trust_depth
1704                   && pk->trust_timestamp <= sig->timestamp)
1705                 {
1706                   unsigned char depth;
1707
1708                   /* If the depth on the signature is less than the
1709                      chain currently has, then use the signature depth
1710                      so we don't increase the depth beyond what the
1711                      signer wanted.  If the depth on the signature is
1712                      more than the chain currently has, then use the
1713                      chain depth so we use as much of the signature
1714                      depth as the chain will permit.  An ultimately
1715                      trusted signature can restart the depth to
1716                      whatever level it likes. */
1717
1718                   if (sig->trust_depth < kr->trust_depth
1719                       || kr->ownertrust == TRUST_ULTIMATE)
1720                     depth = sig->trust_depth;
1721                   else
1722                     depth = kr->trust_depth;
1723
1724                   if (depth)
1725                     {
1726                       if(DBG_TRUST)
1727                         log_debug ("trust sig on %s, sig depth is %d,"
1728                                    " kr depth is %d\n",
1729                                    uidnode->pkt->pkt.user_id->name,
1730                                    sig->trust_depth,
1731                                    kr->trust_depth);
1732
1733                       /* If we got here, we know that:
1734
1735                          this is a trust sig.
1736
1737                          it's a newer trust sig than any previous trust
1738                          sig on this key (not uid).
1739
1740                          it is legal in that it was either generated by an
1741                          ultimate key, or a key that was part of a trust
1742                          chain, and the depth does not violate the
1743                          original trust sig.
1744
1745                          if there is a regexp attached, it matched
1746                          successfully.
1747                       */
1748
1749                       if (DBG_TRUST)
1750                         log_debug ("replacing trust value %d with %d and "
1751                                    "depth %d with %d\n",
1752                                    pk->trust_value,sig->trust_value,
1753                                    pk->trust_depth,depth);
1754
1755                       pk->trust_value = sig->trust_value;
1756                       pk->trust_depth = depth-1;
1757
1758                       /* If the trust sig contains a regexp, record it
1759                          on the pk for the next round. */
1760                       if (sig->trust_regexp)
1761                         pk->trust_regexp = sig->trust_regexp;
1762                     }
1763                 }
1764
1765               if (kr->ownertrust == TRUST_ULTIMATE)
1766                 uid->help_full_count = opt.completes_needed;
1767               else if (kr->ownertrust == TRUST_FULLY)
1768                 uid->help_full_count++;
1769               else if (kr->ownertrust == TRUST_MARGINAL)
1770                 uid->help_marginal_count++;
1771               issigned = 1;
1772             }
1773         }
1774     }
1775
1776   if (uidnode && issigned)
1777     {
1778       if (uid->help_full_count >= opt.completes_needed
1779           || uid->help_marginal_count >= opt.marginals_needed )
1780         uidnode->flag |= 4;
1781       else if (uid->help_full_count || uid->help_marginal_count)
1782         uidnode->flag |= 2;
1783       uidnode->flag |= 1;
1784       any_signed = 1;
1785     }
1786
1787   return any_signed;
1788 }
1789
1790
1791 static int
1792 search_skipfnc (void *opaque, u32 *kid, int dummy_uid_no)
1793 {
1794   (void)dummy_uid_no;
1795   return test_key_hash_table ((KeyHashTable)opaque, kid);
1796 }
1797
1798
1799 /*
1800  * Scan all keys and return a key_array of all suitable keys from
1801  * kllist.  The caller has to pass keydb handle so that we don't use
1802  * to create our own.  Returns either a key_array or NULL in case of
1803  * an error.  No results found are indicated by an empty array.
1804  * Caller hast to release the returned array.
1805  */
1806 static struct key_array *
1807 validate_key_list (ctrl_t ctrl, KEYDB_HANDLE hd, KeyHashTable full_trust,
1808                    struct key_item *klist, u32 curtime, u32 *next_expire)
1809 {
1810   KBNODE keyblock = NULL;
1811   struct key_array *keys = NULL;
1812   size_t nkeys, maxkeys;
1813   int rc;
1814   KEYDB_SEARCH_DESC desc;
1815
1816   maxkeys = 1000;
1817   keys = xmalloc ((maxkeys+1) * sizeof *keys);
1818   nkeys = 0;
1819
1820   rc = keydb_search_reset (hd);
1821   if (rc)
1822     {
1823       log_error ("keydb_search_reset failed: %s\n", gpg_strerror (rc));
1824       xfree (keys);
1825       return NULL;
1826     }
1827
1828   memset (&desc, 0, sizeof desc);
1829   desc.mode = KEYDB_SEARCH_MODE_FIRST;
1830   desc.skipfnc = search_skipfnc;
1831   desc.skipfncvalue = full_trust;
1832   rc = keydb_search (hd, &desc, 1, NULL);
1833   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1834     {
1835       keys[nkeys].keyblock = NULL;
1836       return keys;
1837     }
1838   if (rc)
1839     {
1840       log_error ("keydb_search(first) failed: %s\n", gpg_strerror (rc));
1841       goto die;
1842     }
1843
1844   desc.mode = KEYDB_SEARCH_MODE_NEXT; /* change mode */
1845   do
1846     {
1847       PKT_public_key *pk;
1848
1849       rc = keydb_get_keyblock (hd, &keyblock);
1850       if (rc)
1851         {
1852           log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1853           goto die;
1854         }
1855
1856       if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1857         {
1858           log_debug ("ooops: invalid pkttype %d encountered\n",
1859                      keyblock->pkt->pkttype);
1860           dump_kbnode (keyblock);
1861           release_kbnode(keyblock);
1862           continue;
1863         }
1864
1865       /* prepare the keyblock for further processing */
1866       merge_keys_and_selfsig (ctrl, keyblock);
1867       clear_kbnode_flags (keyblock);
1868       pk = keyblock->pkt->pkt.public_key;
1869       if (pk->has_expired || pk->flags.revoked)
1870         {
1871           /* it does not make sense to look further at those keys */
1872           mark_keyblock_seen (full_trust, keyblock);
1873         }
1874       else if (validate_one_keyblock (ctrl, keyblock, klist,
1875                                       curtime, next_expire))
1876         {
1877           KBNODE node;
1878
1879           if (pk->expiredate && pk->expiredate >= curtime
1880               && pk->expiredate < *next_expire)
1881             *next_expire = pk->expiredate;
1882
1883           if (nkeys == maxkeys) {
1884             maxkeys += 1000;
1885             keys = xrealloc (keys, (maxkeys+1) * sizeof *keys);
1886           }
1887           keys[nkeys++].keyblock = keyblock;
1888
1889           /* Optimization - if all uids are fully trusted, then we
1890              never need to consider this key as a candidate again. */
1891
1892           for (node=keyblock; node; node = node->next)
1893             if (node->pkt->pkttype == PKT_USER_ID && !(node->flag & 4))
1894               break;
1895
1896           if(node==NULL)
1897             mark_keyblock_seen (full_trust, keyblock);
1898
1899           keyblock = NULL;
1900         }
1901
1902       release_kbnode (keyblock);
1903       keyblock = NULL;
1904     }
1905   while (!(rc = keydb_search (hd, &desc, 1, NULL)));
1906
1907   if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
1908     {
1909       log_error ("keydb_search_next failed: %s\n", gpg_strerror (rc));
1910       goto die;
1911     }
1912
1913   keys[nkeys].keyblock = NULL;
1914   return keys;
1915
1916  die:
1917   keys[nkeys].keyblock = NULL;
1918   release_key_array (keys);
1919   return NULL;
1920 }
1921
1922 /* Caller must sync */
1923 static void
1924 reset_trust_records (ctrl_t ctrl)
1925 {
1926   TRUSTREC rec;
1927   ulong recnum;
1928   int count = 0, nreset = 0;
1929
1930   for (recnum=1; !tdbio_read_record (recnum, &rec, 0); recnum++ )
1931     {
1932       if(rec.rectype==RECTYPE_TRUST)
1933         {
1934           count++;
1935           if(rec.r.trust.min_ownertrust)
1936             {
1937               rec.r.trust.min_ownertrust=0;
1938               write_record (ctrl, &rec);
1939             }
1940
1941         }
1942       else if(rec.rectype==RECTYPE_VALID
1943               && ((rec.r.valid.validity&TRUST_MASK)
1944                   || rec.r.valid.marginal_count
1945                   || rec.r.valid.full_count))
1946         {
1947           rec.r.valid.validity &= ~TRUST_MASK;
1948           rec.r.valid.marginal_count=rec.r.valid.full_count=0;
1949           nreset++;
1950           write_record (ctrl, &rec);
1951         }
1952
1953     }
1954
1955   if (opt.verbose)
1956     {
1957       log_info (ngettext("%d key processed",
1958                          "%d keys processed",
1959                          count), count);
1960       log_printf (ngettext(" (%d validity count cleared)\n",
1961                            " (%d validity counts cleared)\n",
1962                            nreset), nreset);
1963     }
1964 }
1965
1966 /*
1967  * Run the key validation procedure.
1968  *
1969  * This works this way:
1970  * Step 1: Find all ultimately trusted keys (UTK).
1971  *         mark them all as seen and put them into klist.
1972  * Step 2: loop max_cert_times
1973  * Step 3:   if OWNERTRUST of any key in klist is undefined
1974  *             ask user to assign ownertrust
1975  * Step 4:   Loop over all keys in the keyDB which are not marked seen
1976  * Step 5:     if key is revoked or expired
1977  *                mark key as seen
1978  *                continue loop at Step 4
1979  * Step 6:     For each user ID of that key signed by a key in klist
1980  *                Calculate validity by counting trusted signatures.
1981  *                Set validity of user ID
1982  * Step 7:     If any signed user ID was found
1983  *                mark key as seen
1984  *             End Loop
1985  * Step 8:   Build a new klist from all fully trusted keys from step 6
1986  *           End Loop
1987  *         Ready
1988  *
1989  */
1990 static int
1991 validate_keys (ctrl_t ctrl, int interactive)
1992 {
1993   int rc = 0;
1994   int quit=0;
1995   struct key_item *klist = NULL;
1996   struct key_item *k;
1997   struct key_array *keys = NULL;
1998   struct key_array *kar;
1999   KEYDB_HANDLE kdb = NULL;
2000   KBNODE node;
2001   int depth;
2002   int ot_unknown, ot_undefined, ot_never, ot_marginal, ot_full, ot_ultimate;
2003   KeyHashTable stored,used,full_trust;
2004   u32 start_time, next_expire;
2005
2006   /* Make sure we have all sigs cached.  TODO: This is going to
2007      require some architectural re-thinking, as it is agonizingly slow.
2008      Perhaps combine this with reset_trust_records(), or only check
2009      the caches on keys that are actually involved in the web of
2010      trust. */
2011   keydb_rebuild_caches (ctrl, 0);
2012
2013   kdb = keydb_new ();
2014   if (!kdb)
2015     return gpg_error_from_syserror ();
2016
2017   start_time = make_timestamp ();
2018   next_expire = 0xffffffff; /* set next expire to the year 2106 */
2019   stored = new_key_hash_table ();
2020   used = new_key_hash_table ();
2021   full_trust = new_key_hash_table ();
2022
2023   reset_trust_records (ctrl);
2024
2025   /* Fixme: Instead of always building a UTK list, we could just build it
2026    * here when needed */
2027   if (!utk_list)
2028     {
2029       if (!opt.quiet)
2030         log_info (_("no ultimately trusted keys found\n"));
2031       goto leave;
2032     }
2033
2034   /* mark all UTKs as used and fully_trusted and set validity to
2035      ultimate */
2036   for (k=utk_list; k; k = k->next)
2037     {
2038       KBNODE keyblock;
2039       PKT_public_key *pk;
2040
2041       keyblock = get_pubkeyblock (ctrl, k->kid);
2042       if (!keyblock)
2043         {
2044           log_error (_("public key of ultimately"
2045                        " trusted key %s not found\n"), keystr(k->kid));
2046           continue;
2047         }
2048       mark_keyblock_seen (used, keyblock);
2049       mark_keyblock_seen (stored, keyblock);
2050       mark_keyblock_seen (full_trust, keyblock);
2051       pk = keyblock->pkt->pkt.public_key;
2052       for (node=keyblock; node; node = node->next)
2053         {
2054           if (node->pkt->pkttype == PKT_USER_ID)
2055             update_validity (ctrl, pk, node->pkt->pkt.user_id,
2056                              0, TRUST_ULTIMATE);
2057         }
2058       if ( pk->expiredate && pk->expiredate >= start_time
2059            && pk->expiredate < next_expire)
2060         next_expire = pk->expiredate;
2061
2062       release_kbnode (keyblock);
2063       do_sync ();
2064     }
2065
2066   if (opt.trust_model == TM_TOFU)
2067     /* In the TOFU trust model, we only need to save the ultimately
2068        trusted keys.  */
2069     goto leave;
2070
2071   klist = utk_list;
2072
2073   if (!opt.quiet)
2074     log_info ("marginals needed: %d  completes needed: %d  trust model: %s\n",
2075               opt.marginals_needed, opt.completes_needed,
2076               trust_model_string (opt.trust_model));
2077
2078   for (depth=0; depth < opt.max_cert_depth; depth++)
2079     {
2080       int valids=0,key_count;
2081       /* See whether we should assign ownertrust values to the keys in
2082          klist.  */
2083       ot_unknown = ot_undefined = ot_never = 0;
2084       ot_marginal = ot_full = ot_ultimate = 0;
2085       for (k=klist; k; k = k->next)
2086         {
2087           int min=0;
2088
2089           /* 120 and 60 are as per RFC2440 */
2090           if(k->trust_value>=120)
2091             min=TRUST_FULLY;
2092           else if(k->trust_value>=60)
2093             min=TRUST_MARGINAL;
2094
2095           if(min!=k->min_ownertrust)
2096             update_min_ownertrust (ctrl, k->kid,min);
2097
2098           if (interactive && k->ownertrust == TRUST_UNKNOWN)
2099             {
2100               k->ownertrust = ask_ownertrust (ctrl, k->kid,min);
2101
2102               if (k->ownertrust == (unsigned int)(-1))
2103                 {
2104                   quit=1;
2105                   goto leave;
2106                 }
2107             }
2108
2109           /* This can happen during transition from an old trustdb
2110              before trust sigs.  It can also happen if a user uses two
2111              different versions of GnuPG or changes the --trust-model
2112              setting. */
2113           if(k->ownertrust<min)
2114             {
2115               if(DBG_TRUST)
2116                 log_debug("key %08lX%08lX:"
2117                           " overriding ownertrust '%s' with '%s'\n",
2118                           (ulong)k->kid[0],(ulong)k->kid[1],
2119                           trust_value_to_string(k->ownertrust),
2120                           trust_value_to_string(min));
2121
2122               k->ownertrust=min;
2123             }
2124
2125           if (k->ownertrust == TRUST_UNKNOWN)
2126             ot_unknown++;
2127           else if (k->ownertrust == TRUST_UNDEFINED)
2128             ot_undefined++;
2129           else if (k->ownertrust == TRUST_NEVER)
2130             ot_never++;
2131           else if (k->ownertrust == TRUST_MARGINAL)
2132             ot_marginal++;
2133           else if (k->ownertrust == TRUST_FULLY)
2134             ot_full++;
2135           else if (k->ownertrust == TRUST_ULTIMATE)
2136             ot_ultimate++;
2137
2138           valids++;
2139         }
2140
2141       /* Find all keys which are signed by a key in kdlist */
2142       keys = validate_key_list (ctrl, kdb, full_trust, klist,
2143                                 start_time, &next_expire);
2144       if (!keys)
2145         {
2146           log_error ("validate_key_list failed\n");
2147           rc = GPG_ERR_GENERAL;
2148           goto leave;
2149         }
2150
2151       for (key_count=0, kar=keys; kar->keyblock; kar++, key_count++)
2152         ;
2153
2154       /* Store the calculated valididation status somewhere */
2155       if (opt.verbose > 1 && DBG_TRUST)
2156         dump_key_array (depth, keys);
2157
2158       for (kar=keys; kar->keyblock; kar++)
2159         store_validation_status (ctrl, depth, kar->keyblock, stored);
2160
2161       if (!opt.quiet)
2162         log_info (_("depth: %d  valid: %3d  signed: %3d"
2163                     "  trust: %d-, %dq, %dn, %dm, %df, %du\n"),
2164                   depth, valids, key_count, ot_unknown, ot_undefined,
2165                   ot_never, ot_marginal, ot_full, ot_ultimate );
2166
2167       /* Build a new kdlist from all fully valid keys in KEYS */
2168       if (klist != utk_list)
2169         release_key_items (klist);
2170       klist = NULL;
2171       for (kar=keys; kar->keyblock; kar++)
2172         {
2173           for (node=kar->keyblock; node; node = node->next)
2174             {
2175               if (node->pkt->pkttype == PKT_USER_ID && (node->flag & 4))
2176                 {
2177                   u32 kid[2];
2178
2179                   /* have we used this key already? */
2180                   keyid_from_pk (kar->keyblock->pkt->pkt.public_key, kid);
2181                   if(test_key_hash_table(used,kid)==0)
2182                     {
2183                       /* Normally we add both the primary and subkey
2184                          ids to the hash via mark_keyblock_seen, but
2185                          since we aren't using this hash as a skipfnc,
2186                          that doesn't matter here. */
2187                       add_key_hash_table (used,kid);
2188                       k = new_key_item ();
2189                       k->kid[0]=kid[0];
2190                       k->kid[1]=kid[1];
2191                       k->ownertrust =
2192                         (tdb_get_ownertrust
2193                            (ctrl, kar->keyblock->pkt->pkt.public_key, 0)
2194                          & TRUST_MASK);
2195                       k->min_ownertrust = tdb_get_min_ownertrust
2196                         (ctrl, kar->keyblock->pkt->pkt.public_key, 0);
2197                       k->trust_depth=
2198                         kar->keyblock->pkt->pkt.public_key->trust_depth;
2199                       k->trust_value=
2200                         kar->keyblock->pkt->pkt.public_key->trust_value;
2201                       if(kar->keyblock->pkt->pkt.public_key->trust_regexp)
2202                         k->trust_regexp=
2203                           xstrdup(kar->keyblock->pkt->
2204                                    pkt.public_key->trust_regexp);
2205                       k->next = klist;
2206                       klist = k;
2207                       break;
2208                     }
2209                 }
2210             }
2211         }
2212       release_key_array (keys);
2213       keys = NULL;
2214       if (!klist)
2215         break; /* no need to dive in deeper */
2216     }
2217
2218  leave:
2219   keydb_release (kdb);
2220   release_key_array (keys);
2221   if (klist != utk_list)
2222     release_key_items (klist);
2223   release_key_hash_table (full_trust);
2224   release_key_hash_table (used);
2225   release_key_hash_table (stored);
2226   if (!rc && !quit) /* mark trustDB as checked */
2227     {
2228       int rc2;
2229
2230       if (next_expire == 0xffffffff || next_expire < start_time )
2231         tdbio_write_nextcheck (ctrl, 0);
2232       else
2233         {
2234           tdbio_write_nextcheck (ctrl, next_expire);
2235           if (!opt.quiet)
2236             log_info (_("next trustdb check due at %s\n"),
2237                       strtimestamp (next_expire));
2238         }
2239
2240       rc2 = tdbio_update_version_record (ctrl);
2241       if (rc2)
2242         {
2243           log_error (_("unable to update trustdb version record: "
2244                        "write failed: %s\n"), gpg_strerror (rc2));
2245           tdbio_invalid ();
2246         }
2247
2248       do_sync ();
2249       pending_check_trustdb = 0;
2250     }
2251
2252   return rc;
2253 }