summaryrefslogtreecommitdiffstats
path: root/g10/tdbio.c
blob: 11b2dcf25caf62153e2555e5c7411373d4cc467e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
/* tdbio.c
 *	Copyright (C) 1998 Free Software Foundation, Inc.
 *
 * This file is part of GNUPG.
 *
 * GNUPG is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GNUPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "errors.h"
#include "iobuf.h"
#include "memory.h"
#include "util.h"
#include "options.h"
#include "main.h"
#include "i18n.h"
#include "trustdb.h"
#include "tdbio.h"


/****************
 * Yes, this is a very simple implementation. We should really
 * use a page aligned buffer and read complete pages.
 * To implement a simple trannsaction system, this is sufficient.
 */
typedef struct cache_ctrl_struct *CACHE_CTRL;
struct cache_ctrl_struct {
    CACHE_CTRL next;
    struct {
	unsigned used:1;
	unsigned dirty:1;
    } flags;
    ulong recno;
    char data[TRUST_RECORD_LEN];
};

#define MAX_CACHE_ENTRIES_SOFT	200   /* may be increased while in a */
#define MAX_CACHE_ENTRIES_HARD	1000  /* transaction to this one */
static CACHE_CTRL cache_list;
static int cache_entries;
static int cache_is_dirty;

/* a type used to pass infomation to cmp_krec_fpr */
struct cmp_krec_fpr_struct {
    int pubkey_algo;
    const char *fpr;
    int fprlen;
};

/* a type used to pass infomation to cmp_sdir */
struct cmp_sdir_struct {
    int pubkey_algo;
    u32 keyid[2];
};


static char *db_name;
static int  db_fd = -1;
static int in_transaction;


static void open_db(void);


/*************************************
 ************* record cache **********
 *************************************/

/****************
 * Get the data from therecord cache and return a
 * pointer into that cache.  Caller should copy
 * the return data.  NULL is returned on a cache miss.
 */
static const char *
get_record_from_cache( ulong recno )
{
    CACHE_CTRL r;

    for( r = cache_list; r; r = r->next ) {
	if( r->flags.used && r->recno == recno )
	    return r->data;
    }
    return NULL;
}


static int
write_cache_item( CACHE_CTRL r )
{
    int n;

    if( lseek( db_fd, r->recno * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
	log_error(_("trustdb rec %lu: lseek failed: %s\n"),
					    r->recno, strerror(errno) );
	return G10ERR_WRITE_FILE;
    }
    n = write( db_fd, r->data, TRUST_RECORD_LEN);
    if( n != TRUST_RECORD_LEN ) {
	log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
					    r->recno, n, strerror(errno) );
	return G10ERR_WRITE_FILE;
    }
    r->flags.dirty = 0;
    return 0;
}

/****************
 * Put data into the cache.  This function may flush the
 * some cache entries if there is not enough space available.
 */
int
put_record_into_cache( ulong recno, const char *data )
{
    CACHE_CTRL r, unused;
    int dirty_count = 0;
    int clean_count = 0;

    /* see whether we already cached this one */
    for( unused = NULL, r = cache_list; r; r = r->next ) {
	if( !r->flags.used ) {
	    if( !unused )
		unused = r;
	}
	else if( r->recno == recno ) {
	    if( !r->flags.dirty ) {
		/* Hmmm: should we use a a copy and compare? */
		if( memcmp(r->data, data, TRUST_RECORD_LEN ) ) {
		    r->flags.dirty = 1;
		    cache_is_dirty = 1;
		}
	    }
	    memcpy( r->data, data, TRUST_RECORD_LEN );
	    return 0;
	}
	if( r->flags.used ) {
	    if( r->flags.dirty )
		dirty_count++;
	    else
		clean_count++;
	}
    }
    /* not in the cache: add a new entry */
    if( unused ) { /* reuse this entry */
	r = unused;
	r->flags.used = 1;
	r->recno = recno;
	memcpy( r->data, data, TRUST_RECORD_LEN );
	r->flags.dirty = 1;
	cache_is_dirty = 1;
	cache_entries++;
	return 0;
    }
    /* see whether we reached the limit */
    if( cache_entries < MAX_CACHE_ENTRIES_SOFT ) { /* no */
	r = m_alloc( sizeof *r );
	r->flags.used = 1;
	r->recno = recno;
	memcpy( r->data, data, TRUST_RECORD_LEN );
	r->flags.dirty = 1;
	r->next = cache_list;
	cache_list = r;
	cache_is_dirty = 1;
	cache_entries++;
	return 0;
    }
    /* cache is full: discard some clean entries */
    if( clean_count ) {
	int n = clean_count / 3; /* discard a third of the clean entries */
	if( !n )
	    n = 1;
	for( unused = NULL, r = cache_list; r; r = r->next ) {
	    if( r->flags.used && !r->flags.dirty ) {
		if( !unused )
		    unused = r;
		r->flags.used = 0;
		cache_entries--;
		if( !--n )
		    break;
	    }
	}
	assert( unused );
	r = unused;
	r->flags.used = 1;
	r->recno = recno;
	memcpy( r->data, data, TRUST_RECORD_LEN );
	r->flags.dirty = 1;
	cache_is_dirty = 1;
	cache_entries++;
	return 0;
    }
    /* no clean entries: have to flush some dirty entries */
    if( in_transaction ) {
	/* but we can't do this while in a transaction
	 * we increase the cache size instead */
	if( cache_entries < MAX_CACHE_ENTRIES_HARD ) { /* no */
	    if( opt.debug && !(cache_entries % 100) )
		log_debug("increasing tdbio cache size\n");
	    r = m_alloc( sizeof *r );
	    r->flags.used = 1;
	    r->recno = recno;
	    memcpy( r->data, data, TRUST_RECORD_LEN );
	    r->flags.dirty = 1;
	    r->next = cache_list;
	    cache_list = r;
	    cache_is_dirty = 1;
	    cache_entries++;
	    return 0;
	}
	log_info(_("trustdb transaction to large\n"));
	return G10ERR_RESOURCE_LIMIT;
    }
    if( dirty_count ) {
	int n = dirty_count / 5; /* discard some dirty entries */
	if( !n )
	    n = 1;
	for( unused = NULL, r = cache_list; r; r = r->next ) {
	    if( r->flags.used && r->flags.dirty ) {
		int rc = write_cache_item( r );
		if( rc )
		    return rc;
		if( !unused )
		    unused = r;
		r->flags.used = 0;
		cache_entries--;
		if( !--n )
		    break;
	    }
	}
	assert( unused );
	r = unused;
	r->flags.used = 1;
	r->recno = recno;
	memcpy( r->data, data, TRUST_RECORD_LEN );
	r->flags.dirty = 1;
	cache_is_dirty = 1;
	cache_entries++;
	return 0;
    }
    BUG();
}


int
tdbio_is_dirty()
{
    return cache_is_dirty;
}


/****************
 * Flush the cache.  This cannot be used while in a transaction.
 */
int
tdbio_sync()
{
    CACHE_CTRL r;

    if( in_transaction )
	log_bug("tdbio: syncing while in transaction\n");

    if( !cache_is_dirty )
	return 0;

    for( r = cache_list; r; r = r->next ) {
	if( r->flags.used && r->flags.dirty ) {
	    int rc = write_cache_item( r );
	    if( rc )
		return rc;
	}
    }
    cache_is_dirty = 0;
    return 0;
}



/****************
 * Simple transactions system:
 * Everything between begin_transaction and end/cancel_transaction
 * is not immediatly written but at the time of end_transaction.
 *
 */
int
tdbio_begin_transaction()
{
    int rc;

    if( in_transaction )
	log_bug("tdbio: nested transactions\n");
    /* flush everything out */
    rc = tdbio_sync();
    if( rc )
	return rc;
    in_transaction = 1;
    return 0;
}

int
tdbio_end_transaction()
{
    int rc;

    if( !in_transaction )
	log_bug("tdbio: no active transaction\n");
    block_all_signals();
    in_transaction = 0;
    rc = tdbio_sync();
    unblock_all_signals();
    return rc;
}

int
tdbio_cancel_transaction()
{
    CACHE_CTRL r;

    if( !in_transaction )
	log_bug("tdbio: no active transaction\n");

    /* remove all dirty marked entries, so that the original ones
     * are read back the next time */
    if( cache_is_dirty ) {
	for( r = cache_list; r; r = r->next ) {
	    if( r->flags.used && r->flags.dirty ) {
		r->flags.used = 0;
		cache_entries--;
	    }
	}
	cache_is_dirty = 0;
    }

    in_transaction = 0;
    return 0;
}



/********************************************************
 **************** cached I/O functions ******************
 ********************************************************/

int
tdbio_set_dbname( const char *new_dbname, int create )
{
    char *fname;

    fname = new_dbname? m_strdup( new_dbname )
		      : make_filename(opt.homedir, "trustdb.gpg", NULL );

    if( access( fname, R_OK ) ) {
	if( errno != ENOENT ) {
	    log_error( _("%s: can't access: %s\n"), fname, strerror(errno) );
	    m_free(fname);
	    return G10ERR_TRUSTDB;
	}
	if( create ) {
	    FILE *fp;
	    TRUSTREC rec;
	    int rc;
	    char *p = strrchr( fname, '/' );

	    assert(p);
	    *p = 0;
	    if( access( fname, F_OK ) ) {
		if( strlen(fname) >= 7
		    && !strcmp(fname+strlen(fname)-7, "/.gnupg" ) ) {
		  #if __MINGW32__
		    if( mkdir( fname ) )
		  #else
		    if( mkdir( fname, S_IRUSR|S_IWUSR|S_IXUSR ) )
		  #endif
			log_fatal( _("%s: can't create directory: %s\n"),
						    fname,  strerror(errno) );
		    else
			log_info( _("%s: directory created\n"), fname );
		    copy_options_file( fname );
		}
		else
		    log_fatal( _("%s: directory does not exist!\n"), fname );
	    }
	    *p = '/';

	    fp =fopen( fname, "wb" );
	    if( !fp )
		log_fatal( _("%s: can't create: %s\n"), fname, strerror(errno) );
	    fclose(fp);
	    m_free(db_name);
	    db_name = fname;
	  #ifdef __MINGW32__
	    db_fd = open( db_name, O_RDWR | O_BINARY );
	  #else
	    db_fd = open( db_name, O_RDWR );
	  #endif
	    if( db_fd == -1 )
		log_fatal( _("%s: can't open: %s\n"), db_name, strerror(errno) );

	    memset( &rec, 0, sizeof rec );
	    rec.r.ver.version = 2;
	    rec.r.ver.created = make_timestamp();
	    rec.rectype = RECTYPE_VER;
	    rec.recnum = 0;
	    rc = tdbio_write_record( &rec );
	    if( !rc )
		tdbio_sync();
	    if( rc )
		log_fatal( _("%s: failed to create version record: %s"),
						   fname, g10_errstr(rc));
	    /* and read again to check that we are okay */
	    if( tdbio_read_record( 0, &rec, RECTYPE_VER ) )
		log_fatal( _("%s: invalid trust-db created\n"), db_name );

	    log_info(_("%s: trust-db created\n"), db_name);

	    return 0;
	}
    }
    m_free(db_name);
    db_name = fname;
    return 0;
}


const char *
tdbio_get_dbname()
{
    return db_name;
}



static void
open_db()
{
    TRUSTREC rec;
    assert( db_fd == -1 );

  #ifdef __MINGW32__
    db_fd = open( db_name, O_RDWR | O_BINARY );
  #else
    db_fd = open( db_name, O_RDWR );
  #endif
    if( db_fd == -1 )
	log_fatal( _("%s: can't open: %s\n"), db_name, strerror(errno) );
    if( tdbio_read_record( 0, &rec, RECTYPE_VER ) )
	log_fatal( _("%s: invalid trust-db\n"), db_name );
    /* fixme: check ->locked and other stuff */
}


/****************
 * Make a hashtable: type 0 = key hash, 1 = sdir hash
 */
static void
create_hashtable( TRUSTREC *vr, int type )
{
    TRUSTREC rec;
    off_t offset;
    ulong recnum;
    int i, n, rc;

    offset = lseek( db_fd, 0, SEEK_END );
    if( offset == -1 )
	log_fatal("trustdb: lseek to end failed: %s\n", strerror(errno) );
    recnum = offset / TRUST_RECORD_LEN;
    assert(recnum); /* this is will never be the first record */

    if( !type )
	vr->r.ver.keyhashtbl = recnum;
    else
	vr->r.ver.sdirhashtbl = recnum;
    /* Now write the records */
    n = (256+ITEMS_PER_HTBL_RECORD-1) / ITEMS_PER_HTBL_RECORD;
    for(i=0; i < n; i++, recnum++ ) {
	 memset( &rec, 0, sizeof rec );
	 rec.rectype = RECTYPE_HTBL;
	 rec.recnum = recnum;
	 rc = tdbio_write_record( &rec );
	 if( rc )
	     log_fatal( _("%s: failed to create hashtable: %s\n"),
					db_name, g10_errstr(rc));
    }
    /* update the version record */
    rc = tdbio_write_record( vr );
    if( !rc )
	rc = tdbio_sync();
    if( rc )
	log_fatal( _("%s: error updating version record: %s\n"),
						  db_name, g10_errstr(rc));
}



/****************
 * Return the record number of the keyhash tbl or create a new one.
 */
static ulong
get_keyhashrec()
{
    static ulong keyhashtbl; /* record number of the key hashtable */

    if( !keyhashtbl ) {
	TRUSTREC vr;
	int rc;

	rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
	if( rc )
	    log_fatal( _("%s: error reading version record: %s\n"),
					    db_name, g10_errstr(rc) );
	if( !vr.r.ver.keyhashtbl )
	    create_hashtable( &vr, 0 );

	keyhashtbl = vr.r.ver.keyhashtbl;
    }
    return keyhashtbl;
}

/****************
 * Return the record number of the shadow direcory hash table
 * or create a new one.
 */
static ulong
get_sdirhashrec()
{
    static ulong sdirhashtbl; /* record number of the hashtable */

    if( !sdirhashtbl ) {
	TRUSTREC vr;
	int rc;

	rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
	if( rc )
	    log_fatal( _("%s: error reading version record: %s\n"),
						    db_name, g10_errstr(rc) );
	if( !vr.r.ver.sdirhashtbl )
	    create_hashtable( &vr, 1 );

	sdirhashtbl = vr.r.ver.sdirhashtbl;
    }
    return sdirhashtbl;
}


/****************
 * Update a hashtable.
 * table gives the start of the table, key and keylen is the key,
 * newrecnum is the record number to insert.
 */
static int
upd_hashtable( ulong table, byte *key, int keylen, ulong newrecnum )
{
    TRUSTREC lastrec, rec;
    ulong hashrec, item;
    int msb;
    int level=0;
    int rc, i;

    hashrec = table;
  next_level:
    msb = key[level];
    hashrec += msb / ITEMS_PER_HTBL_RECORD;
    rc = tdbio_read_record( hashrec, &rec, RECTYPE_HTBL );
    if( rc ) {
	log_error( db_name, "upd_hashtable: read failed: %s\n",
							g10_errstr(rc) );
	return rc;
    }

    item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
    if( !item ) { /* insert a new item into the hash table */
	rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = newrecnum;
	rc = tdbio_write_record( &rec );
	if( rc ) {
	    log_error( db_name, "upd_hashtable: write htbl failed: %s\n",
							    g10_errstr(rc) );
	    return rc;
	}
    }
    else if( item != newrecnum ) {  /* must do an update */
	lastrec = rec;
	rc = tdbio_read_record( item, &rec, 0 );
	if( rc ) {
	    log_error( "upd_hashtable: read item failed: %s\n",
							    g10_errstr(rc) );
	    return rc;
	}

	if( rec.rectype == RECTYPE_HTBL ) {
	    hashrec = item;
	    level++;
	    if( level >= keylen ) {
		log_error( "hashtable has invalid indirections.\n");
		return G10ERR_TRUSTDB;
	    }
	    goto next_level;
	}
	else if( rec.rectype == RECTYPE_HLST ) { /* extend list */
	    /* see whether the key is already in this list */
	    for(;;) {
		for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
		    if( rec.r.hlst.rnum[i] == newrecnum ) {
			return 0; /* okay, already in the list */
		    }
		}
		if( rec.r.hlst.next ) {
		    rc = tdbio_read_record( rec.r.hlst.next,
						       &rec, RECTYPE_HLST);
		    if( rc ) {
			log_error( "scan keyhashtbl read hlst failed: %s\n",
							     g10_errstr(rc) );
			return rc;
		    }
		}
		else
		    break; /* not there */
	    }
	    /* find the next free entry and put it in */
	    for(;;) {
		for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
		    if( !rec.r.hlst.rnum[i] ) {
			rec.r.hlst.rnum[i] = newrecnum;
			rc = tdbio_write_record( &rec );
			if( rc )
			    log_error( "upd_hashtable: write hlst failed: %s\n",
							      g10_errstr(rc) );
			return rc; /* done */
		    }
		}
		if( rec.r.hlst.next ) {
		    rc = tdbio_read_record( rec.r.hlst.next,
						      &rec, RECTYPE_HLST );
		    if( rc ) {
			log_error( "upd_hashtable: read hlst failed: %s\n",
							     g10_errstr(rc) );
			return rc;
		    }
		}
		else { /* add a new list record */
		    rec.r.hlst.next = item = tdbio_new_recnum();
		    rc = tdbio_write_record( &rec );
		    if( rc ) {
			log_error( "upd_hashtable: write hlst failed: %s\n",
							  g10_errstr(rc) );
			return rc;
		    }
		    memset( &rec, 0, sizeof rec );
		    rec.rectype = RECTYPE_HLST;
		    rec.recnum = item;
		    rec.r.hlst.rnum[0] = newrecnum;
		    rc = tdbio_write_record( &rec );
		    if( rc )
			log_error( "upd_hashtable: write ext hlst failed: %s\n",
							  g10_errstr(rc) );
		    return rc; /* done */
		}
	    } /* end loop over hlst slots */
	}
	else if( rec.rectype == RECTYPE_KEY
		 || rec.rectype == RECTYPE_DIR
		 || rec.rectype == RECTYPE_SDIR ) { /* insert a list record */
	    if( rec.recnum == newrecnum ) {
		return 0;
	    }
	    item = rec.recnum; /* save number of key record */
	    memset( &rec, 0, sizeof rec );
	    rec.rectype = RECTYPE_HLST;
	    rec.recnum = tdbio_new_recnum();
	    rec.r.hlst.rnum[0] = item;	     /* old keyrecord */
	    rec.r.hlst.rnum[1] = newrecnum; /* and new one */
	    rc = tdbio_write_record( &rec );
	    if( rc ) {
		log_error( "upd_hashtable: write new hlst failed: %s\n",
						  g10_errstr(rc) );
		return rc;
	    }
	    /* update the hashtable record */
	    lastrec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = rec.recnum;
	    rc = tdbio_write_record( &lastrec );
	    if( rc )
		log_error( "upd_hashtable: update htbl failed: %s\n",
							     g10_errstr(rc) );
	    return rc; /* ready */
	}
	else {
	    log_error( "hashtbl %lu points to an invalid record\n",
								    item);
	    return G10ERR_TRUSTDB;
	}
    }

    return 0;
}



/****************
 * Lookup a record via the hashtable tablewith key/keylen and return the
 * result in rec.  cmp() should return if the record is the desired one.
 * Returns -1 if not found, 0 if found or another errocode
 */
static int
lookup_hashtable( ulong table, const byte *key, size_t keylen,
		  int (*cmpfnc)(void*, const TRUSTREC *), void *cmpdata,
						TRUSTREC *rec )
{
    int rc;
    ulong hashrec, item;
    int msb;
    int level=0;

    hashrec = table;
  next_level:
    msb = key[level];
    hashrec += msb / ITEMS_PER_HTBL_RECORD;
    rc = tdbio_read_record( hashrec, rec, RECTYPE_HTBL );
    if( rc ) {
	log_error( db_name, "lookup_hashtable failed: %s\n", g10_errstr(rc) );
	return rc;
    }

    item = rec->r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
    if( !item )
	return -1; /* not found */

    rc = tdbio_read_record( item, rec, 0 );
    if( rc ) {
	log_error( db_name, "hashtable read failed: %s\n", g10_errstr(rc) );
	return rc;
    }
    if( rec->rectype == RECTYPE_HTBL ) {
	hashrec = item;
	level++;
	if( level >= keylen ) {
	    log_error( db_name, "hashtable has invalid indirections\n");
	    return G10ERR_TRUSTDB;
	}
	goto next_level;
    }
    else if( rec->rectype == RECTYPE_HLST ) {
	for(;;) {
	    int i;

	    for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
		if( rec->r.hlst.rnum[i] ) {
		    TRUSTREC tmp;

		    rc = tdbio_read_record( rec->r.hlst.rnum[i], &tmp, 0 );
		    if( rc ) {
			log_error( "lookup_hashtable: read item failed: %s\n",
							      g10_errstr(rc) );
			return rc;
		    }
		    if( (*cmpfnc)( cmpdata, &tmp ) ) {
			*rec = tmp;
			return 0;
		    }
		}
	    }
	    if( rec->r.hlst.next ) {
		rc = tdbio_read_record( rec->r.hlst.next, rec, RECTYPE_HLST );
		if( rc ) {
		    log_error( "lookup_hashtable: read hlst failed: %s\n",
							 g10_errstr(rc) );
		    return rc;
		}
	    }
	    else
		return -1; /* not found */
	}
    }


    if( (*cmpfnc)( cmpdata, rec ) )
	return 0; /* really found */

    return -1; /* no: not found */
}




/****************
 * Update the key hashtbl or create the table if it does not exist
 */
static int
update_keyhashtbl( TRUSTREC *kr )
{
    return upd_hashtable( get_keyhashrec(),
			  kr->r.key.fingerprint,
			  kr->r.key.fingerprint_len, kr->recnum );
}

/****************
 * Update the shadow dir hashtbl or create the table if it does not exist
 */
static int
update_sdirhashtbl( TRUSTREC *sr )
{
    byte key[8];

    u32tobuf( key   , sr->r.sdir.keyid[0] );
    u32tobuf( key+4 , sr->r.sdir.keyid[1] );
    return upd_hashtable( get_sdirhashrec(), key, 8, sr->recnum );
}




void
tdbio_dump_record( TRUSTREC *rec, FILE *fp  )
{
    int i;
    ulong rnum = rec->recnum;
    byte *p;

    fprintf(fp, "rec %5lu, ", rnum );

    switch( rec->rectype ) {
      case 0: fprintf(fp, "blank\n");
	break;
      case RECTYPE_VER: fprintf(fp, "version, kd=%lu, sd=%lu, free=%lu\n",
	    rec->r.ver.keyhashtbl, rec->r.ver.sdirhashtbl,
				   rec->r.ver.firstfree );
	break;
      case RECTYPE_FREE: fprintf(fp, "free, next=%lu\n", rec->r.free.next );
	break;
      case RECTYPE_DIR:
	fprintf(fp, "dir %lu, keys=%lu, uids=%lu, cach=%lu, ot=%02x",
		    rec->r.dir.lid,
		    rec->r.dir.keylist,
		    rec->r.dir.uidlist,
		    rec->r.dir.cacherec,
		    rec->r.dir.ownertrust );
	if( rec->r.dir.dirflags & DIRF_CHECKED ) {
	    if( rec->r.dir.dirflags & DIRF_VALID )
		fputs(", valid", fp );
	    if( rec->r.dir.dirflags & DIRF_EXPIRED )
		fputs(", expired", fp );
	    if( rec->r.dir.dirflags & DIRF_REVOKED )
		fputs(", revoked", fp );
	}
	putc('\n', fp);
	break;
      case RECTYPE_KEY:
	fprintf(fp, "key %lu, next=%lu, algo=%d, ",
		   rec->r.key.lid,
		   rec->r.key.next,
		   rec->r.key.pubkey_algo );
	for(i=0; i < rec->r.key.fingerprint_len; i++ )
	    fprintf(fp, "%02X", rec->r.key.fingerprint[i] );
	if( rec->r.key.keyflags & KEYF_CHECKED ) {
	    if( rec->r.key.keyflags & KEYF_VALID )
		fputs(", valid", fp );
	    if( rec->r.key.keyflags & KEYF_EXPIRED )
		fputs(", expired", fp );
	    if( rec->r.key.keyflags & KEYF_REVOKED )
		fputs(", revoked", fp );
	}
	putc('\n', fp);
	break;
      case RECTYPE_UID:
	fprintf(fp, "uid %lu, next=%lu, pref=%lu, sig=%lu, hash=%02X%02X",
		    rec->r.uid.lid,
		    rec->r.uid.next,
		    rec->r.uid.prefrec,
		    rec->r.uid.siglist,
		    rec->r.uid.namehash[18], rec->r.uid.namehash[19]);
	if( rec->r.uid.uidflags & UIDF_CHECKED ) {
	    if( rec->r.uid.uidflags & UIDF_VALID )
		fputs(", valid", fp );
	    if( rec->r.uid.uidflags & UIDF_REVOKED )
		fputs(", revoked", fp );
	}
	putc('\n', fp);
	break;
      case RECTYPE_PREF:
	fprintf(fp, "pref %lu, next=%lu,",
		    rec->r.pref.lid, rec->r.pref.next);
	for(i=0,p=rec->r.pref.data; i < ITEMS_PER_PREF_RECORD; i+=2,p+=2 ) {
	    if( *p )
		fprintf(fp, " %c%d", *p == PREFTYPE_SYM    ? 'S' :
				     *p == PREFTYPE_HASH   ? 'H' :
				     *p == PREFTYPE_COMPR  ? 'Z' : '?', p[1]);
	}
	putc('\n', fp);
	break;
      case RECTYPE_SIG:
	fprintf(fp, "sig %lu, next=%lu,",
			 rec->r.sig.lid, rec->r.sig.next );
	for(i=0; i < SIGS_PER_RECORD; i++ ) {
	    if( rec->r.sig.sig[i].lid ) {
		fprintf(fp, " %lu:", rec->r.sig.sig[i].lid );
		if( rec->r.sig.sig[i].flag & SIGF_CHECKED ) {
		    fprintf(fp,"%c%c%c",
		       (rec->r.sig.sig[i].flag & SIGF_VALID)   ? 'V':'-',
		       (rec->r.sig.sig[i].flag & SIGF_EXPIRED) ? 'E':'-',
		       (rec->r.sig.sig[i].flag & SIGF_REVOKED) ? 'R':'-');
		}
		else if( rec->r.sig.sig[i].flag & SIGF_NOPUBKEY)
		    fputs("?--", fp);
		else
		    fputs("---", fp);
	    }
	}
	putc('\n', fp);
	break;
      case RECTYPE_SDIR:
	fprintf(fp, "sdir %lu, keyid=%08lX%08lX, algo=%d, hint=%lu\n",
		    rec->r.sdir.lid,
		    (ulong)rec->r.sdir.keyid[0],
		    (ulong)rec->r.sdir.keyid[1],
		    rec->r.sdir.pubkey_algo,
		    (ulong)rec->r.sdir.hintlist );
	break;
      case RECTYPE_CACH:
	fprintf(fp, "cach\n");
	break;
      case RECTYPE_HTBL:
	fprintf(fp, "htbl,");
	for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ )
	    fprintf(fp, " %lu", rec->r.htbl.item[i] );
	putc('\n', fp);
	break;
      case RECTYPE_HLST:
	fprintf(fp, "hlst, next=%lu,", rec->r.hlst.next );
	for(i=0; i < ITEMS_PER_HLST_RECORD; i++ )
	    fprintf(fp, " %lu", rec->r.hlst.rnum[i] );
	putc('\n', fp);
	break;
      default:
	fprintf(fp, "unknown type %d\n", rec->rectype );
	break;
    }
}

/****************
 * read the record with number recnum
 * returns: -1 on error, 0 on success
 */
int
tdbio_read_record( ulong recnum, TRUSTREC *rec, int expected )
{
    byte readbuf[TRUST_RECORD_LEN];
    const byte *buf, *p;
    int rc = 0;
    int n, i;

    if( db_fd == -1 )
	open_db();
    buf = get_record_from_cache( recnum );
    if( !buf ) {
	if( lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
	    log_error(_("trustdb: lseek failed: %s\n"), strerror(errno) );
	    return G10ERR_READ_FILE;
	}
	n = read( db_fd, readbuf, TRUST_RECORD_LEN);
	if( !n ) {
	    return -1; /* eof */
	}
	else if( n != TRUST_RECORD_LEN ) {
	    log_error(_("trustdb: read failed (n=%d): %s\n"), n,
							strerror(errno) );
	    return G10ERR_READ_FILE;
	}
	buf = readbuf;
    }
    rec->recnum = recnum;
    rec->dirty = 0;
    p = buf;
    rec->rectype = *p++;
    if( expected && rec->rectype != expected ) {
	log_error("%lu: read expected rec type %d, got %d\n",
		    recnum, expected, rec->rectype );
	return G10ERR_TRUSTDB;
    }
    p++;    /* skip reserved byte */
    switch( rec->rectype ) {
      case 0:  /* unused (free) record */
	break;
      case RECTYPE_VER: /* version record */
	if( memcmp(buf+1, "gpg", 3 ) ) {
	    log_error( _("%s: not a trustdb file\n"), db_name );
	    rc = G10ERR_TRUSTDB;
	}
	p += 2; /* skip "pgp" */
	rec->r.ver.version  = *p++;
	p += 3; /* reserved bytes */
	p += 4; /* lock flags */
	rec->r.ver.created  = buftoulong(p); p += 4;
	rec->r.ver.modified = buftoulong(p); p += 4;
	rec->r.ver.validated= buftoulong(p); p += 4;
	rec->r.ver.keyhashtbl=buftoulong(p); p += 4;
	rec->r.ver.firstfree =buftoulong(p); p += 4;
	rec->r.ver.sdirhashtbl =buftoulong(p); p += 4;
	if( recnum ) {
	    log_error( _("%s: version record with recnum %lu\n"), db_name,
							     (ulong)recnum );
	    rc = G10ERR_TRUSTDB;
	}
	else if( rec->r.ver.version != 2 ) {
	    log_error( _("%s: invalid file version %d\n"), db_name,
							rec->r.ver.version );
	    rc = G10ERR_TRUSTDB;
	}
	break;
      case RECTYPE_FREE:
	rec->r.free.next  = buftoulong(p); p += 4;
	break;
      case RECTYPE_DIR:   /*directory record */
	rec->r.dir.lid	    = buftoulong(p); p += 4;
	rec->r.dir.keylist  = buftoulong(p); p += 4;
	rec->r.dir.uidlist  = buftoulong(p); p += 4;
	rec->r.dir.cacherec = buftoulong(p); p += 4;
	rec->r.dir.ownertrust = *p++;
	rec->r.dir.dirflags   = *p++;
	if( rec->r.dir.lid != recnum ) {
	    log_error( "%s: dir LID != recnum (%lu,%lu)\n",
			      db_name, rec->r.dir.lid, (ulong)recnum );
	    rc = G10ERR_TRUSTDB;
	}
	break;
      case RECTYPE_KEY:   /* public key record */
	rec->r.key.lid	    = buftoulong(p); p += 4;
	rec->r.key.next     = buftoulong(p); p += 4;
	p += 7;
	rec->r.key.keyflags = *p++;
	rec->r.key.pubkey_algo = *p++;
	rec->r.key.fingerprint_len = *p++;
	if( rec->r.key.fingerprint_len < 1 || rec->r.key.fingerprint_len > 20 )
	    rec->r.key.fingerprint_len = 20;
	memcpy( rec->r.key.fingerprint, p, 20);
	break;
      case RECTYPE_UID:   /* user id record */
	rec->r.uid.lid	    = buftoulong(p); p += 4;
	rec->r.uid.next     = buftoulong(p); p += 4;
	rec->r.uid.prefrec  = buftoulong(p); p += 4;
	rec->r.uid.siglist  = buftoulong(p); p += 4;
	rec->r.uid.uidflags = *p++;
	p ++;
	memcpy( rec->r.uid.namehash, p, 20);
	break;
      case RECTYPE_PREF:  /* preference record */
	rec->r.pref.lid     = buftoulong(p); p += 4;
	rec->r.pref.next    = buftoulong(p); p += 4;
	memcpy( rec->r.pref.data, p, 30 );
	break;
      case RECTYPE_SIG:
	rec->r.sig.lid	   = buftoulong(p); p += 4;
	rec->r.sig.next    = buftoulong(p); p += 4;
	for(i=0; i < SIGS_PER_RECORD; i++ ) {
	    rec->r.sig.sig[i].lid  = buftoulong(p); p += 4;
	    rec->r.sig.sig[i].flag = *p++;
	}
	break;
      case RECTYPE_SDIR:   /* shadow directory record */
	rec->r.sdir.lid     = buftoulong(p); p += 4;
	rec->r.sdir.keyid[0]= buftou32(p); p += 4;
	rec->r.sdir.keyid[1]= buftou32(p); p += 4;
	rec->r.sdir.pubkey_algo = *p++;
	p += 3;
	rec->r.sdir.hintlist = buftoulong(p);
	if( rec->r.sdir.lid != recnum ) {
	    log_error( "%s: sdir LID != recnum (%lu,%lu)\n",
			       db_name, rec->r.sdir.lid, (ulong)recnum );
	    rc = G10ERR_TRUSTDB;
	}
	break;
      case RECTYPE_CACH:   /* cache record */
	rec->r.cache.lid    = buftoulong(p); p += 4;
	memcpy(rec->r.cache.blockhash, p, 20); p += 20;
	rec->r.cache.trustlevel = *p++;
	break;
      case RECTYPE_HTBL:
	for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
	    rec->r.htbl.item[i] = buftoulong(p); p += 4;
	}
	break;
      case RECTYPE_HLST:
	rec->r.hlst.next = buftoulong(p); p += 4;
	for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
	    rec->r.hlst.rnum[i] = buftoulong(p); p += 4;
	}
	break;
      default:
	log_error( "%s: invalid record type %d at recnum %lu\n",
				   db_name, rec->rectype, (ulong)recnum );
	rc = G10ERR_TRUSTDB;
	break;
    }

    return rc;
}

/****************
 * Write the record at RECNUM
 */
int
tdbio_write_record( TRUSTREC *rec )
{
    byte buf[TRUST_RECORD_LEN], *p;
    int rc = 0;
    int i;
    ulong recnum = rec->recnum;

    if( db_fd == -1 )
	open_db();

    memset(buf, 0, TRUST_RECORD_LEN);
    p = buf;
    *p++ = rec->rectype; p++;
    switch( rec->rectype ) {
      case 0:  /* unused record */
	break;
      case RECTYPE_VER: /* version record */
	if( recnum )
	    BUG();
	memcpy(p-1, "gpg", 3 ); p += 2;
	*p++ = rec->r.ver.version;
	p += 7; /* skip reserved bytes and lock flags */
	ulongtobuf(p, rec->r.ver.created); p += 4;
	ulongtobuf(p, rec->r.ver.modified); p += 4;
	ulongtobuf(p, rec->r.ver.validated); p += 4;
	ulongtobuf(p, rec->r.ver.keyhashtbl); p += 4;
	ulongtobuf(p, rec->r.ver.firstfree ); p += 4;
	ulongtobuf(p, rec->r.ver.sdirhashtbl ); p += 4;
	break;

      case RECTYPE_FREE:
	ulongtobuf(p, rec->r.free.next); p += 4;
	break;

      case RECTYPE_DIR:   /*directory record */
	ulongtobuf(p, rec->r.dir.lid); p += 4;
	ulongtobuf(p, rec->r.dir.keylist); p += 4;
	ulongtobuf(p, rec->r.dir.uidlist); p += 4;
	ulongtobuf(p, rec->r.dir.cacherec); p += 4;
	*p++ = rec->r.dir.ownertrust;
	*p++ = rec->r.dir.dirflags;
	assert( rec->r.dir.lid == recnum );
	break;

      case RECTYPE_KEY:
	ulongtobuf(p, rec->r.key.lid); p += 4;
	ulongtobuf(p, rec->r.key.next); p += 4;
	p += 7;
	*p++ = rec->r.key.keyflags;
	*p++ = rec->r.key.pubkey_algo;
	*p++ = rec->r.key.fingerprint_len;
	memcpy( p, rec->r.key.fingerprint, 20); p += 20;
	break;

      case RECTYPE_UID:   /* user id record */
	ulongtobuf(p, rec->r.uid.lid); p += 4;
	ulongtobuf(p, rec->r.uid.next); p += 4;
	ulongtobuf(p, rec->r.uid.prefrec); p += 4;
	ulongtobuf(p, rec->r.uid.siglist); p += 4;
	*p++ = rec->r.uid.uidflags;
	p++;
	memcpy( p, rec->r.uid.namehash, 20 ); p += 20;
	break;

      case RECTYPE_PREF:
	ulongtobuf(p, rec->r.pref.lid); p += 4;
	ulongtobuf(p, rec->r.pref.next); p += 4;
	memcpy( p, rec->r.pref.data, 30 );
	break;

      case RECTYPE_SIG:
	ulongtobuf(p, rec->r.sig.lid); p += 4;
	ulongtobuf(p, rec->r.sig.next); p += 4;
	for(i=0; i < SIGS_PER_RECORD; i++ ) {
	    ulongtobuf(p, rec->r.sig.sig[i].lid); p += 4;
	    *p++ = rec->r.sig.sig[i].flag;
	}
	break;

      case RECTYPE_SDIR:
	ulongtobuf( p, rec->r.sdir.lid); p += 4;
	u32tobuf( p, rec->r.sdir.keyid[0] ); p += 4;
	u32tobuf( p, rec->r.sdir.keyid[1] ); p += 4;
	*p++ = rec->r.sdir.pubkey_algo;
	p += 3;
	ulongtobuf( p, rec->r.sdir.hintlist );
	break;

      case RECTYPE_CACH:
	ulongtobuf(p, rec->r.cache.lid); p += 4;
	memcpy(p, rec->r.cache.blockhash, 20); p += 20;
	*p++ = rec->r.cache.trustlevel;
	break;

      case RECTYPE_HTBL:
	for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
	    ulongtobuf( p, rec->r.htbl.item[i]); p += 4;
	}
	break;

      case RECTYPE_HLST:
	ulongtobuf( p, rec->r.hlst.next); p += 4;
	for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
	    ulongtobuf( p, rec->r.hlst.rnum[i]); p += 4;
	}
	break;

      default:
	BUG();
    }

    rc = put_record_into_cache( recnum, buf );
    if( rc )
	;
    if( rec->rectype == RECTYPE_KEY )
	rc = update_keyhashtbl( rec );
    else if( rec->rectype == RECTYPE_SDIR )
	rc = update_sdirhashtbl( rec );

    return rc;
}

int
tdbio_delete_record( ulong recnum )
{
    TRUSTREC vr, rec;
    int rc;

    rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
    if( rc )
	log_fatal( _("%s: error reading version record: %s\n"),
				       db_name, g10_errstr(rc) );

    rec.recnum = recnum;
    rec.rectype = RECTYPE_FREE;
    rec.r.free.next = vr.r.ver.firstfree;
    vr.r.ver.firstfree = recnum;
    rc = tdbio_write_record( &rec );
    if( !rc )
	rc = tdbio_write_record( &vr );
    return rc;
}

/****************
 * create a new record and return its record number
 */
ulong
tdbio_new_recnum()
{
    off_t offset;
    ulong recnum;
    TRUSTREC vr, rec;
    int rc;

    /* look for unused records */
    rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
    if( rc )
	log_fatal( _("%s: error reading version record: %s\n"),
					     db_name, g10_errstr(rc) );
    if( vr.r.ver.firstfree ) {
	recnum = vr.r.ver.firstfree;
	rc = tdbio_read_record( recnum, &rec, RECTYPE_FREE );
	if( rc ) {
	    log_error( _("%s: error reading free record: %s\n"),
						  db_name,  g10_errstr(rc) );
	    return rc;
	}
	/* update dir record */
	vr.r.ver.firstfree = rec.r.free.next;
	rc = tdbio_write_record( &vr );
	if( rc ) {
	    log_error( _("%s: error writing dir record: %s\n"),
						     db_name, g10_errstr(rc) );
	    return rc;
	}
	/*zero out the new record */
	memset( &rec, 0, sizeof rec );
	rec.rectype = 0; /* unused record */
	rec.recnum = recnum;
	rc = tdbio_write_record( &rec );
	if( rc )
	    log_fatal(_("%s: failed to zero a record: %s\n"),
				       db_name, g10_errstr(rc));
    }
    else { /* not found, append a new record */
	offset = lseek( db_fd, 0, SEEK_END );
	if( offset == -1 )
	    log_fatal("trustdb: lseek to end failed: %s\n", strerror(errno) );
	recnum = offset / TRUST_RECORD_LEN;
	assert(recnum); /* this is will never be the first record */
	/* we must write a record, so that the next call to this function
	 * returns another recnum */
	memset( &rec, 0, sizeof rec );
	rec.rectype = 0; /* unused record */
	rec.recnum = recnum;
	rc = 0;
	if( lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
	    log_error(_("trustdb rec %lu: lseek failed: %s\n"),
						recnum, strerror(errno) );
	    rc = G10ERR_WRITE_FILE;
	}
	else {
	    int n = write( db_fd, &rec, TRUST_RECORD_LEN);
	    if( n != TRUST_RECORD_LEN ) {
		log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
						 recnum, n, strerror(errno) );
		rc = G10ERR_WRITE_FILE;
	    }
	}

	if( rc )
	    log_fatal(_("%s: failed to append a record: %s\n"),
				    db_name,	g10_errstr(rc));
    }
    return recnum ;
}



/****************
 * Search the trustdb for a key which matches PK and return the dir record
 * The local_id of PK is set to the correct value
 */
int
tdbio_search_dir_bypk( PKT_public_key *pk, TRUSTREC *rec )
{
    byte fingerprint[MAX_FINGERPRINT_LEN];
    size_t fingerlen;
    u32 keyid[2];
    int rc;

    keyid_from_pk( pk, keyid );
    fingerprint_from_pk( pk, fingerprint, &fingerlen );
    rc = tdbio_search_dir_byfpr( fingerprint, fingerlen,
				 pk->pubkey_algo, rec );

    if( !rc ) {
	if( pk->local_id && pk->local_id != rec->recnum )
	    log_error("%s: found record, but LID from memory does "
		       "not match recnum (%lu,%lu)\n",
			    db_name,  pk->local_id, rec->recnum );
	pk->local_id = rec->recnum;
    }
    return rc;
}


static int
cmp_krec_fpr( void *dataptr, const TRUSTREC *rec )
{
    const struct cmp_krec_fpr_struct *d = dataptr;

    return rec->rectype == RECTYPE_KEY
	   && ( !d->pubkey_algo || rec->r.key.pubkey_algo == d->pubkey_algo )
	   && rec->r.key.fingerprint_len == d->fprlen
	   && !memcmp( rec->r.key.fingerprint, d->fpr, d->fprlen );
}

int
tdbio_search_dir_byfpr( const byte *fingerprint, size_t fingerlen,
			int pubkey_algo, TRUSTREC *rec )
{
    struct cmp_krec_fpr_struct cmpdata;
    ulong recnum;
    int rc;

    assert( fingerlen == 20 || fingerlen == 16 );

    /* locate the key using the hash table */
    cmpdata.pubkey_algo = pubkey_algo;
    cmpdata.fpr = fingerprint;
    cmpdata.fprlen = fingerlen;
    rc = lookup_hashtable( get_keyhashrec(), fingerprint, fingerlen,
			   cmp_krec_fpr, &cmpdata, rec );
    if( !rc ) {
	recnum = rec->r.key.lid;
	/* Now read the dir record */
	rc = tdbio_read_record( recnum, rec, RECTYPE_DIR);
	if( rc )
	    log_error("%s: can't read dirrec %lu: %s\n",
				     db_name, recnum, g10_errstr(rc) );
    }
    return rc;
}



static int
cmp_sdir( void *dataptr, const TRUSTREC *rec )
{
    const struct cmp_sdir_struct *d = dataptr;

    return rec->rectype == RECTYPE_SDIR
	   && ( !d->pubkey_algo || rec->r.sdir.pubkey_algo == d->pubkey_algo )
	   && rec->r.sdir.keyid[0] == d->keyid[0]
	   && rec->r.sdir.keyid[1] == d->keyid[1];
}


int
tdbio_search_sdir( u32 *keyid, int pubkey_algo, TRUSTREC *rec )
{
    struct cmp_sdir_struct cmpdata;
    int rc;
    byte key[8];

    /* locate the shadow dir record using the hash table */
    u32tobuf( key   , keyid[0] );
    u32tobuf( key+4 , keyid[1] );
    cmpdata.pubkey_algo = pubkey_algo;
    cmpdata.keyid[0] = keyid[0];
    cmpdata.keyid[1] = keyid[1];
    rc = lookup_hashtable( get_sdirhashrec(), key, 8,
			   cmp_sdir, &cmpdata, rec );
    return rc;
}