2008-02-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / tdbio.c
blob2429f1a5d68c12302a7770e7a538a4845d10f570
1 /* tdbio.c - trust databse I/O operations
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
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 3 of the License, or
9 * (at your option) any later version.
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.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <assert.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 #include <unistd.h>
31 #include "gpg.h"
32 #include "status.h"
33 #include "iobuf.h"
34 #include "util.h"
35 #include "options.h"
36 #include "main.h"
37 #include "i18n.h"
38 #include "trustdb.h"
39 #include "tdbio.h"
41 #if defined(HAVE_DOSISH_SYSTEM)
42 #define ftruncate chsize
43 #endif
45 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
46 #define MY_O_BINARY O_BINARY
47 #else
48 #define MY_O_BINARY 0
49 #endif
52 /****************
53 * Yes, this is a very simple implementation. We should really
54 * use a page aligned buffer and read complete pages.
55 * To implement a simple trannsaction system, this is sufficient.
57 typedef struct cache_ctrl_struct *CACHE_CTRL;
58 struct cache_ctrl_struct {
59 CACHE_CTRL next;
60 struct {
61 unsigned used:1;
62 unsigned dirty:1;
63 } flags;
64 ulong recno;
65 char data[TRUST_RECORD_LEN];
68 #define MAX_CACHE_ENTRIES_SOFT 200 /* may be increased while in a */
69 #define MAX_CACHE_ENTRIES_HARD 10000 /* transaction to this one */
70 static CACHE_CTRL cache_list;
71 static int cache_entries;
72 static int cache_is_dirty;
74 /* a type used to pass infomation to cmp_krec_fpr */
75 struct cmp_krec_fpr_struct {
76 int pubkey_algo;
77 const char *fpr;
78 int fprlen;
81 /* a type used to pass infomation to cmp_[s]dir */
82 struct cmp_xdir_struct {
83 int pubkey_algo;
84 u32 keyid[2];
88 static char *db_name;
89 static DOTLOCK lockhandle;
90 static int is_locked;
91 static int db_fd = -1;
92 static int in_transaction;
94 static void open_db(void);
98 /*************************************
99 ************* record cache **********
100 *************************************/
102 /****************
103 * Get the data from therecord cache and return a
104 * pointer into that cache. Caller should copy
105 * the return data. NULL is returned on a cache miss.
107 static const char *
108 get_record_from_cache( ulong recno )
110 CACHE_CTRL r;
112 for( r = cache_list; r; r = r->next ) {
113 if( r->flags.used && r->recno == recno )
114 return r->data;
116 return NULL;
120 static int
121 write_cache_item( CACHE_CTRL r )
123 gpg_error_t err;
124 int n;
126 if( lseek( db_fd, r->recno * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
127 err = gpg_error_from_syserror ();
128 log_error(_("trustdb rec %lu: lseek failed: %s\n"),
129 r->recno, strerror(errno) );
130 return err;
132 n = write( db_fd, r->data, TRUST_RECORD_LEN);
133 if( n != TRUST_RECORD_LEN ) {
134 err = gpg_error_from_syserror ();
135 log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
136 r->recno, n, strerror(errno) );
137 return err;
139 r->flags.dirty = 0;
140 return 0;
143 /****************
144 * Put data into the cache. This function may flush the
145 * some cache entries if there is not enough space available.
148 put_record_into_cache( ulong recno, const char *data )
150 CACHE_CTRL r, unused;
151 int dirty_count = 0;
152 int clean_count = 0;
154 /* see whether we already cached this one */
155 for( unused = NULL, r = cache_list; r; r = r->next ) {
156 if( !r->flags.used ) {
157 if( !unused )
158 unused = r;
160 else if( r->recno == recno ) {
161 if( !r->flags.dirty ) {
162 /* Hmmm: should we use a a copy and compare? */
163 if( memcmp(r->data, data, TRUST_RECORD_LEN ) ) {
164 r->flags.dirty = 1;
165 cache_is_dirty = 1;
168 memcpy( r->data, data, TRUST_RECORD_LEN );
169 return 0;
171 if( r->flags.used ) {
172 if( r->flags.dirty )
173 dirty_count++;
174 else
175 clean_count++;
178 /* not in the cache: add a new entry */
179 if( unused ) { /* reuse this entry */
180 r = unused;
181 r->flags.used = 1;
182 r->recno = recno;
183 memcpy( r->data, data, TRUST_RECORD_LEN );
184 r->flags.dirty = 1;
185 cache_is_dirty = 1;
186 cache_entries++;
187 return 0;
189 /* see whether we reached the limit */
190 if( cache_entries < MAX_CACHE_ENTRIES_SOFT ) { /* no */
191 r = xmalloc( sizeof *r );
192 r->flags.used = 1;
193 r->recno = recno;
194 memcpy( r->data, data, TRUST_RECORD_LEN );
195 r->flags.dirty = 1;
196 r->next = cache_list;
197 cache_list = r;
198 cache_is_dirty = 1;
199 cache_entries++;
200 return 0;
202 /* cache is full: discard some clean entries */
203 if( clean_count ) {
204 int n = clean_count / 3; /* discard a third of the clean entries */
205 if( !n )
206 n = 1;
207 for( unused = NULL, r = cache_list; r; r = r->next ) {
208 if( r->flags.used && !r->flags.dirty ) {
209 if( !unused )
210 unused = r;
211 r->flags.used = 0;
212 cache_entries--;
213 if( !--n )
214 break;
217 assert( unused );
218 r = unused;
219 r->flags.used = 1;
220 r->recno = recno;
221 memcpy( r->data, data, TRUST_RECORD_LEN );
222 r->flags.dirty = 1;
223 cache_is_dirty = 1;
224 cache_entries++;
225 return 0;
227 /* no clean entries: have to flush some dirty entries */
228 if( in_transaction ) {
229 /* but we can't do this while in a transaction
230 * we increase the cache size instead */
231 if( cache_entries < MAX_CACHE_ENTRIES_HARD ) { /* no */
232 if( opt.debug && !(cache_entries % 100) )
233 log_debug("increasing tdbio cache size\n");
234 r = xmalloc( sizeof *r );
235 r->flags.used = 1;
236 r->recno = recno;
237 memcpy( r->data, data, TRUST_RECORD_LEN );
238 r->flags.dirty = 1;
239 r->next = cache_list;
240 cache_list = r;
241 cache_is_dirty = 1;
242 cache_entries++;
243 return 0;
245 log_info(_("trustdb transaction too large\n"));
246 return G10ERR_RESOURCE_LIMIT;
248 if( dirty_count ) {
249 int n = dirty_count / 5; /* discard some dirty entries */
250 if( !n )
251 n = 1;
252 if( !is_locked ) {
253 if( make_dotlock( lockhandle, -1 ) )
254 log_fatal("can't acquire lock - giving up\n");
255 else
256 is_locked = 1;
258 for( unused = NULL, r = cache_list; r; r = r->next ) {
259 if( r->flags.used && r->flags.dirty ) {
260 int rc = write_cache_item( r );
261 if( rc )
262 return rc;
263 if( !unused )
264 unused = r;
265 r->flags.used = 0;
266 cache_entries--;
267 if( !--n )
268 break;
271 if( !opt.lock_once ) {
272 if( !release_dotlock( lockhandle ) )
273 is_locked = 0;
275 assert( unused );
276 r = unused;
277 r->flags.used = 1;
278 r->recno = recno;
279 memcpy( r->data, data, TRUST_RECORD_LEN );
280 r->flags.dirty = 1;
281 cache_is_dirty = 1;
282 cache_entries++;
283 return 0;
285 BUG();
290 tdbio_is_dirty()
292 return cache_is_dirty;
296 /****************
297 * Flush the cache. This cannot be used while in a transaction.
300 tdbio_sync()
302 CACHE_CTRL r;
303 int did_lock = 0;
305 if( db_fd == -1 )
306 open_db();
307 if( in_transaction )
308 log_bug("tdbio: syncing while in transaction\n");
310 if( !cache_is_dirty )
311 return 0;
313 if( !is_locked ) {
314 if( make_dotlock( lockhandle, -1 ) )
315 log_fatal("can't acquire lock - giving up\n");
316 else
317 is_locked = 1;
318 did_lock = 1;
320 for( r = cache_list; r; r = r->next ) {
321 if( r->flags.used && r->flags.dirty ) {
322 int rc = write_cache_item( r );
323 if( rc )
324 return rc;
327 cache_is_dirty = 0;
328 if( did_lock && !opt.lock_once ) {
329 if( !release_dotlock( lockhandle ) )
330 is_locked = 0;
333 return 0;
336 #if 0
337 /* The transaction code is disabled in the 1.2.x branch, as it is not
338 yet used. It will be enabled in 1.3.x. */
340 /****************
341 * Simple transactions system:
342 * Everything between begin_transaction and end/cancel_transaction
343 * is not immediatly written but at the time of end_transaction.
347 tdbio_begin_transaction()
349 int rc;
351 if( in_transaction )
352 log_bug("tdbio: nested transactions\n");
353 /* flush everything out */
354 rc = tdbio_sync();
355 if( rc )
356 return rc;
357 in_transaction = 1;
358 return 0;
362 tdbio_end_transaction()
364 int rc;
366 if( !in_transaction )
367 log_bug("tdbio: no active transaction\n");
368 if( !is_locked ) {
369 if( make_dotlock( lockhandle, -1 ) )
370 log_fatal("can't acquire lock - giving up\n");
371 else
372 is_locked = 1;
374 block_all_signals();
375 in_transaction = 0;
376 rc = tdbio_sync();
377 unblock_all_signals();
378 if( !opt.lock_once ) {
379 if( !release_dotlock( lockhandle ) )
380 is_locked = 0;
382 return rc;
386 tdbio_cancel_transaction()
388 CACHE_CTRL r;
390 if( !in_transaction )
391 log_bug("tdbio: no active transaction\n");
393 /* remove all dirty marked entries, so that the original ones
394 * are read back the next time */
395 if( cache_is_dirty ) {
396 for( r = cache_list; r; r = r->next ) {
397 if( r->flags.used && r->flags.dirty ) {
398 r->flags.used = 0;
399 cache_entries--;
402 cache_is_dirty = 0;
405 in_transaction = 0;
406 return 0;
408 #endif
411 /********************************************************
412 **************** cached I/O functions ******************
413 ********************************************************/
415 static void
416 cleanup(void)
418 if( is_locked ) {
419 if( !release_dotlock(lockhandle) )
420 is_locked = 0;
424 /* Caller must sync */
426 tdbio_update_version_record (void)
428 TRUSTREC rec;
429 int rc;
431 memset( &rec, 0, sizeof rec );
433 rc=tdbio_read_record( 0, &rec, RECTYPE_VER);
434 if(rc==0)
436 rec.r.ver.created = make_timestamp();
437 rec.r.ver.marginals = opt.marginals_needed;
438 rec.r.ver.completes = opt.completes_needed;
439 rec.r.ver.cert_depth = opt.max_cert_depth;
440 rec.r.ver.trust_model = opt.trust_model;
441 rc=tdbio_write_record(&rec);
444 return rc;
447 static int
448 create_version_record (void)
450 TRUSTREC rec;
451 int rc;
453 memset( &rec, 0, sizeof rec );
454 rec.r.ver.version = 3;
455 rec.r.ver.created = make_timestamp();
456 rec.r.ver.marginals = opt.marginals_needed;
457 rec.r.ver.completes = opt.completes_needed;
458 rec.r.ver.cert_depth = opt.max_cert_depth;
459 if(opt.trust_model==TM_PGP || opt.trust_model==TM_CLASSIC)
460 rec.r.ver.trust_model = opt.trust_model;
461 else
462 rec.r.ver.trust_model = TM_PGP;
463 rec.rectype = RECTYPE_VER;
464 rec.recnum = 0;
465 rc = tdbio_write_record( &rec );
466 if( !rc )
467 tdbio_sync();
468 return rc;
474 tdbio_set_dbname( const char *new_dbname, int create )
476 char *fname;
477 static int initialized = 0;
479 if( !initialized ) {
480 atexit( cleanup );
481 initialized = 1;
484 if(new_dbname==NULL)
485 fname=make_filename(opt.homedir,"trustdb" EXTSEP_S "gpg", NULL);
486 else if (*new_dbname != DIRSEP_C )
488 if (strchr(new_dbname, DIRSEP_C) )
489 fname = make_filename (new_dbname, NULL);
490 else
491 fname = make_filename (opt.homedir, new_dbname, NULL);
493 else
494 fname = xstrdup (new_dbname);
496 if( access( fname, R_OK ) ) {
497 if( errno != ENOENT ) {
498 log_error( _("can't access `%s': %s\n"), fname, strerror(errno) );
499 xfree(fname);
500 return G10ERR_TRUSTDB;
502 if( create ) {
503 FILE *fp;
504 TRUSTREC rec;
505 int rc;
506 char *p = strrchr( fname, DIRSEP_C );
507 mode_t oldmask;
508 int save_slash;
510 #if HAVE_W32_SYSTEM
512 /* Windows may either have a slash or a backslash. Take
513 care of it. */
514 char *pp = strrchr (fname, '/');
515 if (!p || pp > p)
516 p = pp;
518 #endif /*HAVE_W32_SYSTEM*/
519 assert (p);
520 save_slash = *p;
521 *p = 0;
522 if( access( fname, F_OK ) ) {
523 try_make_homedir( fname );
524 log_fatal( _("%s: directory does not exist!\n"), fname );
526 *p = save_slash;
528 xfree(db_name);
529 db_name = fname;
530 #ifdef __riscos__
531 if( !lockhandle )
532 lockhandle = create_dotlock( db_name );
533 if( !lockhandle )
534 log_fatal( _("can't create lock for `%s'\n"), db_name );
535 if( make_dotlock( lockhandle, -1 ) )
536 log_fatal( _("can't lock `%s'\n"), db_name );
537 #endif /* __riscos__ */
538 oldmask=umask(077);
539 if (is_secured_filename (fname)) {
540 fp = NULL;
541 errno = EPERM;
543 else
544 fp =fopen( fname, "wb" );
545 umask(oldmask);
546 if( !fp )
547 log_fatal( _("can't create `%s': %s\n"), fname, strerror(errno) );
548 fclose(fp);
549 db_fd = open( db_name, O_RDWR | MY_O_BINARY );
550 if( db_fd == -1 )
551 log_fatal( _("can't open `%s': %s\n"), db_name, strerror(errno) );
553 #ifndef __riscos__
554 if( !lockhandle )
555 lockhandle = create_dotlock( db_name );
556 if( !lockhandle )
557 log_fatal( _("can't create lock for `%s'\n"), db_name );
558 #endif /* !__riscos__ */
560 rc = create_version_record ();
561 if( rc )
562 log_fatal( _("%s: failed to create version record: %s"),
563 fname, g10_errstr(rc));
564 /* and read again to check that we are okay */
565 if( tdbio_read_record( 0, &rec, RECTYPE_VER ) )
566 log_fatal( _("%s: invalid trustdb created\n"), db_name );
568 if( !opt.quiet )
569 log_info(_("%s: trustdb created\n"), db_name);
571 return 0;
574 xfree(db_name);
575 db_name = fname;
576 return 0;
580 const char *
581 tdbio_get_dbname()
583 return db_name;
588 static void
589 open_db()
591 TRUSTREC rec;
593 assert( db_fd == -1 );
595 if (!lockhandle )
596 lockhandle = create_dotlock( db_name );
597 if (!lockhandle )
598 log_fatal( _("can't create lock for `%s'\n"), db_name );
599 #ifdef __riscos__
600 if (make_dotlock( lockhandle, -1 ) )
601 log_fatal( _("can't lock `%s'\n"), db_name );
602 #endif /* __riscos__ */
603 db_fd = open (db_name, O_RDWR | MY_O_BINARY );
604 if (db_fd == -1 && (errno == EACCES
605 #ifdef EROFS
606 || errno == EROFS)
607 #endif
609 db_fd = open (db_name, O_RDONLY | MY_O_BINARY );
610 if (db_fd != -1)
611 log_info (_("NOTE: trustdb not writable\n"));
613 if ( db_fd == -1 )
614 log_fatal( _("can't open `%s': %s\n"), db_name, strerror(errno) );
615 register_secured_file (db_name);
617 /* Read the version record. */
618 if (tdbio_read_record (0, &rec, RECTYPE_VER ) )
619 log_fatal( _("%s: invalid trustdb\n"), db_name );
623 /****************
624 * Make a hashtable: type 0 = trust hash
626 static void
627 create_hashtable( TRUSTREC *vr, int type )
629 TRUSTREC rec;
630 off_t offset;
631 ulong recnum;
632 int i, n, rc;
634 offset = lseek( db_fd, 0, SEEK_END );
635 if( offset == -1 )
636 log_fatal("trustdb: lseek to end failed: %s\n", strerror(errno) );
637 recnum = offset / TRUST_RECORD_LEN;
638 assert(recnum); /* this is will never be the first record */
640 if( !type )
641 vr->r.ver.trusthashtbl = recnum;
643 /* Now write the records */
644 n = (256+ITEMS_PER_HTBL_RECORD-1) / ITEMS_PER_HTBL_RECORD;
645 for(i=0; i < n; i++, recnum++ ) {
646 memset( &rec, 0, sizeof rec );
647 rec.rectype = RECTYPE_HTBL;
648 rec.recnum = recnum;
649 rc = tdbio_write_record( &rec );
650 if( rc )
651 log_fatal( _("%s: failed to create hashtable: %s\n"),
652 db_name, g10_errstr(rc));
654 /* update the version record */
655 rc = tdbio_write_record( vr );
656 if( !rc )
657 rc = tdbio_sync();
658 if( rc )
659 log_fatal( _("%s: error updating version record: %s\n"),
660 db_name, g10_errstr(rc));
665 tdbio_db_matches_options()
667 static int yes_no = -1;
669 if( yes_no == -1 )
671 TRUSTREC vr;
672 int rc;
674 rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
675 if( rc )
676 log_fatal( _("%s: error reading version record: %s\n"),
677 db_name, g10_errstr(rc) );
679 yes_no = vr.r.ver.marginals == opt.marginals_needed
680 && vr.r.ver.completes == opt.completes_needed
681 && vr.r.ver.cert_depth == opt.max_cert_depth
682 && vr.r.ver.trust_model == opt.trust_model;
685 return yes_no;
688 byte
689 tdbio_read_model(void)
691 TRUSTREC vr;
692 int rc;
694 rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
695 if( rc )
696 log_fatal( _("%s: error reading version record: %s\n"),
697 db_name, g10_errstr(rc) );
698 return vr.r.ver.trust_model;
701 /****************
702 * Return the nextstamp value.
704 ulong
705 tdbio_read_nextcheck ()
707 TRUSTREC vr;
708 int rc;
710 rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
711 if( rc )
712 log_fatal( _("%s: error reading version record: %s\n"),
713 db_name, g10_errstr(rc) );
714 return vr.r.ver.nextcheck;
717 /* Return true when the stamp was actually changed. */
719 tdbio_write_nextcheck (ulong stamp)
721 TRUSTREC vr;
722 int rc;
724 rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
725 if( rc )
726 log_fatal( _("%s: error reading version record: %s\n"),
727 db_name, g10_errstr(rc) );
729 if (vr.r.ver.nextcheck == stamp)
730 return 0;
732 vr.r.ver.nextcheck = stamp;
733 rc = tdbio_write_record( &vr );
734 if( rc )
735 log_fatal( _("%s: error writing version record: %s\n"),
736 db_name, g10_errstr(rc) );
737 return 1;
742 /****************
743 * Return the record number of the trusthash tbl or create a new one.
745 static ulong
746 get_trusthashrec(void)
748 static ulong trusthashtbl; /* record number of the trust hashtable */
750 if( !trusthashtbl ) {
751 TRUSTREC vr;
752 int rc;
754 rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
755 if( rc )
756 log_fatal( _("%s: error reading version record: %s\n"),
757 db_name, g10_errstr(rc) );
758 if( !vr.r.ver.trusthashtbl )
759 create_hashtable( &vr, 0 );
761 trusthashtbl = vr.r.ver.trusthashtbl;
763 return trusthashtbl;
768 /****************
769 * Update a hashtable.
770 * table gives the start of the table, key and keylen is the key,
771 * newrecnum is the record number to insert.
773 static int
774 upd_hashtable( ulong table, byte *key, int keylen, ulong newrecnum )
776 TRUSTREC lastrec, rec;
777 ulong hashrec, item;
778 int msb;
779 int level=0;
780 int rc, i;
782 hashrec = table;
783 next_level:
784 msb = key[level];
785 hashrec += msb / ITEMS_PER_HTBL_RECORD;
786 rc = tdbio_read_record( hashrec, &rec, RECTYPE_HTBL );
787 if( rc ) {
788 log_error("upd_hashtable: read failed: %s\n", g10_errstr(rc) );
789 return rc;
792 item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
793 if( !item ) { /* insert a new item into the hash table */
794 rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = newrecnum;
795 rc = tdbio_write_record( &rec );
796 if( rc ) {
797 log_error("upd_hashtable: write htbl failed: %s\n",
798 g10_errstr(rc) );
799 return rc;
802 else if( item != newrecnum ) { /* must do an update */
803 lastrec = rec;
804 rc = tdbio_read_record( item, &rec, 0 );
805 if( rc ) {
806 log_error( "upd_hashtable: read item failed: %s\n",
807 g10_errstr(rc) );
808 return rc;
811 if( rec.rectype == RECTYPE_HTBL ) {
812 hashrec = item;
813 level++;
814 if( level >= keylen ) {
815 log_error( "hashtable has invalid indirections.\n");
816 return G10ERR_TRUSTDB;
818 goto next_level;
820 else if( rec.rectype == RECTYPE_HLST ) { /* extend list */
821 /* see whether the key is already in this list */
822 for(;;) {
823 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
824 if( rec.r.hlst.rnum[i] == newrecnum ) {
825 return 0; /* okay, already in the list */
828 if( rec.r.hlst.next ) {
829 rc = tdbio_read_record( rec.r.hlst.next,
830 &rec, RECTYPE_HLST);
831 if( rc ) {
832 log_error( "upd_hashtable: read hlst failed: %s\n",
833 g10_errstr(rc) );
834 return rc;
837 else
838 break; /* not there */
840 /* find the next free entry and put it in */
841 for(;;) {
842 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
843 if( !rec.r.hlst.rnum[i] ) {
844 rec.r.hlst.rnum[i] = newrecnum;
845 rc = tdbio_write_record( &rec );
846 if( rc )
847 log_error( "upd_hashtable: write hlst failed: %s\n",
848 g10_errstr(rc) );
849 return rc; /* done */
852 if( rec.r.hlst.next ) {
853 rc = tdbio_read_record( rec.r.hlst.next,
854 &rec, RECTYPE_HLST );
855 if( rc ) {
856 log_error( "upd_hashtable: read hlst failed: %s\n",
857 g10_errstr(rc) );
858 return rc;
861 else { /* add a new list record */
862 rec.r.hlst.next = item = tdbio_new_recnum();
863 rc = tdbio_write_record( &rec );
864 if( rc ) {
865 log_error( "upd_hashtable: write hlst failed: %s\n",
866 g10_errstr(rc) );
867 return rc;
869 memset( &rec, 0, sizeof rec );
870 rec.rectype = RECTYPE_HLST;
871 rec.recnum = item;
872 rec.r.hlst.rnum[0] = newrecnum;
873 rc = tdbio_write_record( &rec );
874 if( rc )
875 log_error( "upd_hashtable: write ext hlst failed: %s\n",
876 g10_errstr(rc) );
877 return rc; /* done */
879 } /* end loop over hlst slots */
881 else if( rec.rectype == RECTYPE_TRUST ) { /* insert a list record */
882 if( rec.recnum == newrecnum ) {
883 return 0;
885 item = rec.recnum; /* save number of key record */
886 memset( &rec, 0, sizeof rec );
887 rec.rectype = RECTYPE_HLST;
888 rec.recnum = tdbio_new_recnum();
889 rec.r.hlst.rnum[0] = item; /* old keyrecord */
890 rec.r.hlst.rnum[1] = newrecnum; /* and new one */
891 rc = tdbio_write_record( &rec );
892 if( rc ) {
893 log_error( "upd_hashtable: write new hlst failed: %s\n",
894 g10_errstr(rc) );
895 return rc;
897 /* update the hashtable record */
898 lastrec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = rec.recnum;
899 rc = tdbio_write_record( &lastrec );
900 if( rc )
901 log_error( "upd_hashtable: update htbl failed: %s\n",
902 g10_errstr(rc) );
903 return rc; /* ready */
905 else {
906 log_error( "hashtbl %lu: %lu/%d points to an invalid record %lu\n",
907 table, hashrec, (msb % ITEMS_PER_HTBL_RECORD), item);
908 list_trustdb(NULL);
909 return G10ERR_TRUSTDB;
913 return 0;
917 /****************
918 * Drop an entry from a hashtable
919 * table gives the start of the table, key and keylen is the key,
921 static int
922 drop_from_hashtable( ulong table, byte *key, int keylen, ulong recnum )
924 TRUSTREC rec;
925 ulong hashrec, item;
926 int msb;
927 int level=0;
928 int rc, i;
930 hashrec = table;
931 next_level:
932 msb = key[level];
933 hashrec += msb / ITEMS_PER_HTBL_RECORD;
934 rc = tdbio_read_record( hashrec, &rec, RECTYPE_HTBL );
935 if( rc ) {
936 log_error("drop_from_hashtable: read failed: %s\n",
937 g10_errstr(rc) );
938 return rc;
941 item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
942 if( !item ) /* not found - forget about it */
943 return 0;
945 if( item == recnum ) { /* tables points direct to the record */
946 rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = 0;
947 rc = tdbio_write_record( &rec );
948 if( rc )
949 log_error("drop_from_hashtable: write htbl failed: %s\n",
950 g10_errstr(rc) );
951 return rc;
954 rc = tdbio_read_record( item, &rec, 0 );
955 if( rc ) {
956 log_error( "drop_from_hashtable: read item failed: %s\n",
957 g10_errstr(rc) );
958 return rc;
961 if( rec.rectype == RECTYPE_HTBL ) {
962 hashrec = item;
963 level++;
964 if( level >= keylen ) {
965 log_error( "hashtable has invalid indirections.\n");
966 return G10ERR_TRUSTDB;
968 goto next_level;
971 if( rec.rectype == RECTYPE_HLST ) {
972 for(;;) {
973 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
974 if( rec.r.hlst.rnum[i] == recnum ) {
975 rec.r.hlst.rnum[i] = 0; /* drop */
976 rc = tdbio_write_record( &rec );
977 if( rc )
978 log_error("drop_from_hashtable: write htbl failed: %s\n",
979 g10_errstr(rc) );
980 return rc;
983 if( rec.r.hlst.next ) {
984 rc = tdbio_read_record( rec.r.hlst.next,
985 &rec, RECTYPE_HLST);
986 if( rc ) {
987 log_error( "drop_from_hashtable: read hlst failed: %s\n",
988 g10_errstr(rc) );
989 return rc;
992 else
993 return 0; /* key not in table */
997 log_error( "hashtbl %lu: %lu/%d points to wrong record %lu\n",
998 table, hashrec, (msb % ITEMS_PER_HTBL_RECORD), item);
999 return G10ERR_TRUSTDB;
1004 /****************
1005 * Lookup a record via the hashtable tablewith key/keylen and return the
1006 * result in rec. cmp() should return if the record is the desired one.
1007 * Returns -1 if not found, 0 if found or another errocode
1009 static int
1010 lookup_hashtable( ulong table, const byte *key, size_t keylen,
1011 int (*cmpfnc)(void*, const TRUSTREC *), void *cmpdata,
1012 TRUSTREC *rec )
1014 int rc;
1015 ulong hashrec, item;
1016 int msb;
1017 int level=0;
1019 hashrec = table;
1020 next_level:
1021 msb = key[level];
1022 hashrec += msb / ITEMS_PER_HTBL_RECORD;
1023 rc = tdbio_read_record( hashrec, rec, RECTYPE_HTBL );
1024 if( rc ) {
1025 log_error("lookup_hashtable failed: %s\n", g10_errstr(rc) );
1026 return rc;
1029 item = rec->r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
1030 if( !item )
1031 return -1; /* not found */
1033 rc = tdbio_read_record( item, rec, 0 );
1034 if( rc ) {
1035 log_error( "hashtable read failed: %s\n", g10_errstr(rc) );
1036 return rc;
1038 if( rec->rectype == RECTYPE_HTBL ) {
1039 hashrec = item;
1040 level++;
1041 if( level >= keylen ) {
1042 log_error("hashtable has invalid indirections\n");
1043 return G10ERR_TRUSTDB;
1045 goto next_level;
1047 else if( rec->rectype == RECTYPE_HLST ) {
1048 for(;;) {
1049 int i;
1051 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1052 if( rec->r.hlst.rnum[i] ) {
1053 TRUSTREC tmp;
1055 rc = tdbio_read_record( rec->r.hlst.rnum[i], &tmp, 0 );
1056 if( rc ) {
1057 log_error( "lookup_hashtable: read item failed: %s\n",
1058 g10_errstr(rc) );
1059 return rc;
1061 if( (*cmpfnc)( cmpdata, &tmp ) ) {
1062 *rec = tmp;
1063 return 0;
1067 if( rec->r.hlst.next ) {
1068 rc = tdbio_read_record( rec->r.hlst.next, rec, RECTYPE_HLST );
1069 if( rc ) {
1070 log_error( "lookup_hashtable: read hlst failed: %s\n",
1071 g10_errstr(rc) );
1072 return rc;
1075 else
1076 return -1; /* not found */
1081 if( (*cmpfnc)( cmpdata, rec ) )
1082 return 0; /* really found */
1084 return -1; /* no: not found */
1088 /****************
1089 * Update the trust hashtbl or create the table if it does not exist
1091 static int
1092 update_trusthashtbl( TRUSTREC *tr )
1094 return upd_hashtable( get_trusthashrec(),
1095 tr->r.trust.fingerprint, 20, tr->recnum );
1100 void
1101 tdbio_dump_record( TRUSTREC *rec, FILE *fp )
1103 int i;
1104 ulong rnum = rec->recnum;
1106 fprintf(fp, "rec %5lu, ", rnum );
1108 switch( rec->rectype ) {
1109 case 0: fprintf(fp, "blank\n");
1110 break;
1111 case RECTYPE_VER: fprintf(fp,
1112 "version, td=%lu, f=%lu, m/c/d=%d/%d/%d tm=%d nc=%lu (%s)\n",
1113 rec->r.ver.trusthashtbl,
1114 rec->r.ver.firstfree,
1115 rec->r.ver.marginals,
1116 rec->r.ver.completes,
1117 rec->r.ver.cert_depth,
1118 rec->r.ver.trust_model,
1119 rec->r.ver.nextcheck,
1120 strtimestamp(rec->r.ver.nextcheck)
1122 break;
1123 case RECTYPE_FREE: fprintf(fp, "free, next=%lu\n", rec->r.free.next );
1124 break;
1125 case RECTYPE_HTBL:
1126 fprintf(fp, "htbl,");
1127 for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ )
1128 fprintf(fp, " %lu", rec->r.htbl.item[i] );
1129 putc('\n', fp);
1130 break;
1131 case RECTYPE_HLST:
1132 fprintf(fp, "hlst, next=%lu,", rec->r.hlst.next );
1133 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ )
1134 fprintf(fp, " %lu", rec->r.hlst.rnum[i] );
1135 putc('\n', fp);
1136 break;
1137 case RECTYPE_TRUST:
1138 fprintf(fp, "trust ");
1139 for(i=0; i < 20; i++ )
1140 fprintf(fp, "%02X", rec->r.trust.fingerprint[i] );
1141 fprintf (fp, ", ot=%d, d=%d, vl=%lu\n", rec->r.trust.ownertrust,
1142 rec->r.trust.depth, rec->r.trust.validlist);
1143 break;
1144 case RECTYPE_VALID:
1145 fprintf(fp, "valid ");
1146 for(i=0; i < 20; i++ )
1147 fprintf(fp, "%02X", rec->r.valid.namehash[i] );
1148 fprintf (fp, ", v=%d, next=%lu\n", rec->r.valid.validity,
1149 rec->r.valid.next);
1150 break;
1151 default:
1152 fprintf(fp, "unknown type %d\n", rec->rectype );
1153 break;
1157 /****************
1158 * read the record with number recnum
1159 * returns: -1 on error, 0 on success
1162 tdbio_read_record( ulong recnum, TRUSTREC *rec, int expected )
1164 byte readbuf[TRUST_RECORD_LEN];
1165 const byte *buf, *p;
1166 gpg_error_t err = 0;
1167 int n, i;
1169 if( db_fd == -1 )
1170 open_db();
1171 buf = get_record_from_cache( recnum );
1172 if( !buf ) {
1173 if( lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
1174 err = gpg_error_from_syserror ();
1175 log_error(_("trustdb: lseek failed: %s\n"), strerror(errno) );
1176 return err;
1178 n = read( db_fd, readbuf, TRUST_RECORD_LEN);
1179 if( !n ) {
1180 return -1; /* eof */
1182 else if( n != TRUST_RECORD_LEN ) {
1183 err = gpg_error_from_syserror ();
1184 log_error(_("trustdb: read failed (n=%d): %s\n"), n,
1185 strerror(errno) );
1186 return err;
1188 buf = readbuf;
1190 rec->recnum = recnum;
1191 rec->dirty = 0;
1192 p = buf;
1193 rec->rectype = *p++;
1194 if( expected && rec->rectype != expected ) {
1195 log_error("%lu: read expected rec type %d, got %d\n",
1196 recnum, expected, rec->rectype );
1197 return gpg_error (GPG_ERR_TRUSTDB);
1199 p++; /* skip reserved byte */
1200 switch( rec->rectype ) {
1201 case 0: /* unused (free) record */
1202 break;
1203 case RECTYPE_VER: /* version record */
1204 if( memcmp(buf+1, "gpg", 3 ) ) {
1205 log_error( _("%s: not a trustdb file\n"), db_name );
1206 err = gpg_error (GPG_ERR_TRUSTDB);
1208 p += 2; /* skip "gpg" */
1209 rec->r.ver.version = *p++;
1210 rec->r.ver.marginals = *p++;
1211 rec->r.ver.completes = *p++;
1212 rec->r.ver.cert_depth = *p++;
1213 rec->r.ver.trust_model = *p++;
1214 p += 3;
1215 rec->r.ver.created = buftoulong(p); p += 4;
1216 rec->r.ver.nextcheck = buftoulong(p); p += 4;
1217 p += 4;
1218 p += 4;
1219 rec->r.ver.firstfree =buftoulong(p); p += 4;
1220 p += 4;
1221 rec->r.ver.trusthashtbl =buftoulong(p); p += 4;
1222 if( recnum ) {
1223 log_error( _("%s: version record with recnum %lu\n"), db_name,
1224 (ulong)recnum );
1225 err = gpg_error (GPG_ERR_TRUSTDB);
1227 else if( rec->r.ver.version != 3 ) {
1228 log_error( _("%s: invalid file version %d\n"), db_name,
1229 rec->r.ver.version );
1230 err = gpg_error (GPG_ERR_TRUSTDB);
1232 break;
1233 case RECTYPE_FREE:
1234 rec->r.free.next = buftoulong(p); p += 4;
1235 break;
1236 case RECTYPE_HTBL:
1237 for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
1238 rec->r.htbl.item[i] = buftoulong(p); p += 4;
1240 break;
1241 case RECTYPE_HLST:
1242 rec->r.hlst.next = buftoulong(p); p += 4;
1243 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1244 rec->r.hlst.rnum[i] = buftoulong(p); p += 4;
1246 break;
1247 case RECTYPE_TRUST:
1248 memcpy( rec->r.trust.fingerprint, p, 20); p+=20;
1249 rec->r.trust.ownertrust = *p++;
1250 rec->r.trust.depth = *p++;
1251 rec->r.trust.min_ownertrust = *p++;
1252 p++;
1253 rec->r.trust.validlist = buftoulong(p); p += 4;
1254 break;
1255 case RECTYPE_VALID:
1256 memcpy( rec->r.valid.namehash, p, 20); p+=20;
1257 rec->r.valid.validity = *p++;
1258 rec->r.valid.next = buftoulong(p); p += 4;
1259 rec->r.valid.full_count = *p++;
1260 rec->r.valid.marginal_count = *p++;
1261 break;
1262 default:
1263 log_error( "%s: invalid record type %d at recnum %lu\n",
1264 db_name, rec->rectype, (ulong)recnum );
1265 err = gpg_error (GPG_ERR_TRUSTDB);
1266 break;
1269 return err;
1272 /****************
1273 * Write the record at RECNUM
1276 tdbio_write_record( TRUSTREC *rec )
1278 byte buf[TRUST_RECORD_LEN], *p;
1279 int rc = 0;
1280 int i;
1281 ulong recnum = rec->recnum;
1283 if( db_fd == -1 )
1284 open_db();
1286 memset(buf, 0, TRUST_RECORD_LEN);
1287 p = buf;
1288 *p++ = rec->rectype; p++;
1289 switch( rec->rectype ) {
1290 case 0: /* unused record */
1291 break;
1292 case RECTYPE_VER: /* version record */
1293 if( recnum )
1294 BUG();
1295 memcpy(p-1, "gpg", 3 ); p += 2;
1296 *p++ = rec->r.ver.version;
1297 *p++ = rec->r.ver.marginals;
1298 *p++ = rec->r.ver.completes;
1299 *p++ = rec->r.ver.cert_depth;
1300 *p++ = rec->r.ver.trust_model;
1301 p += 3;
1302 ulongtobuf(p, rec->r.ver.created); p += 4;
1303 ulongtobuf(p, rec->r.ver.nextcheck); p += 4;
1304 p += 4;
1305 p += 4;
1306 ulongtobuf(p, rec->r.ver.firstfree ); p += 4;
1307 p += 4;
1308 ulongtobuf(p, rec->r.ver.trusthashtbl ); p += 4;
1309 break;
1311 case RECTYPE_FREE:
1312 ulongtobuf(p, rec->r.free.next); p += 4;
1313 break;
1316 case RECTYPE_HTBL:
1317 for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
1318 ulongtobuf( p, rec->r.htbl.item[i]); p += 4;
1320 break;
1322 case RECTYPE_HLST:
1323 ulongtobuf( p, rec->r.hlst.next); p += 4;
1324 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1325 ulongtobuf( p, rec->r.hlst.rnum[i]); p += 4;
1327 break;
1329 case RECTYPE_TRUST:
1330 memcpy( p, rec->r.trust.fingerprint, 20); p += 20;
1331 *p++ = rec->r.trust.ownertrust;
1332 *p++ = rec->r.trust.depth;
1333 *p++ = rec->r.trust.min_ownertrust;
1334 p++;
1335 ulongtobuf( p, rec->r.trust.validlist); p += 4;
1336 break;
1338 case RECTYPE_VALID:
1339 memcpy( p, rec->r.valid.namehash, 20); p += 20;
1340 *p++ = rec->r.valid.validity;
1341 ulongtobuf( p, rec->r.valid.next); p += 4;
1342 *p++ = rec->r.valid.full_count;
1343 *p++ = rec->r.valid.marginal_count;
1344 break;
1346 default:
1347 BUG();
1350 rc = put_record_into_cache( recnum, buf );
1351 if( rc )
1353 else if( rec->rectype == RECTYPE_TRUST )
1354 rc = update_trusthashtbl( rec );
1356 return rc;
1360 tdbio_delete_record( ulong recnum )
1362 TRUSTREC vr, rec;
1363 int rc;
1365 /* Must read the record fist, so we can drop it from the hash tables */
1366 rc = tdbio_read_record( recnum, &rec, 0 );
1367 if( rc )
1369 else if( rec.rectype == RECTYPE_TRUST ) {
1370 rc = drop_from_hashtable( get_trusthashrec(),
1371 rec.r.trust.fingerprint, 20, rec.recnum );
1374 if( rc )
1375 return rc;
1377 /* now we can chnage it to a free record */
1378 rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
1379 if( rc )
1380 log_fatal( _("%s: error reading version record: %s\n"),
1381 db_name, g10_errstr(rc) );
1383 rec.recnum = recnum;
1384 rec.rectype = RECTYPE_FREE;
1385 rec.r.free.next = vr.r.ver.firstfree;
1386 vr.r.ver.firstfree = recnum;
1387 rc = tdbio_write_record( &rec );
1388 if( !rc )
1389 rc = tdbio_write_record( &vr );
1390 return rc;
1393 /****************
1394 * create a new record and return its record number
1396 ulong
1397 tdbio_new_recnum()
1399 off_t offset;
1400 ulong recnum;
1401 TRUSTREC vr, rec;
1402 int rc;
1404 /* look for unused records */
1405 rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
1406 if( rc )
1407 log_fatal( _("%s: error reading version record: %s\n"),
1408 db_name, g10_errstr(rc) );
1409 if( vr.r.ver.firstfree ) {
1410 recnum = vr.r.ver.firstfree;
1411 rc = tdbio_read_record( recnum, &rec, RECTYPE_FREE );
1412 if( rc ) {
1413 log_error( _("%s: error reading free record: %s\n"),
1414 db_name, g10_errstr(rc) );
1415 return rc;
1417 /* update dir record */
1418 vr.r.ver.firstfree = rec.r.free.next;
1419 rc = tdbio_write_record( &vr );
1420 if( rc ) {
1421 log_error( _("%s: error writing dir record: %s\n"),
1422 db_name, g10_errstr(rc) );
1423 return rc;
1425 /*zero out the new record */
1426 memset( &rec, 0, sizeof rec );
1427 rec.rectype = 0; /* unused record */
1428 rec.recnum = recnum;
1429 rc = tdbio_write_record( &rec );
1430 if( rc )
1431 log_fatal(_("%s: failed to zero a record: %s\n"),
1432 db_name, g10_errstr(rc));
1434 else { /* not found, append a new record */
1435 offset = lseek( db_fd, 0, SEEK_END );
1436 if( offset == -1 )
1437 log_fatal("trustdb: lseek to end failed: %s\n", strerror(errno) );
1438 recnum = offset / TRUST_RECORD_LEN;
1439 assert(recnum); /* this is will never be the first record */
1440 /* we must write a record, so that the next call to this function
1441 * returns another recnum */
1442 memset( &rec, 0, sizeof rec );
1443 rec.rectype = 0; /* unused record */
1444 rec.recnum = recnum;
1445 rc = 0;
1446 if( lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
1447 rc = gpg_error_from_syserror ();
1448 log_error(_("trustdb rec %lu: lseek failed: %s\n"),
1449 recnum, strerror(errno) );
1451 else {
1452 int n = write( db_fd, &rec, TRUST_RECORD_LEN);
1453 if( n != TRUST_RECORD_LEN ) {
1454 rc = gpg_error_from_syserror ();
1455 log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
1456 recnum, n, strerror(errno) );
1460 if( rc )
1461 log_fatal(_("%s: failed to append a record: %s\n"),
1462 db_name, g10_errstr(rc));
1464 return recnum ;
1469 static int
1470 cmp_trec_fpr ( void *fpr, const TRUSTREC *rec )
1472 return rec->rectype == RECTYPE_TRUST
1473 && !memcmp( rec->r.trust.fingerprint, fpr, 20);
1478 tdbio_search_trust_byfpr( const byte *fingerprint, TRUSTREC *rec )
1480 int rc;
1482 /* locate the trust record using the hash table */
1483 rc = lookup_hashtable( get_trusthashrec(), fingerprint, 20,
1484 cmp_trec_fpr, (void*)fingerprint, rec );
1485 return rc;
1489 tdbio_search_trust_bypk (PKT_public_key *pk, TRUSTREC *rec)
1491 byte fingerprint[MAX_FINGERPRINT_LEN];
1492 size_t fingerlen;
1494 fingerprint_from_pk( pk, fingerprint, &fingerlen );
1495 for (; fingerlen < 20; fingerlen++ )
1496 fingerprint[fingerlen] = 0;
1497 return tdbio_search_trust_byfpr (fingerprint, rec);
1502 void
1503 tdbio_invalid(void)
1505 log_error(_(
1506 "the trustdb is corrupted; please run \"gpg --fix-trustdb\".\n") );
1507 g10_exit(2);