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