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