Tizen 2.1 base
[framework/security/gnupg.git] / g10 / tdbio.c
1 /* tdbio.c
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19  * USA.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <assert.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32
33 #include "errors.h"
34 #include "iobuf.h"
35 #include "memory.h"
36 #include "util.h"
37 #include "options.h"
38 #include "main.h"
39 #include "i18n.h"
40 #include "trustdb.h"
41 #include "tdbio.h"
42
43 #if defined(HAVE_DOSISH_SYSTEM)
44 #define ftruncate chsize
45 #endif
46
47 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
48 #define MY_O_BINARY  O_BINARY
49 #else
50 #define MY_O_BINARY  0
51 #endif
52
53
54 /****************
55  * Yes, this is a very simple implementation. We should really
56  * use a page aligned buffer and read complete pages.
57  * To implement a simple trannsaction system, this is sufficient.
58  */
59 typedef struct cache_ctrl_struct *CACHE_CTRL;
60 struct cache_ctrl_struct {
61     CACHE_CTRL next;
62     struct {
63         unsigned used:1;
64         unsigned dirty:1;
65     } flags;
66     ulong recno;
67     char data[TRUST_RECORD_LEN];
68 };
69
70 #define MAX_CACHE_ENTRIES_SOFT  200    /* may be increased while in a */
71 #define MAX_CACHE_ENTRIES_HARD  10000  /* transaction to this one */
72 static CACHE_CTRL cache_list;
73 static int cache_entries;
74 static int cache_is_dirty;
75
76 /* a type used to pass infomation to cmp_krec_fpr */
77 struct cmp_krec_fpr_struct {
78     int pubkey_algo;
79     const char *fpr;
80     int fprlen;
81 };
82
83 /* a type used to pass infomation to cmp_[s]dir */
84 struct cmp_xdir_struct {
85     int pubkey_algo;
86     u32 keyid[2];
87 };
88
89
90 static char *db_name;
91 static DOTLOCK lockhandle;
92 static int is_locked;
93 static int  db_fd = -1;
94 static int in_transaction;
95
96 static void open_db(void);
97 static void migrate_from_v2 (void);
98
99
100 \f
101 /*************************************
102  ************* record cache **********
103  *************************************/
104
105 /****************
106  * Get the data from therecord cache and return a
107  * pointer into that cache.  Caller should copy
108  * the return data.  NULL is returned on a cache miss.
109  */
110 static const char *
111 get_record_from_cache( ulong recno )
112 {
113     CACHE_CTRL r;
114
115     for( r = cache_list; r; r = r->next ) {
116         if( r->flags.used && r->recno == recno )
117             return r->data;
118     }
119     return NULL;
120 }
121
122
123 static int
124 write_cache_item( CACHE_CTRL r )
125 {
126     int n;
127
128     if( lseek( db_fd, r->recno * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
129         log_error(_("trustdb rec %lu: lseek failed: %s\n"),
130                                             r->recno, strerror(errno) );
131         return G10ERR_WRITE_FILE;
132     }
133     n = write( db_fd, r->data, TRUST_RECORD_LEN);
134     if( n != TRUST_RECORD_LEN ) {
135         log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
136                                             r->recno, n, strerror(errno) );
137         return G10ERR_WRITE_FILE;
138     }
139     r->flags.dirty = 0;
140     return 0;
141 }
142
143 /****************
144  * Put data into the cache.  This function may flush the
145  * some cache entries if there is not enough space available.
146  */
147 int
148 put_record_into_cache( ulong recno, const char *data )
149 {
150     CACHE_CTRL r, unused;
151     int dirty_count = 0;
152     int clean_count = 0;
153
154     /* see whether we already cached this one */
155     for( unused = NULL, r = cache_list; r; r = r->next ) {
156         if( !r->flags.used ) {
157             if( !unused )
158                 unused = r;
159         }
160         else if( r->recno == recno ) {
161             if( !r->flags.dirty ) {
162                 /* Hmmm: should we use a a copy and compare? */
163                 if( memcmp(r->data, data, TRUST_RECORD_LEN ) ) {
164                     r->flags.dirty = 1;
165                     cache_is_dirty = 1;
166                 }
167             }
168             memcpy( r->data, data, TRUST_RECORD_LEN );
169             return 0;
170         }
171         if( r->flags.used ) {
172             if( r->flags.dirty )
173                 dirty_count++;
174             else
175                 clean_count++;
176         }
177     }
178     /* not in the cache: add a new entry */
179     if( unused ) { /* reuse this entry */
180         r = unused;
181         r->flags.used = 1;
182         r->recno = recno;
183         memcpy( r->data, data, TRUST_RECORD_LEN );
184         r->flags.dirty = 1;
185         cache_is_dirty = 1;
186         cache_entries++;
187         return 0;
188     }
189     /* see whether we reached the limit */
190     if( cache_entries < MAX_CACHE_ENTRIES_SOFT ) { /* no */
191         r = xmalloc( sizeof *r );
192         r->flags.used = 1;
193         r->recno = recno;
194         memcpy( r->data, data, TRUST_RECORD_LEN );
195         r->flags.dirty = 1;
196         r->next = cache_list;
197         cache_list = r;
198         cache_is_dirty = 1;
199         cache_entries++;
200         return 0;
201     }
202     /* cache is full: discard some clean entries */
203     if( clean_count ) {
204         int n = clean_count / 3; /* discard a third of the clean entries */
205         if( !n )
206             n = 1;
207         for( unused = NULL, r = cache_list; r; r = r->next ) {
208             if( r->flags.used && !r->flags.dirty ) {
209                 if( !unused )
210                     unused = r;
211                 r->flags.used = 0;
212                 cache_entries--;
213                 if( !--n )
214                     break;
215             }
216         }
217         assert( unused );
218         r = unused;
219         r->flags.used = 1;
220         r->recno = recno;
221         memcpy( r->data, data, TRUST_RECORD_LEN );
222         r->flags.dirty = 1;
223         cache_is_dirty = 1;
224         cache_entries++;
225         return 0;
226     }
227     /* no clean entries: have to flush some dirty entries */
228     if( in_transaction ) {
229         /* but we can't do this while in a transaction
230          * we increase the cache size instead */
231         if( cache_entries < MAX_CACHE_ENTRIES_HARD ) { /* no */
232             if( opt.debug && !(cache_entries % 100) )
233                 log_debug("increasing tdbio cache size\n");
234             r = xmalloc( sizeof *r );
235             r->flags.used = 1;
236             r->recno = recno;
237             memcpy( r->data, data, TRUST_RECORD_LEN );
238             r->flags.dirty = 1;
239             r->next = cache_list;
240             cache_list = r;
241             cache_is_dirty = 1;
242             cache_entries++;
243             return 0;
244         }
245         log_info(_("trustdb transaction too large\n"));
246         return G10ERR_RESOURCE_LIMIT;
247     }
248     if( dirty_count ) {
249         int n = dirty_count / 5; /* discard some dirty entries */
250         if( !n )
251             n = 1;
252         if( !is_locked ) {
253             if( make_dotlock( lockhandle, -1 ) )
254                 log_fatal("can't acquire lock - giving up\n");
255             else
256                 is_locked = 1;
257         }
258         for( unused = NULL, r = cache_list; r; r = r->next ) {
259             if( r->flags.used && r->flags.dirty ) {
260                 int rc = write_cache_item( r );
261                 if( rc )
262                     return rc;
263                 if( !unused )
264                     unused = r;
265                 r->flags.used = 0;
266                 cache_entries--;
267                 if( !--n )
268                     break;
269             }
270         }
271         if( !opt.lock_once ) {
272             if( !release_dotlock( lockhandle ) )
273                 is_locked = 0;
274         }
275         assert( unused );
276         r = unused;
277         r->flags.used = 1;
278         r->recno = recno;
279         memcpy( r->data, data, TRUST_RECORD_LEN );
280         r->flags.dirty = 1;
281         cache_is_dirty = 1;
282         cache_entries++;
283         return 0;
284     }
285     BUG();
286 }
287
288
289 int
290 tdbio_is_dirty()
291 {
292     return cache_is_dirty;
293 }
294
295
296 /****************
297  * Flush the cache.  This cannot be used while in a transaction.
298  */
299 int
300 tdbio_sync()
301 {
302     CACHE_CTRL r;
303     int did_lock = 0;
304
305     if( db_fd == -1 )
306         open_db();
307     if( in_transaction )
308         log_bug("tdbio: syncing while in transaction\n");
309
310     if( !cache_is_dirty )
311         return 0;
312
313     if( !is_locked ) {
314         if( make_dotlock( lockhandle, -1 ) )
315             log_fatal("can't acquire lock - giving up\n");
316         else
317             is_locked = 1;
318         did_lock = 1;
319     }
320     for( r = cache_list; r; r = r->next ) {
321         if( r->flags.used && r->flags.dirty ) {
322             int rc = write_cache_item( r );
323             if( rc )
324                 return rc;
325         }
326     }
327     cache_is_dirty = 0;
328     if( did_lock && !opt.lock_once ) {
329         if( !release_dotlock( lockhandle ) )
330             is_locked = 0;
331     }
332
333     return 0;
334 }
335
336 #if 0
337 /* The transaction code is disabled in the 1.2.x branch, as it is not
338    yet used.  It will be enabled in 1.3.x. */
339
340 /****************
341  * Simple transactions system:
342  * Everything between begin_transaction and end/cancel_transaction
343  * is not immediatly written but at the time of end_transaction.
344  *
345  */
346 int
347 tdbio_begin_transaction()
348 {
349     int rc;
350
351     if( in_transaction )
352         log_bug("tdbio: nested transactions\n");
353     /* flush everything out */
354     rc = tdbio_sync();
355     if( rc )
356         return rc;
357     in_transaction = 1;
358     return 0;
359 }
360
361 int
362 tdbio_end_transaction()
363 {
364     int rc;
365
366     if( !in_transaction )
367         log_bug("tdbio: no active transaction\n");
368     if( !is_locked ) {
369         if( make_dotlock( lockhandle, -1 ) )
370             log_fatal("can't acquire lock - giving up\n");
371         else
372             is_locked = 1;
373     }
374     block_all_signals();
375     in_transaction = 0;
376     rc = tdbio_sync();
377     unblock_all_signals();
378     if( !opt.lock_once ) {
379         if( !release_dotlock( lockhandle ) )
380             is_locked = 0;
381     }
382     return rc;
383 }
384
385 int
386 tdbio_cancel_transaction()
387 {
388     CACHE_CTRL r;
389
390     if( !in_transaction )
391         log_bug("tdbio: no active transaction\n");
392
393     /* remove all dirty marked entries, so that the original ones
394      * are read back the next time */
395     if( cache_is_dirty ) {
396         for( r = cache_list; r; r = r->next ) {
397             if( r->flags.used && r->flags.dirty ) {
398                 r->flags.used = 0;
399                 cache_entries--;
400             }
401         }
402         cache_is_dirty = 0;
403     }
404
405     in_transaction = 0;
406     return 0;
407 }
408 #endif
409
410 \f
411 /********************************************************
412  **************** cached I/O functions ******************
413  ********************************************************/
414
415 static void
416 cleanup(void)
417 {
418     if( is_locked ) {
419         if( !release_dotlock(lockhandle) )
420             is_locked = 0;
421     }
422 }
423
424 /* Caller must sync */
425 int
426 tdbio_update_version_record (void)
427 {
428   TRUSTREC rec;
429   int rc;
430
431   memset( &rec, 0, sizeof rec );
432
433   rc=tdbio_read_record( 0, &rec, RECTYPE_VER);
434   if(rc==0)
435     {
436       rec.r.ver.created     = make_timestamp();
437       rec.r.ver.marginals   = opt.marginals_needed;
438       rec.r.ver.completes   = opt.completes_needed;
439       rec.r.ver.cert_depth  = opt.max_cert_depth;
440       rec.r.ver.trust_model = opt.trust_model;
441       rc=tdbio_write_record(&rec);
442     }
443
444   return rc;
445 }
446
447 static int
448 create_version_record (void)
449 {
450   TRUSTREC rec;
451   int rc;
452   
453   memset( &rec, 0, sizeof rec );
454   rec.r.ver.version     = 3;
455   rec.r.ver.created     = make_timestamp();
456   rec.r.ver.marginals   = opt.marginals_needed;
457   rec.r.ver.completes   = opt.completes_needed;
458   rec.r.ver.cert_depth  = opt.max_cert_depth;
459   if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
460     rec.r.ver.trust_model = opt.trust_model;
461   else
462     rec.r.ver.trust_model = TM_PGP;
463   rec.rectype = RECTYPE_VER;
464   rec.recnum = 0;
465   rc = tdbio_write_record( &rec );
466   if( !rc )
467     tdbio_sync();
468   return rc;
469 }
470
471
472
473 int
474 tdbio_set_dbname( const char *new_dbname, int create )
475 {
476     char *fname;
477     static int initialized = 0;
478
479     if( !initialized ) {
480         atexit( cleanup );
481         initialized = 1;
482     }
483
484     if(new_dbname==NULL)
485       fname=make_filename(opt.homedir,"trustdb" EXTSEP_S "gpg", NULL);
486     else if (*new_dbname != DIRSEP_C )
487       {
488         if (strchr(new_dbname, DIRSEP_C) )
489           fname = make_filename (new_dbname, NULL);
490         else
491           fname = make_filename (opt.homedir, new_dbname, NULL);
492       }
493     else
494       fname = xstrdup (new_dbname);
495
496     if( access( fname, R_OK ) ) {
497         if( errno != ENOENT ) {
498             log_error( _("can't access `%s': %s\n"), fname, strerror(errno) );
499             xfree(fname);
500             return G10ERR_TRUSTDB;
501         }
502         if( create ) {
503             FILE *fp;
504             TRUSTREC rec;
505             int rc;
506             char *p = strrchr( fname, DIRSEP_C );
507             mode_t oldmask;
508
509             assert(p);
510             *p = 0;
511             if( access( fname, F_OK ) ) {
512                 try_make_homedir( fname );
513                 log_fatal( _("%s: directory does not exist!\n"), fname );
514             }
515             *p = DIRSEP_C;
516
517             xfree(db_name);
518             db_name = fname;
519 #ifdef __riscos__
520             if( !lockhandle )
521                 lockhandle = create_dotlock( db_name );
522             if( !lockhandle )
523                 log_fatal( _("can't create lock for `%s'\n"), db_name );
524             if( make_dotlock( lockhandle, -1 ) )
525                 log_fatal( _("can't lock `%s'\n"), db_name );
526 #endif /* __riscos__ */
527             oldmask=umask(077);
528             if (is_secured_filename (fname)) {
529                 fp = NULL;
530                 errno = EPERM;
531             }
532             else
533                 fp =fopen( fname, "wb" );
534             umask(oldmask);
535             if( !fp )
536                 log_fatal( _("can't create `%s': %s\n"), fname, strerror(errno) );
537             fclose(fp);
538             db_fd = open( db_name, O_RDWR | MY_O_BINARY );
539             if( db_fd == -1 )
540                 log_fatal( _("can't open `%s': %s\n"), db_name, strerror(errno) );
541
542 #ifndef __riscos__
543             if( !lockhandle )
544                 lockhandle = create_dotlock( db_name );
545             if( !lockhandle )
546                 log_fatal( _("can't create lock for `%s'\n"), db_name );
547 #endif /* !__riscos__ */
548
549             rc = create_version_record ();
550             if( rc )
551                 log_fatal( _("%s: failed to create version record: %s"),
552                                                    fname, g10_errstr(rc));
553             /* and read again to check that we are okay */
554             if( tdbio_read_record( 0, &rec, RECTYPE_VER ) )
555                 log_fatal( _("%s: invalid trustdb created\n"), db_name );
556
557             if( !opt.quiet )
558                 log_info(_("%s: trustdb created\n"), db_name);
559
560             return 0;
561         }
562     }
563     xfree(db_name);
564     db_name = fname;
565     return 0;
566 }
567
568
569 const char *
570 tdbio_get_dbname()
571 {
572     return db_name;
573 }
574
575
576
577 static void
578 open_db()
579 {
580   byte buf[10];
581   int n;
582   TRUSTREC rec;
583
584   assert( db_fd == -1 );
585
586   if (!lockhandle )
587     lockhandle = create_dotlock( db_name );
588   if (!lockhandle )
589     log_fatal( _("can't create lock for `%s'\n"), db_name );
590 #ifdef __riscos__
591   if (make_dotlock( lockhandle, -1 ) )
592     log_fatal( _("can't lock `%s'\n"), db_name );
593 #endif /* __riscos__ */
594   db_fd = open (db_name, O_RDWR | MY_O_BINARY );
595   if (db_fd == -1 && (errno == EACCES
596 #ifdef EROFS
597                       || errno == EROFS)
598 #endif
599       ) {
600       db_fd = open (db_name, O_RDONLY | MY_O_BINARY );
601       if (db_fd != -1)
602           log_info (_("NOTE: trustdb not writable\n"));
603   }
604   if ( db_fd == -1 )
605     log_fatal( _("can't open `%s': %s\n"), db_name, strerror(errno) );
606   register_secured_file (db_name);
607
608   /* check whether we need to do a version migration */
609   do
610     n = read (db_fd, buf, 5);
611   while (n==-1 && errno == EINTR);
612   if (n == 5 && !memcmp (buf, "\x01gpg\x02", 5))
613     {
614       migrate_from_v2 ();
615     }
616   
617   /* read the version record */
618   if (tdbio_read_record (0, &rec, RECTYPE_VER ) )
619     log_fatal( _("%s: invalid trustdb\n"), db_name );
620 }
621
622
623 /****************
624  * Make a hashtable: type 0 = trust hash
625  */
626 static void
627 create_hashtable( TRUSTREC *vr, int type )
628 {
629     TRUSTREC rec;
630     off_t offset;
631     ulong recnum;
632     int i, n, rc;
633
634     offset = lseek( db_fd, 0, SEEK_END );
635     if( offset == -1 )
636         log_fatal("trustdb: lseek to end failed: %s\n", strerror(errno) );
637     recnum = offset / TRUST_RECORD_LEN;
638     assert(recnum); /* this is will never be the first record */
639
640     if( !type )
641         vr->r.ver.trusthashtbl = recnum;
642
643     /* Now write the records */
644     n = (256+ITEMS_PER_HTBL_RECORD-1) / ITEMS_PER_HTBL_RECORD;
645     for(i=0; i < n; i++, recnum++ ) {
646          memset( &rec, 0, sizeof rec );
647          rec.rectype = RECTYPE_HTBL;
648          rec.recnum = recnum;
649          rc = tdbio_write_record( &rec );
650          if( rc )
651              log_fatal( _("%s: failed to create hashtable: %s\n"),
652                                         db_name, g10_errstr(rc));
653     }
654     /* update the version record */
655     rc = tdbio_write_record( vr );
656     if( !rc )
657         rc = tdbio_sync();
658     if( rc )
659         log_fatal( _("%s: error updating version record: %s\n"),
660                                                   db_name, g10_errstr(rc));
661 }
662
663
664 int
665 tdbio_db_matches_options()
666 {
667   static int yes_no = -1;
668
669   if( yes_no == -1 )
670     {
671       TRUSTREC vr;
672       int rc;
673
674       rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
675       if( rc )
676         log_fatal( _("%s: error reading version record: %s\n"),
677                    db_name, g10_errstr(rc) );
678
679       yes_no = vr.r.ver.marginals == opt.marginals_needed
680         && vr.r.ver.completes == opt.completes_needed
681         && vr.r.ver.cert_depth == opt.max_cert_depth
682         && vr.r.ver.trust_model == opt.trust_model;
683     }
684
685   return yes_no;
686 }
687
688 byte
689 tdbio_read_model(void)
690 {
691   TRUSTREC vr;
692   int rc;
693  
694   rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
695   if( rc )
696     log_fatal( _("%s: error reading version record: %s\n"),
697                db_name, g10_errstr(rc) );
698   return vr.r.ver.trust_model;
699 }
700
701 /****************
702  * Return the nextstamp value.
703  */
704 ulong
705 tdbio_read_nextcheck ()
706 {
707     TRUSTREC vr;
708     int rc;
709
710     rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
711     if( rc )
712         log_fatal( _("%s: error reading version record: %s\n"),
713                                                     db_name, g10_errstr(rc) );
714     return vr.r.ver.nextcheck;
715 }
716
717 /* Return true when the stamp was actually changed. */
718 int
719 tdbio_write_nextcheck (ulong stamp)
720 {
721     TRUSTREC vr;
722     int rc;
723
724     rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
725     if( rc )
726         log_fatal( _("%s: error reading version record: %s\n"),
727                                        db_name, g10_errstr(rc) );
728
729     if (vr.r.ver.nextcheck == stamp)
730       return 0;
731
732     vr.r.ver.nextcheck = stamp;
733     rc = tdbio_write_record( &vr );
734     if( rc )
735         log_fatal( _("%s: error writing version record: %s\n"),
736                                        db_name, g10_errstr(rc) );
737     return 1;
738 }
739
740
741
742 /****************
743  * Return the record number of the trusthash tbl or create a new one.
744  */
745 static ulong
746 get_trusthashrec(void)
747 {
748     static ulong trusthashtbl; /* record number of the trust hashtable */
749
750     if( !trusthashtbl ) {
751         TRUSTREC vr;
752         int rc;
753
754         rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
755         if( rc )
756             log_fatal( _("%s: error reading version record: %s\n"),
757                                             db_name, g10_errstr(rc) );
758         if( !vr.r.ver.trusthashtbl )
759             create_hashtable( &vr, 0 );
760
761         trusthashtbl = vr.r.ver.trusthashtbl;
762     }
763     return trusthashtbl;
764 }
765
766
767
768 /****************
769  * Update a hashtable.
770  * table gives the start of the table, key and keylen is the key,
771  * newrecnum is the record number to insert.
772  */
773 static int
774 upd_hashtable( ulong table, byte *key, int keylen, ulong newrecnum )
775 {
776     TRUSTREC lastrec, rec;
777     ulong hashrec, item;
778     int msb;
779     int level=0;
780     int rc, i;
781
782     hashrec = table;
783   next_level:
784     msb = key[level];
785     hashrec += msb / ITEMS_PER_HTBL_RECORD;
786     rc = tdbio_read_record( hashrec, &rec, RECTYPE_HTBL );
787     if( rc ) {
788         log_error("upd_hashtable: read failed: %s\n",   g10_errstr(rc) );
789         return rc;
790     }
791
792     item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
793     if( !item ) { /* insert a new item into the hash table */
794         rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = newrecnum;
795         rc = tdbio_write_record( &rec );
796         if( rc ) {
797             log_error("upd_hashtable: write htbl failed: %s\n",
798                                                             g10_errstr(rc) );
799             return rc;
800         }
801     }
802     else if( item != newrecnum ) {  /* must do an update */
803         lastrec = rec;
804         rc = tdbio_read_record( item, &rec, 0 );
805         if( rc ) {
806             log_error( "upd_hashtable: read item failed: %s\n",
807                                                             g10_errstr(rc) );
808             return rc;
809         }
810
811         if( rec.rectype == RECTYPE_HTBL ) {
812             hashrec = item;
813             level++;
814             if( level >= keylen ) {
815                 log_error( "hashtable has invalid indirections.\n");
816                 return G10ERR_TRUSTDB;
817             }
818             goto next_level;
819         }
820         else if( rec.rectype == RECTYPE_HLST ) { /* extend list */
821             /* see whether the key is already in this list */
822             for(;;) {
823                 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
824                     if( rec.r.hlst.rnum[i] == newrecnum ) {
825                         return 0; /* okay, already in the list */
826                     }
827                 }
828                 if( rec.r.hlst.next ) {
829                     rc = tdbio_read_record( rec.r.hlst.next,
830                                                        &rec, RECTYPE_HLST);
831                     if( rc ) {
832                         log_error( "upd_hashtable: read hlst failed: %s\n",
833                                                              g10_errstr(rc) );
834                         return rc;
835                     }
836                 }
837                 else
838                     break; /* not there */
839             }
840             /* find the next free entry and put it in */
841             for(;;) {
842                 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
843                     if( !rec.r.hlst.rnum[i] ) {
844                         rec.r.hlst.rnum[i] = newrecnum;
845                         rc = tdbio_write_record( &rec );
846                         if( rc )
847                             log_error( "upd_hashtable: write hlst failed: %s\n",
848                                                               g10_errstr(rc) );
849                         return rc; /* done */
850                     }
851                 }
852                 if( rec.r.hlst.next ) {
853                     rc = tdbio_read_record( rec.r.hlst.next,
854                                                       &rec, RECTYPE_HLST );
855                     if( rc ) {
856                         log_error( "upd_hashtable: read hlst failed: %s\n",
857                                                              g10_errstr(rc) );
858                         return rc;
859                     }
860                 }
861                 else { /* add a new list record */
862                     rec.r.hlst.next = item = tdbio_new_recnum();
863                     rc = tdbio_write_record( &rec );
864                     if( rc ) {
865                         log_error( "upd_hashtable: write hlst failed: %s\n",
866                                                           g10_errstr(rc) );
867                         return rc;
868                     }
869                     memset( &rec, 0, sizeof rec );
870                     rec.rectype = RECTYPE_HLST;
871                     rec.recnum = item;
872                     rec.r.hlst.rnum[0] = newrecnum;
873                     rc = tdbio_write_record( &rec );
874                     if( rc )
875                         log_error( "upd_hashtable: write ext hlst failed: %s\n",
876                                                           g10_errstr(rc) );
877                     return rc; /* done */
878                 }
879             } /* end loop over hlst slots */
880         }
881         else if( rec.rectype == RECTYPE_TRUST ) { /* insert a list record */
882             if( rec.recnum == newrecnum ) {
883                 return 0;
884             }
885             item = rec.recnum; /* save number of key record */
886             memset( &rec, 0, sizeof rec );
887             rec.rectype = RECTYPE_HLST;
888             rec.recnum = tdbio_new_recnum();
889             rec.r.hlst.rnum[0] = item;       /* old keyrecord */
890             rec.r.hlst.rnum[1] = newrecnum; /* and new one */
891             rc = tdbio_write_record( &rec );
892             if( rc ) {
893                 log_error( "upd_hashtable: write new hlst failed: %s\n",
894                                                   g10_errstr(rc) );
895                 return rc;
896             }
897             /* update the hashtable record */
898             lastrec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = rec.recnum;
899             rc = tdbio_write_record( &lastrec );
900             if( rc )
901                 log_error( "upd_hashtable: update htbl failed: %s\n",
902                                                              g10_errstr(rc) );
903             return rc; /* ready */
904         }
905         else {
906             log_error( "hashtbl %lu: %lu/%d points to an invalid record %lu\n",
907                        table, hashrec, (msb % ITEMS_PER_HTBL_RECORD), item);
908             list_trustdb(NULL);
909             return G10ERR_TRUSTDB;
910         }
911     }
912
913     return 0;
914 }
915
916
917 /****************
918  * Drop an entry from a hashtable
919  * table gives the start of the table, key and keylen is the key,
920  */
921 static int
922 drop_from_hashtable( ulong table, byte *key, int keylen, ulong recnum )
923 {
924     TRUSTREC rec;
925     ulong hashrec, item;
926     int msb;
927     int level=0;
928     int rc, i;
929
930     hashrec = table;
931   next_level:
932     msb = key[level];
933     hashrec += msb / ITEMS_PER_HTBL_RECORD;
934     rc = tdbio_read_record( hashrec, &rec, RECTYPE_HTBL );
935     if( rc ) {
936         log_error("drop_from_hashtable: read failed: %s\n",
937                                                         g10_errstr(rc) );
938         return rc;
939     }
940
941     item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
942     if( !item )  /* not found - forget about it  */
943         return 0;
944
945     if( item == recnum ) {  /* tables points direct to the record */
946         rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = 0;
947         rc = tdbio_write_record( &rec );
948         if( rc )
949             log_error("drop_from_hashtable: write htbl failed: %s\n",
950                                                             g10_errstr(rc) );
951         return rc;
952     }
953
954     rc = tdbio_read_record( item, &rec, 0 );
955     if( rc ) {
956         log_error( "drop_from_hashtable: read item failed: %s\n",
957                                                         g10_errstr(rc) );
958         return rc;
959     }
960
961     if( rec.rectype == RECTYPE_HTBL ) {
962         hashrec = item;
963         level++;
964         if( level >= keylen ) {
965             log_error( "hashtable has invalid indirections.\n");
966             return G10ERR_TRUSTDB;
967         }
968         goto next_level;
969     }
970
971     if( rec.rectype == RECTYPE_HLST ) {
972         for(;;) {
973             for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
974                 if( rec.r.hlst.rnum[i] == recnum ) {
975                     rec.r.hlst.rnum[i] = 0; /* drop */
976                     rc = tdbio_write_record( &rec );
977                     if( rc )
978                         log_error("drop_from_hashtable: write htbl failed: %s\n",
979                                                                         g10_errstr(rc) );
980                     return rc;
981                 }
982             }
983             if( rec.r.hlst.next ) {
984                 rc = tdbio_read_record( rec.r.hlst.next,
985                                                    &rec, RECTYPE_HLST);
986                 if( rc ) {
987                     log_error( "drop_from_hashtable: read hlst failed: %s\n",
988                                                          g10_errstr(rc) );
989                     return rc;
990                 }
991             }
992             else
993                 return 0; /* key not in table */
994         }
995     }
996
997     log_error( "hashtbl %lu: %lu/%d points to wrong record %lu\n",
998                     table, hashrec, (msb % ITEMS_PER_HTBL_RECORD), item);
999     return G10ERR_TRUSTDB;
1000 }
1001
1002
1003
1004 /****************
1005  * Lookup a record via the hashtable tablewith key/keylen and return the
1006  * result in rec.  cmp() should return if the record is the desired one.
1007  * Returns -1 if not found, 0 if found or another errocode
1008  */
1009 static int
1010 lookup_hashtable( ulong table, const byte *key, size_t keylen,
1011                   int (*cmpfnc)(void*, const TRUSTREC *), void *cmpdata,
1012                                                 TRUSTREC *rec )
1013 {
1014     int rc;
1015     ulong hashrec, item;
1016     int msb;
1017     int level=0;
1018
1019     hashrec = table;
1020   next_level:
1021     msb = key[level];
1022     hashrec += msb / ITEMS_PER_HTBL_RECORD;
1023     rc = tdbio_read_record( hashrec, rec, RECTYPE_HTBL );
1024     if( rc ) {
1025         log_error("lookup_hashtable failed: %s\n", g10_errstr(rc) );
1026         return rc;
1027     }
1028
1029     item = rec->r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
1030     if( !item )
1031         return -1; /* not found */
1032
1033     rc = tdbio_read_record( item, rec, 0 );
1034     if( rc ) {
1035         log_error( "hashtable read failed: %s\n", g10_errstr(rc) );
1036         return rc;
1037     }
1038     if( rec->rectype == RECTYPE_HTBL ) {
1039         hashrec = item;
1040         level++;
1041         if( level >= keylen ) {
1042             log_error("hashtable has invalid indirections\n");
1043             return G10ERR_TRUSTDB;
1044         }
1045         goto next_level;
1046     }
1047     else if( rec->rectype == RECTYPE_HLST ) {
1048         for(;;) {
1049             int i;
1050
1051             for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1052                 if( rec->r.hlst.rnum[i] ) {
1053                     TRUSTREC tmp;
1054
1055                     rc = tdbio_read_record( rec->r.hlst.rnum[i], &tmp, 0 );
1056                     if( rc ) {
1057                         log_error( "lookup_hashtable: read item failed: %s\n",
1058                                                               g10_errstr(rc) );
1059                         return rc;
1060                     }
1061                     if( (*cmpfnc)( cmpdata, &tmp ) ) {
1062                         *rec = tmp;
1063                         return 0;
1064                     }
1065                 }
1066             }
1067             if( rec->r.hlst.next ) {
1068                 rc = tdbio_read_record( rec->r.hlst.next, rec, RECTYPE_HLST );
1069                 if( rc ) {
1070                     log_error( "lookup_hashtable: read hlst failed: %s\n",
1071                                                          g10_errstr(rc) );
1072                     return rc;
1073                 }
1074             }
1075             else
1076                 return -1; /* not found */
1077         }
1078     }
1079
1080
1081     if( (*cmpfnc)( cmpdata, rec ) )
1082         return 0; /* really found */
1083
1084     return -1; /* no: not found */
1085 }
1086
1087
1088 /****************
1089  * Update the trust hashtbl or create the table if it does not exist
1090  */
1091 static int
1092 update_trusthashtbl( TRUSTREC *tr )
1093 {
1094     return upd_hashtable( get_trusthashrec(),
1095                           tr->r.trust.fingerprint, 20, tr->recnum );
1096 }
1097
1098
1099
1100 void
1101 tdbio_dump_record( TRUSTREC *rec, FILE *fp  )
1102 {
1103     int i;
1104     ulong rnum = rec->recnum;
1105
1106     fprintf(fp, "rec %5lu, ", rnum );
1107
1108     switch( rec->rectype ) {
1109       case 0: fprintf(fp, "blank\n");
1110         break;
1111       case RECTYPE_VER: fprintf(fp,
1112             "version, td=%lu, f=%lu, m/c/d=%d/%d/%d tm=%d nc=%lu (%s)\n",
1113                                    rec->r.ver.trusthashtbl,
1114                                    rec->r.ver.firstfree,
1115                                    rec->r.ver.marginals,
1116                                    rec->r.ver.completes,
1117                                    rec->r.ver.cert_depth,
1118                                    rec->r.ver.trust_model,
1119                                    rec->r.ver.nextcheck,
1120                                    strtimestamp(rec->r.ver.nextcheck)
1121                                  );
1122         break;
1123       case RECTYPE_FREE: fprintf(fp, "free, next=%lu\n", rec->r.free.next );
1124         break;
1125       case RECTYPE_HTBL:
1126         fprintf(fp, "htbl,");
1127         for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ )
1128             fprintf(fp, " %lu", rec->r.htbl.item[i] );
1129         putc('\n', fp);
1130         break;
1131       case RECTYPE_HLST:
1132         fprintf(fp, "hlst, next=%lu,", rec->r.hlst.next );
1133         for(i=0; i < ITEMS_PER_HLST_RECORD; i++ )
1134             fprintf(fp, " %lu", rec->r.hlst.rnum[i] );
1135         putc('\n', fp);
1136         break;
1137       case RECTYPE_TRUST:
1138         fprintf(fp, "trust ");
1139         for(i=0; i < 20; i++ )
1140             fprintf(fp, "%02X", rec->r.trust.fingerprint[i] );
1141         fprintf (fp, ", ot=%d, d=%d, vl=%lu\n", rec->r.trust.ownertrust,
1142                  rec->r.trust.depth, rec->r.trust.validlist);
1143         break;
1144       case RECTYPE_VALID:
1145         fprintf(fp, "valid ");
1146         for(i=0; i < 20; i++ )
1147             fprintf(fp, "%02X", rec->r.valid.namehash[i] );
1148         fprintf (fp, ", v=%d, next=%lu\n", rec->r.valid.validity,
1149                  rec->r.valid.next);
1150         break;
1151       default:
1152         fprintf(fp, "unknown type %d\n", rec->rectype );
1153         break;
1154     }
1155 }
1156
1157 /****************
1158  * read the record with number recnum
1159  * returns: -1 on error, 0 on success
1160  */
1161 int
1162 tdbio_read_record( ulong recnum, TRUSTREC *rec, int expected )
1163 {
1164     byte readbuf[TRUST_RECORD_LEN];
1165     const byte *buf, *p;
1166     int rc = 0;
1167     int n, i;
1168
1169     if( db_fd == -1 )
1170         open_db();
1171     buf = get_record_from_cache( recnum );
1172     if( !buf ) {
1173         if( lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
1174             log_error(_("trustdb: lseek failed: %s\n"), strerror(errno) );
1175             return G10ERR_READ_FILE;
1176         }
1177         n = read( db_fd, readbuf, TRUST_RECORD_LEN);
1178         if( !n ) {
1179             return -1; /* eof */
1180         }
1181         else if( n != TRUST_RECORD_LEN ) {
1182             log_error(_("trustdb: read failed (n=%d): %s\n"), n,
1183                                                         strerror(errno) );
1184             return G10ERR_READ_FILE;
1185         }
1186         buf = readbuf;
1187     }
1188     rec->recnum = recnum;
1189     rec->dirty = 0;
1190     p = buf;
1191     rec->rectype = *p++;
1192     if( expected && rec->rectype != expected ) {
1193         log_error("%lu: read expected rec type %d, got %d\n",
1194                     recnum, expected, rec->rectype );
1195         return G10ERR_TRUSTDB;
1196     }
1197     p++;    /* skip reserved byte */
1198     switch( rec->rectype ) {
1199       case 0:  /* unused (free) record */
1200         break;
1201       case RECTYPE_VER: /* version record */
1202         if( memcmp(buf+1, "gpg", 3 ) ) {
1203             log_error( _("%s: not a trustdb file\n"), db_name );
1204             rc = G10ERR_TRUSTDB;
1205         }
1206         p += 2; /* skip "gpg" */
1207         rec->r.ver.version  = *p++;
1208         rec->r.ver.marginals = *p++;
1209         rec->r.ver.completes = *p++;
1210         rec->r.ver.cert_depth = *p++;
1211         rec->r.ver.trust_model = *p++;
1212         p += 3;
1213         rec->r.ver.created  = buftoulong(p); p += 4;
1214         rec->r.ver.nextcheck = buftoulong(p); p += 4;
1215         p += 4;
1216         p += 4;
1217         rec->r.ver.firstfree =buftoulong(p); p += 4;
1218         p += 4;
1219         rec->r.ver.trusthashtbl =buftoulong(p); p += 4;
1220         if( recnum ) {
1221             log_error( _("%s: version record with recnum %lu\n"), db_name,
1222                                                              (ulong)recnum );
1223             rc = G10ERR_TRUSTDB;
1224         }
1225         else if( rec->r.ver.version != 3 ) {
1226             log_error( _("%s: invalid file version %d\n"), db_name,
1227                                                         rec->r.ver.version );
1228             rc = G10ERR_TRUSTDB;
1229         }
1230         break;
1231       case RECTYPE_FREE:
1232         rec->r.free.next  = buftoulong(p); p += 4;
1233         break;
1234       case RECTYPE_HTBL:
1235         for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
1236             rec->r.htbl.item[i] = buftoulong(p); p += 4;
1237         }
1238         break;
1239       case RECTYPE_HLST:
1240         rec->r.hlst.next = buftoulong(p); p += 4;
1241         for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1242             rec->r.hlst.rnum[i] = buftoulong(p); p += 4;
1243         }
1244         break;
1245       case RECTYPE_TRUST:
1246         memcpy( rec->r.trust.fingerprint, p, 20); p+=20;
1247         rec->r.trust.ownertrust = *p++;
1248         rec->r.trust.depth = *p++;
1249         rec->r.trust.min_ownertrust = *p++;
1250         p++;
1251         rec->r.trust.validlist = buftoulong(p); p += 4;
1252         break;
1253       case RECTYPE_VALID:
1254         memcpy( rec->r.valid.namehash, p, 20); p+=20;
1255         rec->r.valid.validity = *p++;
1256         rec->r.valid.next = buftoulong(p); p += 4;
1257         rec->r.valid.full_count = *p++;
1258         rec->r.valid.marginal_count = *p++;
1259         break;
1260       default:
1261         log_error( "%s: invalid record type %d at recnum %lu\n",
1262                                    db_name, rec->rectype, (ulong)recnum );
1263         rc = G10ERR_TRUSTDB;
1264         break;
1265     }
1266
1267     return rc;
1268 }
1269
1270 /****************
1271  * Write the record at RECNUM
1272  */
1273 int
1274 tdbio_write_record( TRUSTREC *rec )
1275 {
1276     byte buf[TRUST_RECORD_LEN], *p;
1277     int rc = 0;
1278     int i;
1279     ulong recnum = rec->recnum;
1280
1281     if( db_fd == -1 )
1282         open_db();
1283
1284     memset(buf, 0, TRUST_RECORD_LEN);
1285     p = buf;
1286     *p++ = rec->rectype; p++;
1287     switch( rec->rectype ) {
1288       case 0:  /* unused record */
1289         break;
1290       case RECTYPE_VER: /* version record */
1291         if( recnum )
1292             BUG();
1293         memcpy(p-1, "gpg", 3 ); p += 2;
1294         *p++ = rec->r.ver.version;
1295         *p++ = rec->r.ver.marginals;
1296         *p++ = rec->r.ver.completes;
1297         *p++ = rec->r.ver.cert_depth;
1298         *p++ = rec->r.ver.trust_model;
1299         p += 3;
1300         ulongtobuf(p, rec->r.ver.created); p += 4;
1301         ulongtobuf(p, rec->r.ver.nextcheck); p += 4;
1302         p += 4;
1303         p += 4;
1304         ulongtobuf(p, rec->r.ver.firstfree ); p += 4;
1305         p += 4;
1306         ulongtobuf(p, rec->r.ver.trusthashtbl ); p += 4;
1307         break;
1308
1309       case RECTYPE_FREE:
1310         ulongtobuf(p, rec->r.free.next); p += 4;
1311         break;
1312
1313
1314       case RECTYPE_HTBL:
1315         for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
1316             ulongtobuf( p, rec->r.htbl.item[i]); p += 4;
1317         }
1318         break;
1319
1320       case RECTYPE_HLST:
1321         ulongtobuf( p, rec->r.hlst.next); p += 4;
1322         for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1323             ulongtobuf( p, rec->r.hlst.rnum[i]); p += 4;
1324         }
1325         break;
1326
1327       case RECTYPE_TRUST:
1328         memcpy( p, rec->r.trust.fingerprint, 20); p += 20;
1329         *p++ = rec->r.trust.ownertrust;
1330         *p++ = rec->r.trust.depth;
1331         *p++ = rec->r.trust.min_ownertrust;
1332         p++;
1333         ulongtobuf( p, rec->r.trust.validlist); p += 4;
1334         break;
1335
1336       case RECTYPE_VALID:
1337         memcpy( p, rec->r.valid.namehash, 20); p += 20;
1338         *p++ = rec->r.valid.validity;
1339         ulongtobuf( p, rec->r.valid.next); p += 4;
1340         *p++ = rec->r.valid.full_count;
1341         *p++ = rec->r.valid.marginal_count;
1342         break;
1343
1344       default:
1345         BUG();
1346     }
1347
1348     rc = put_record_into_cache( recnum, buf );
1349     if( rc )
1350         ;
1351     else if( rec->rectype == RECTYPE_TRUST )
1352         rc = update_trusthashtbl( rec );
1353
1354     return rc;
1355 }
1356
1357 int
1358 tdbio_delete_record( ulong recnum )
1359 {
1360     TRUSTREC vr, rec;
1361     int rc;
1362
1363     /* Must read the record fist, so we can drop it from the hash tables */
1364     rc = tdbio_read_record( recnum, &rec, 0 );
1365     if( rc )
1366         ;
1367     else if( rec.rectype == RECTYPE_TRUST ) {
1368          rc = drop_from_hashtable( get_trusthashrec(),
1369                                    rec.r.trust.fingerprint, 20, rec.recnum );
1370     }
1371
1372     if( rc )
1373         return rc;
1374
1375     /* now we can chnage it to a free record */
1376     rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
1377     if( rc )
1378         log_fatal( _("%s: error reading version record: %s\n"),
1379                                        db_name, g10_errstr(rc) );
1380
1381     rec.recnum = recnum;
1382     rec.rectype = RECTYPE_FREE;
1383     rec.r.free.next = vr.r.ver.firstfree;
1384     vr.r.ver.firstfree = recnum;
1385     rc = tdbio_write_record( &rec );
1386     if( !rc )
1387         rc = tdbio_write_record( &vr );
1388     return rc;
1389 }
1390
1391 /****************
1392  * create a new record and return its record number
1393  */
1394 ulong
1395 tdbio_new_recnum()
1396 {
1397     off_t offset;
1398     ulong recnum;
1399     TRUSTREC vr, rec;
1400     int rc;
1401
1402     /* look for unused records */
1403     rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
1404     if( rc )
1405         log_fatal( _("%s: error reading version record: %s\n"),
1406                                              db_name, g10_errstr(rc) );
1407     if( vr.r.ver.firstfree ) {
1408         recnum = vr.r.ver.firstfree;
1409         rc = tdbio_read_record( recnum, &rec, RECTYPE_FREE );
1410         if( rc ) {
1411             log_error( _("%s: error reading free record: %s\n"),
1412                                                   db_name,  g10_errstr(rc) );
1413             return rc;
1414         }
1415         /* update dir record */
1416         vr.r.ver.firstfree = rec.r.free.next;
1417         rc = tdbio_write_record( &vr );
1418         if( rc ) {
1419             log_error( _("%s: error writing dir record: %s\n"),
1420                                                      db_name, g10_errstr(rc) );
1421             return rc;
1422         }
1423         /*zero out the new record */
1424         memset( &rec, 0, sizeof rec );
1425         rec.rectype = 0; /* unused record */
1426         rec.recnum = recnum;
1427         rc = tdbio_write_record( &rec );
1428         if( rc )
1429             log_fatal(_("%s: failed to zero a record: %s\n"),
1430                                        db_name, g10_errstr(rc));
1431     }
1432     else { /* not found, append a new record */
1433         offset = lseek( db_fd, 0, SEEK_END );
1434         if( offset == -1 )
1435             log_fatal("trustdb: lseek to end failed: %s\n", strerror(errno) );
1436         recnum = offset / TRUST_RECORD_LEN;
1437         assert(recnum); /* this is will never be the first record */
1438         /* we must write a record, so that the next call to this function
1439          * returns another recnum */
1440         memset( &rec, 0, sizeof rec );
1441         rec.rectype = 0; /* unused record */
1442         rec.recnum = recnum;
1443         rc = 0;
1444         if( lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
1445             log_error(_("trustdb rec %lu: lseek failed: %s\n"),
1446                                                 recnum, strerror(errno) );
1447             rc = G10ERR_WRITE_FILE;
1448         }
1449         else {
1450             int n = write( db_fd, &rec, TRUST_RECORD_LEN);
1451             if( n != TRUST_RECORD_LEN ) {
1452                 log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
1453                                                  recnum, n, strerror(errno) );
1454                 rc = G10ERR_WRITE_FILE;
1455             }
1456         }
1457
1458         if( rc )
1459             log_fatal(_("%s: failed to append a record: %s\n"),
1460                                     db_name,    g10_errstr(rc));
1461     }
1462     return recnum ;
1463 }
1464
1465
1466
1467 static int
1468 cmp_trec_fpr ( void *fpr, const TRUSTREC *rec )
1469 {
1470     return rec->rectype == RECTYPE_TRUST
1471            && !memcmp( rec->r.trust.fingerprint, fpr, 20);
1472 }
1473
1474
1475 int
1476 tdbio_search_trust_byfpr( const byte *fingerprint, TRUSTREC *rec )
1477 {
1478     int rc;
1479
1480     /* locate the trust record using the hash table */
1481     rc = lookup_hashtable( get_trusthashrec(), fingerprint, 20,
1482                            cmp_trec_fpr, (void*)fingerprint, rec );
1483     return rc;
1484 }
1485
1486 int
1487 tdbio_search_trust_bypk (PKT_public_key *pk, TRUSTREC *rec)
1488 {
1489     byte fingerprint[MAX_FINGERPRINT_LEN];
1490     size_t fingerlen;
1491
1492     fingerprint_from_pk( pk, fingerprint, &fingerlen );
1493     for (; fingerlen < 20; fingerlen++ )
1494       fingerprint[fingerlen] = 0;
1495     return tdbio_search_trust_byfpr (fingerprint, rec);
1496 }
1497
1498
1499
1500 void
1501 tdbio_invalid(void)
1502 {
1503     log_error(_(
1504         "the trustdb is corrupted; please run \"gpg --fix-trustdb\".\n") );
1505     g10_exit(2);
1506 }
1507
1508 /*
1509  * Migrate the trustdb as just up to gpg 1.0.6 (trustdb version 2)
1510  * to the 2.1 version as used with 1.0.6b - This is pretty trivial as needs
1511  * only to scan the tdb and insert new the new trust records.  The old ones are
1512  * obsolte from now on
1513  */
1514 static void
1515 migrate_from_v2 ()
1516 {
1517   TRUSTREC rec;
1518   int i, n;
1519   struct {
1520     ulong keyrecno;
1521     byte  ot;
1522     byte okay;
1523     byte  fpr[20];
1524   } *ottable;
1525   int ottable_size, ottable_used;
1526   byte oldbuf[40];
1527   ulong recno;
1528   int rc, count;
1529
1530   ottable_size = 5;
1531   ottable = xmalloc (ottable_size * sizeof *ottable);
1532   ottable_used = 0;
1533
1534   /* We have some restrictions here.  We can't use the version record
1535    * and we can't use any of the old hashtables because we dropped the
1536    * code.  So we first collect all ownertrusts and then use a second
1537    * pass fo find the associated keys.  We have to do this all without using 
1538    * the regular record read functions.
1539    */
1540
1541   /* get all the ownertrusts */
1542   if (lseek (db_fd, 0, SEEK_SET ) == -1 ) 
1543       log_fatal ("migrate_from_v2: lseek failed: %s\n", strerror (errno));
1544   for (recno=0;;recno++)
1545     {
1546       do
1547         n = read (db_fd, oldbuf, 40);
1548       while (n==-1 && errno == EINTR);
1549       if (!n)
1550         break; /* eof */
1551       if (n != 40)
1552         log_fatal ("migrate_vfrom_v2: read error or short read\n");
1553
1554       if (*oldbuf != 2)
1555         continue;
1556       
1557       /* v2 dir record */
1558       if (ottable_used == ottable_size)
1559         {
1560           ottable_size += 1000;
1561           ottable = xrealloc (ottable, ottable_size * sizeof *ottable);
1562         }
1563       ottable[ottable_used].keyrecno = buftoulong (oldbuf+6);
1564       ottable[ottable_used].ot = oldbuf[18];
1565       ottable[ottable_used].okay = 0;
1566       memset (ottable[ottable_used].fpr,0, 20);
1567       if (ottable[ottable_used].keyrecno && ottable[ottable_used].ot)
1568         ottable_used++;
1569     }
1570   log_info ("found %d ownertrust records\n", ottable_used);
1571
1572   /* Read again and find the fingerprints */
1573   if (lseek (db_fd, 0, SEEK_SET ) == -1 ) 
1574       log_fatal ("migrate_from_v2: lseek failed: %s\n", strerror (errno));
1575   for (recno=0;;recno++)
1576     {
1577       do
1578         n = read (db_fd, oldbuf, 40);
1579       while (n==-1 && errno == EINTR);
1580       if (!n)
1581         break; /* eof */
1582       if (n != 40)
1583         log_fatal ("migrate_from_v2: read error or short read\n");
1584
1585       if (*oldbuf != 3) 
1586         continue;
1587
1588       /* v2 key record */
1589       for (i=0; i < ottable_used; i++)
1590         {
1591           if (ottable[i].keyrecno == recno)
1592             {
1593               memcpy (ottable[i].fpr, oldbuf+20, 20);
1594               ottable[i].okay = 1;
1595               break;
1596             }
1597         }
1598     }
1599
1600   /* got everything - create the v3 trustdb */
1601   if (ftruncate (db_fd, 0))
1602     log_fatal ("can't truncate `%s': %s\n", db_name, strerror (errno) );
1603   if (create_version_record ())
1604     log_fatal ("failed to recreate version record of `%s'\n", db_name);
1605
1606   /* access the hash table, so it is store just after the version record, 
1607    * this is not needed put a dump is more pretty */
1608   get_trusthashrec ();
1609
1610   /* And insert the old ownertrust values */
1611   count = 0;
1612   for (i=0; i < ottable_used; i++)
1613     {
1614       if (!ottable[i].okay)
1615         continue;
1616       
1617       memset (&rec, 0, sizeof rec);
1618       rec.recnum = tdbio_new_recnum ();
1619       rec.rectype = RECTYPE_TRUST;
1620       memcpy(rec.r.trust.fingerprint, ottable[i].fpr, 20);
1621       rec.r.trust.ownertrust = ottable[i].ot;
1622       if (tdbio_write_record (&rec))
1623         log_fatal ("failed to write trust record of `%s'\n", db_name);
1624       count++;
1625     }
1626
1627   revalidation_mark ();
1628   rc = tdbio_sync ();
1629   if (rc)
1630     log_fatal ("failed to sync `%s'\n", db_name);
1631   log_info ("migrated %d version 2 ownertrusts\n", count);
1632   xfree (ottable);
1633 }