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