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