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