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