6aaa18012521ea37bc434918cee4c34313ca12f2
[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
86 static void open_db(void);
87
88 \f
89 /*************************************
90  ************* record cache **********
91  *************************************/
92
93 /****************
94  * Get the data from therecord cache and return a
95  * pointer into that cache.  Caller should copy
96  * the return data.  NULL is returned on a cache miss.
97  */
98 static const char *
99 get_record_from_cache( ulong recno )
100 {
101     CACHE_CTRL r;
102
103     for( r = cache_list; r; r = r->next ) {
104         if( r->flags.used && r->recno == recno )
105             return r->data;
106     }
107     return NULL;
108 }
109
110
111 static int
112 write_cache_item( CACHE_CTRL r )
113 {
114     int n;
115
116     if( lseek( db_fd, r->recno * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
117         log_error(_("trustdb rec %lu: lseek failed: %s\n"),
118                                             r->recno, strerror(errno) );
119         return G10ERR_WRITE_FILE;
120     }
121     n = write( db_fd, r->data, TRUST_RECORD_LEN);
122     if( n != TRUST_RECORD_LEN ) {
123         log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
124                                             r->recno, n, strerror(errno) );
125         return G10ERR_WRITE_FILE;
126     }
127     r->flags.dirty = 0;
128     return 0;
129 }
130
131 /****************
132  * Put data into the cache.  This function may flush the
133  * some cache entries if there is not enough space available.
134  */
135 int
136 put_record_into_cache( ulong recno, const char *data )
137 {
138     CACHE_CTRL r, unused;
139     int dirty_count = 0;
140     int clean_count = 0;
141
142     /* see whether we already cached this one */
143     for( unused = NULL, r = cache_list; r; r = r->next ) {
144         if( !r->flags.used ) {
145             if( !unused )
146                 unused = r;
147         }
148         else if( r->recno == recno ) {
149             if( !r->flags.dirty ) {
150                 /* Hmmm: should we use a a copy and compare? */
151                 if( memcmp(r->data, data, TRUST_RECORD_LEN ) ) {
152                     r->flags.dirty = 1;
153                     cache_is_dirty = 1;
154                 }
155             }
156             memcpy( r->data, data, TRUST_RECORD_LEN );
157             return 0;
158         }
159         if( r->flags.used ) {
160             if( r->flags.dirty )
161                 dirty_count++;
162             else
163                 clean_count++;
164         }
165     }
166     /* not in the cache: add a new entry */
167     if( unused ) { /* reuse this entry */
168         r = unused;
169         r->flags.used = 1;
170         r->recno = recno;
171         memcpy( r->data, data, TRUST_RECORD_LEN );
172         r->flags.dirty = 1;
173         cache_is_dirty = 1;
174         cache_entries++;
175         return 0;
176     }
177     /* see whether we reached the limit */
178     if( cache_entries < MAX_CACHE_ENTRIES_SOFT ) { /* no */
179         r = m_alloc( sizeof *r );
180         r->flags.used = 1;
181         r->recno = recno;
182         memcpy( r->data, data, TRUST_RECORD_LEN );
183         r->flags.dirty = 1;
184         r->next = cache_list;
185         cache_list = r;
186         cache_is_dirty = 1;
187         cache_entries++;
188         return 0;
189     }
190     /* cache is full: discard some clean entries */
191     if( clean_count ) {
192         int n = clean_count / 3; /* discard a third of the clean entries */
193         if( !n )
194             n = 1;
195         for( unused = NULL, r = cache_list; r; r = r->next ) {
196             if( r->flags.used && !r->flags.dirty ) {
197                 if( !unused )
198                     unused = r;
199                 r->flags.used = 0;
200                 cache_entries--;
201                 if( !--n )
202                     break;
203             }
204         }
205         assert( unused );
206         r = unused;
207         r->flags.used = 1;
208         r->recno = recno;
209         memcpy( r->data, data, TRUST_RECORD_LEN );
210         r->flags.dirty = 1;
211         cache_is_dirty = 1;
212         cache_entries++;
213         return 0;
214     }
215     /* no clean entries: have to flush some dirty entries */
216     if( in_transaction ) {
217         /* but we can't do this while in a transaction
218          * we increase the cache size instead */
219         if( cache_entries < MAX_CACHE_ENTRIES_HARD ) { /* no */
220             if( opt.debug && !(cache_entries % 100) )
221                 log_debug("increasing tdbio cache size\n");
222             r = m_alloc( sizeof *r );
223             r->flags.used = 1;
224             r->recno = recno;
225             memcpy( r->data, data, TRUST_RECORD_LEN );
226             r->flags.dirty = 1;
227             r->next = cache_list;
228             cache_list = r;
229             cache_is_dirty = 1;
230             cache_entries++;
231             return 0;
232         }
233         log_info(_("trustdb transaction too large\n"));
234         return G10ERR_RESOURCE_LIMIT;
235     }
236     if( dirty_count ) {
237         int n = dirty_count / 5; /* discard some dirty entries */
238         if( !n )
239             n = 1;
240         if( !is_locked ) {
241             if( make_dotlock( lockhandle, -1 ) )
242                 log_fatal("can't acquire lock - giving up\n");
243             else
244                 is_locked = 1;
245         }
246         for( unused = NULL, r = cache_list; r; r = r->next ) {
247             if( r->flags.used && r->flags.dirty ) {
248                 int rc = write_cache_item( r );
249                 if( rc )
250                     return rc;
251                 if( !unused )
252                     unused = r;
253                 r->flags.used = 0;
254                 cache_entries--;
255                 if( !--n )
256                     break;
257             }
258         }
259         if( !opt.lock_once ) {
260             if( !release_dotlock( lockhandle ) )
261                 is_locked = 0;
262         }
263         assert( unused );
264         r = unused;
265         r->flags.used = 1;
266         r->recno = recno;
267         memcpy( r->data, data, TRUST_RECORD_LEN );
268         r->flags.dirty = 1;
269         cache_is_dirty = 1;
270         cache_entries++;
271         return 0;
272     }
273     BUG();
274 }
275
276
277 int
278 tdbio_is_dirty()
279 {
280     return cache_is_dirty;
281 }
282
283
284 /****************
285  * Flush the cache.  This cannot be used while in a transaction.
286  */
287 int
288 tdbio_sync()
289 {
290     CACHE_CTRL r;
291     int did_lock = 0;
292
293     if( db_fd == -1 )
294         open_db();
295     if( in_transaction )
296         log_bug("tdbio: syncing while in transaction\n");
297
298     if( !cache_is_dirty )
299         return 0;
300
301     if( !is_locked ) {
302         if( make_dotlock( lockhandle, -1 ) )
303             log_fatal("can't acquire lock - giving up\n");
304         else
305             is_locked = 1;
306         did_lock = 1;
307     }
308     for( r = cache_list; r; r = r->next ) {
309         if( r->flags.used && r->flags.dirty ) {
310             int rc = write_cache_item( r );
311             if( rc )
312                 return rc;
313         }
314     }
315     cache_is_dirty = 0;
316     if( did_lock && !opt.lock_once ) {
317         if( !release_dotlock( lockhandle ) )
318             is_locked = 0;
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
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             log_info(_("%s: trustdb created\n"), db_name);
493
494             return 0;
495         }
496     }
497     m_free(db_name);
498     db_name = fname;
499     return 0;
500 }
501
502
503 const char *
504 tdbio_get_dbname()
505 {
506     return db_name;
507 }
508
509
510
511 static void
512 open_db()
513 {
514     TRUSTREC rec;
515     assert( db_fd == -1 );
516
517     lockhandle = create_dotlock( db_name );
518     if( !lockhandle )
519         log_fatal( _("%s: can't create lock\n"), db_name );
520   #ifdef HAVE_DOSISH_SYSTEM
521     db_fd = open( db_name, O_RDWR | O_BINARY );
522   #else
523     db_fd = open( db_name, O_RDWR );
524   #endif
525     if( db_fd == -1 )
526         log_fatal( _("%s: can't open: %s\n"), db_name, strerror(errno) );
527     if( tdbio_read_record( 0, &rec, RECTYPE_VER ) )
528         log_fatal( _("%s: invalid trustdb\n"), db_name );
529 }
530
531
532 /****************
533  * Make a hashtable: type 0 = key hash, 1 = sdir hash
534  */
535 static void
536 create_hashtable( TRUSTREC *vr, int type )
537 {
538     TRUSTREC rec;
539     off_t offset;
540     ulong recnum;
541     int i, n, rc;
542
543     offset = lseek( db_fd, 0, SEEK_END );
544     if( offset == -1 )
545         log_fatal("trustdb: lseek to end failed: %s\n", strerror(errno) );
546     recnum = offset / TRUST_RECORD_LEN;
547     assert(recnum); /* this is will never be the first record */
548
549     if( !type )
550         vr->r.ver.keyhashtbl = recnum;
551     else
552         vr->r.ver.sdirhashtbl = recnum;
553     /* Now write the records */
554     n = (256+ITEMS_PER_HTBL_RECORD-1) / ITEMS_PER_HTBL_RECORD;
555     for(i=0; i < n; i++, recnum++ ) {
556          memset( &rec, 0, sizeof rec );
557          rec.rectype = RECTYPE_HTBL;
558          rec.recnum = recnum;
559          rc = tdbio_write_record( &rec );
560          if( rc )
561              log_fatal( _("%s: failed to create hashtable: %s\n"),
562                                         db_name, g10_errstr(rc));
563     }
564     /* update the version record */
565     rc = tdbio_write_record( vr );
566     if( !rc )
567         rc = tdbio_sync();
568     if( rc )
569         log_fatal( _("%s: error updating version record: %s\n"),
570                                                   db_name, g10_errstr(rc));
571 }
572
573
574 int
575 tdbio_db_matches_options()
576 {
577     static int yes_no = -1;
578
579     if( yes_no == -1 ) {
580         TRUSTREC vr;
581         int rc;
582
583         rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
584         if( rc )
585             log_fatal( _("%s: error reading version record: %s\n"),
586                                                     db_name, g10_errstr(rc) );
587
588         if( !vr.r.ver.marginals && !vr.r.ver.completes
589                                 && !vr.r.ver.cert_depth )
590         {   /* special hack for trustdbs created by old versions of GnuPG */
591             vr.r.ver.marginals =  opt.marginals_needed;
592             vr.r.ver.completes =  opt.completes_needed;
593             vr.r.ver.cert_depth = opt.max_cert_depth;
594             rc = tdbio_write_record( &vr );
595             if( !rc && !in_transaction )
596                 rc = tdbio_sync();
597             if( rc )
598                 log_error( _("%s: error writing version record: %s\n"),
599                                                 db_name, g10_errstr(rc) );
600         }
601
602         yes_no = vr.r.ver.marginals == opt.marginals_needed
603                  && vr.r.ver.completes == opt.completes_needed
604                  && vr.r.ver.cert_depth == opt.max_cert_depth;
605     }
606     return yes_no;
607 }
608
609
610 /****************
611  * Return the record number of the keyhash tbl or create a new one.
612  */
613 static ulong
614 get_keyhashrec()
615 {
616     static ulong keyhashtbl; /* record number of the key hashtable */
617
618     if( !keyhashtbl ) {
619         TRUSTREC vr;
620         int rc;
621
622         rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
623         if( rc )
624             log_fatal( _("%s: error reading version record: %s\n"),
625                                             db_name, g10_errstr(rc) );
626         if( !vr.r.ver.keyhashtbl )
627             create_hashtable( &vr, 0 );
628
629         keyhashtbl = vr.r.ver.keyhashtbl;
630     }
631     return keyhashtbl;
632 }
633
634 /****************
635  * Return the record number of the shadow direcory hash table
636  * or create a new one.
637  */
638 static ulong
639 get_sdirhashrec()
640 {
641     static ulong sdirhashtbl; /* record number of the hashtable */
642
643     if( !sdirhashtbl ) {
644         TRUSTREC vr;
645         int rc;
646
647         rc = tdbio_read_record( 0, &vr, RECTYPE_VER );
648         if( rc )
649             log_fatal( _("%s: error reading version record: %s\n"),
650                                                     db_name, g10_errstr(rc) );
651         if( !vr.r.ver.sdirhashtbl )
652             create_hashtable( &vr, 1 );
653
654         sdirhashtbl = vr.r.ver.sdirhashtbl;
655     }
656     return sdirhashtbl;
657 }
658
659
660 /****************
661  * Update a hashtable.
662  * table gives the start of the table, key and keylen is the key,
663  * newrecnum is the record number to insert.
664  */
665 static int
666 upd_hashtable( ulong table, byte *key, int keylen, ulong newrecnum )
667 {
668     TRUSTREC lastrec, rec;
669     ulong hashrec, item;
670     int msb;
671     int level=0;
672     int rc, i;
673
674     hashrec = table;
675   next_level:
676     msb = key[level];
677     hashrec += msb / ITEMS_PER_HTBL_RECORD;
678     rc = tdbio_read_record( hashrec, &rec, RECTYPE_HTBL );
679     if( rc ) {
680         log_error( db_name, "upd_hashtable: read failed: %s\n",
681                                                         g10_errstr(rc) );
682         return rc;
683     }
684
685     item = rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
686     if( !item ) { /* insert a new item into the hash table */
687         rec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = newrecnum;
688         rc = tdbio_write_record( &rec );
689         if( rc ) {
690             log_error( db_name, "upd_hashtable: write htbl failed: %s\n",
691                                                             g10_errstr(rc) );
692             return rc;
693         }
694     }
695     else if( item != newrecnum ) {  /* must do an update */
696         lastrec = rec;
697         rc = tdbio_read_record( item, &rec, 0 );
698         if( rc ) {
699             log_error( "upd_hashtable: read item failed: %s\n",
700                                                             g10_errstr(rc) );
701             return rc;
702         }
703
704         if( rec.rectype == RECTYPE_HTBL ) {
705             hashrec = item;
706             level++;
707             if( level >= keylen ) {
708                 log_error( "hashtable has invalid indirections.\n");
709                 return G10ERR_TRUSTDB;
710             }
711             goto next_level;
712         }
713         else if( rec.rectype == RECTYPE_HLST ) { /* extend list */
714             /* see whether the key is already in this list */
715             for(;;) {
716                 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
717                     if( rec.r.hlst.rnum[i] == newrecnum ) {
718                         return 0; /* okay, already in the list */
719                     }
720                 }
721                 if( rec.r.hlst.next ) {
722                     rc = tdbio_read_record( rec.r.hlst.next,
723                                                        &rec, RECTYPE_HLST);
724                     if( rc ) {
725                         log_error( "scan keyhashtbl read hlst failed: %s\n",
726                                                              g10_errstr(rc) );
727                         return rc;
728                     }
729                 }
730                 else
731                     break; /* not there */
732             }
733             /* find the next free entry and put it in */
734             for(;;) {
735                 for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
736                     if( !rec.r.hlst.rnum[i] ) {
737                         rec.r.hlst.rnum[i] = newrecnum;
738                         rc = tdbio_write_record( &rec );
739                         if( rc )
740                             log_error( "upd_hashtable: write hlst failed: %s\n",
741                                                               g10_errstr(rc) );
742                         return rc; /* done */
743                     }
744                 }
745                 if( rec.r.hlst.next ) {
746                     rc = tdbio_read_record( rec.r.hlst.next,
747                                                       &rec, RECTYPE_HLST );
748                     if( rc ) {
749                         log_error( "upd_hashtable: read hlst failed: %s\n",
750                                                              g10_errstr(rc) );
751                         return rc;
752                     }
753                 }
754                 else { /* add a new list record */
755                     rec.r.hlst.next = item = tdbio_new_recnum();
756                     rc = tdbio_write_record( &rec );
757                     if( rc ) {
758                         log_error( "upd_hashtable: write hlst failed: %s\n",
759                                                           g10_errstr(rc) );
760                         return rc;
761                     }
762                     memset( &rec, 0, sizeof rec );
763                     rec.rectype = RECTYPE_HLST;
764                     rec.recnum = item;
765                     rec.r.hlst.rnum[0] = newrecnum;
766                     rc = tdbio_write_record( &rec );
767                     if( rc )
768                         log_error( "upd_hashtable: write ext hlst failed: %s\n",
769                                                           g10_errstr(rc) );
770                     return rc; /* done */
771                 }
772             } /* end loop over hlst slots */
773         }
774         else if( rec.rectype == RECTYPE_KEY
775                  || rec.rectype == RECTYPE_DIR
776                  || rec.rectype == RECTYPE_SDIR ) { /* insert a list record */
777             if( rec.recnum == newrecnum ) {
778                 return 0;
779             }
780             item = rec.recnum; /* save number of key record */
781             memset( &rec, 0, sizeof rec );
782             rec.rectype = RECTYPE_HLST;
783             rec.recnum = tdbio_new_recnum();
784             rec.r.hlst.rnum[0] = item;       /* old keyrecord */
785             rec.r.hlst.rnum[1] = newrecnum; /* and new one */
786             rc = tdbio_write_record( &rec );
787             if( rc ) {
788                 log_error( "upd_hashtable: write new hlst failed: %s\n",
789                                                   g10_errstr(rc) );
790                 return rc;
791             }
792             /* update the hashtable record */
793             lastrec.r.htbl.item[msb % ITEMS_PER_HTBL_RECORD] = rec.recnum;
794             rc = tdbio_write_record( &lastrec );
795             if( rc )
796                 log_error( "upd_hashtable: update htbl failed: %s\n",
797                                                              g10_errstr(rc) );
798             return rc; /* ready */
799         }
800         else {
801             log_error( "hashtbl %lu points to an invalid record\n",
802                                                                     item);
803             return G10ERR_TRUSTDB;
804         }
805     }
806
807     return 0;
808 }
809
810
811
812 /****************
813  * Lookup a record via the hashtable tablewith key/keylen and return the
814  * result in rec.  cmp() should return if the record is the desired one.
815  * Returns -1 if not found, 0 if found or another errocode
816  */
817 static int
818 lookup_hashtable( ulong table, const byte *key, size_t keylen,
819                   int (*cmpfnc)(void*, const TRUSTREC *), void *cmpdata,
820                                                 TRUSTREC *rec )
821 {
822     int rc;
823     ulong hashrec, item;
824     int msb;
825     int level=0;
826
827     hashrec = table;
828   next_level:
829     msb = key[level];
830     hashrec += msb / ITEMS_PER_HTBL_RECORD;
831     rc = tdbio_read_record( hashrec, rec, RECTYPE_HTBL );
832     if( rc ) {
833         log_error( db_name, "lookup_hashtable failed: %s\n", g10_errstr(rc) );
834         return rc;
835     }
836
837     item = rec->r.htbl.item[msb % ITEMS_PER_HTBL_RECORD];
838     if( !item )
839         return -1; /* not found */
840
841     rc = tdbio_read_record( item, rec, 0 );
842     if( rc ) {
843         log_error( db_name, "hashtable read failed: %s\n", g10_errstr(rc) );
844         return rc;
845     }
846     if( rec->rectype == RECTYPE_HTBL ) {
847         hashrec = item;
848         level++;
849         if( level >= keylen ) {
850             log_error( db_name, "hashtable has invalid indirections\n");
851             return G10ERR_TRUSTDB;
852         }
853         goto next_level;
854     }
855     else if( rec->rectype == RECTYPE_HLST ) {
856         for(;;) {
857             int i;
858
859             for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
860                 if( rec->r.hlst.rnum[i] ) {
861                     TRUSTREC tmp;
862
863                     rc = tdbio_read_record( rec->r.hlst.rnum[i], &tmp, 0 );
864                     if( rc ) {
865                         log_error( "lookup_hashtable: read item failed: %s\n",
866                                                               g10_errstr(rc) );
867                         return rc;
868                     }
869                     if( (*cmpfnc)( cmpdata, &tmp ) ) {
870                         *rec = tmp;
871                         return 0;
872                     }
873                 }
874             }
875             if( rec->r.hlst.next ) {
876                 rc = tdbio_read_record( rec->r.hlst.next, rec, RECTYPE_HLST );
877                 if( rc ) {
878                     log_error( "lookup_hashtable: read hlst failed: %s\n",
879                                                          g10_errstr(rc) );
880                     return rc;
881                 }
882             }
883             else
884                 return -1; /* not found */
885         }
886     }
887
888
889     if( (*cmpfnc)( cmpdata, rec ) )
890         return 0; /* really found */
891
892     return -1; /* no: not found */
893 }
894
895
896
897
898 /****************
899  * Update the key hashtbl or create the table if it does not exist
900  */
901 static int
902 update_keyhashtbl( TRUSTREC *kr )
903 {
904     return upd_hashtable( get_keyhashrec(),
905                           kr->r.key.fingerprint,
906                           kr->r.key.fingerprint_len, kr->recnum );
907 }
908
909 /****************
910  * Update the shadow dir hashtbl or create the table if it does not exist
911  */
912 static int
913 update_sdirhashtbl( TRUSTREC *sr )
914 {
915     byte key[8];
916
917     u32tobuf( key   , sr->r.sdir.keyid[0] );
918     u32tobuf( key+4 , sr->r.sdir.keyid[1] );
919     return upd_hashtable( get_sdirhashrec(), key, 8, sr->recnum );
920 }
921
922
923
924
925 void
926 tdbio_dump_record( TRUSTREC *rec, FILE *fp  )
927 {
928     int i;
929     ulong rnum = rec->recnum;
930     byte *p;
931
932     fprintf(fp, "rec %5lu, ", rnum );
933
934     switch( rec->rectype ) {
935       case 0: fprintf(fp, "blank\n");
936         break;
937       case RECTYPE_VER: fprintf(fp,
938             "version, kd=%lu, sd=%lu, free=%lu, m/c/d=%d/%d/%d\n",
939             rec->r.ver.keyhashtbl, rec->r.ver.sdirhashtbl,
940                                    rec->r.ver.firstfree,
941                                    rec->r.ver.marginals,
942                                    rec->r.ver.completes,
943                                    rec->r.ver.cert_depth );
944         break;
945       case RECTYPE_FREE: fprintf(fp, "free, next=%lu\n", rec->r.free.next );
946         break;
947       case RECTYPE_DIR:
948         fprintf(fp, "dir %lu, keys=%lu, uids=%lu, t=%02x",
949                     rec->r.dir.lid,
950                     rec->r.dir.keylist,
951                     rec->r.dir.uidlist,
952                     rec->r.dir.ownertrust );
953         if( rec->r.dir.dirflags & DIRF_VALVALID )
954             fprintf( fp, ", v=%02x", rec->r.dir.validity );
955         if( rec->r.dir.dirflags & DIRF_CHECKED ) {
956             if( rec->r.dir.dirflags & DIRF_VALID )
957                 fputs(", valid", fp );
958             if( rec->r.dir.dirflags & DIRF_EXPIRED )
959                 fputs(", expired", fp );
960             if( rec->r.dir.dirflags & DIRF_REVOKED )
961                 fputs(", revoked", fp );
962         }
963         putc('\n', fp);
964         break;
965       case RECTYPE_KEY:
966         fprintf(fp, "key %lu, n=%lu a=%d ",
967                    rec->r.key.lid,
968                    rec->r.key.next,
969                    rec->r.key.pubkey_algo );
970         for(i=0; i < rec->r.key.fingerprint_len; i++ )
971             fprintf(fp, "%02X", rec->r.key.fingerprint[i] );
972         if( rec->r.key.keyflags & KEYF_CHECKED ) {
973             if( rec->r.key.keyflags & KEYF_VALID )
974                 fputs(", valid", fp );
975             if( rec->r.key.keyflags & KEYF_EXPIRED )
976                 fputs(", expired", fp );
977             if( rec->r.key.keyflags & KEYF_REVOKED )
978                 fputs(", revoked", fp );
979         }
980         putc('\n', fp);
981         break;
982       case RECTYPE_UID:
983         fprintf(fp, "uid %lu, next=%lu, pref=%lu, sig=%lu, hash=%02X%02X",
984                     rec->r.uid.lid,
985                     rec->r.uid.next,
986                     rec->r.uid.prefrec,
987                     rec->r.uid.siglist,
988                     rec->r.uid.namehash[18], rec->r.uid.namehash[19]);
989         if( rec->r.uid.uidflags & UIDF_VALVALID )
990             fprintf( fp, ", v=%02x", rec->r.uid.validity );
991         if( rec->r.uid.uidflags & UIDF_CHECKED ) {
992             if( rec->r.uid.uidflags & UIDF_VALID )
993                 fputs(", valid", fp );
994             if( rec->r.uid.uidflags & UIDF_REVOKED )
995                 fputs(", revoked", fp );
996         }
997         putc('\n', fp);
998         break;
999       case RECTYPE_PREF:
1000         fprintf(fp, "pref %lu, next=%lu,",
1001                     rec->r.pref.lid, rec->r.pref.next);
1002         for(i=0,p=rec->r.pref.data; i < ITEMS_PER_PREF_RECORD; i+=2,p+=2 ) {
1003             if( *p )
1004                 fprintf(fp, " %c%d", *p == PREFTYPE_SYM    ? 'S' :
1005                                      *p == PREFTYPE_HASH   ? 'H' :
1006                                      *p == PREFTYPE_COMPR  ? 'Z' : '?', p[1]);
1007         }
1008         putc('\n', fp);
1009         break;
1010       case RECTYPE_SIG:
1011         fprintf(fp, "sig %lu, next=%lu,",
1012                          rec->r.sig.lid, rec->r.sig.next );
1013         for(i=0; i < SIGS_PER_RECORD; i++ ) {
1014             if( rec->r.sig.sig[i].lid ) {
1015                 fprintf(fp, " %lu:", rec->r.sig.sig[i].lid );
1016                 if( rec->r.sig.sig[i].flag & SIGF_CHECKED ) {
1017                     fprintf(fp,"%c%c%c",
1018                        (rec->r.sig.sig[i].flag & SIGF_VALID)   ? 'V':'-',
1019                        (rec->r.sig.sig[i].flag & SIGF_EXPIRED) ? 'E':'-',
1020                        (rec->r.sig.sig[i].flag & SIGF_REVOKED) ? 'R':'-');
1021                 }
1022                 else if( rec->r.sig.sig[i].flag & SIGF_NOPUBKEY)
1023                     fputs("?--", fp);
1024                 else
1025                     fputs("---", fp);
1026             }
1027         }
1028         putc('\n', fp);
1029         break;
1030       case RECTYPE_SDIR:
1031         fprintf(fp, "sdir %lu, keyid=%08lX%08lX, algo=%d, hint=%lu\n",
1032                     rec->r.sdir.lid,
1033                     (ulong)rec->r.sdir.keyid[0],
1034                     (ulong)rec->r.sdir.keyid[1],
1035                     rec->r.sdir.pubkey_algo,
1036                     (ulong)rec->r.sdir.hintlist );
1037         break;
1038       case RECTYPE_CACH:
1039         fprintf(fp, "cach\n");
1040         break;
1041       case RECTYPE_HTBL:
1042         fprintf(fp, "htbl,");
1043         for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ )
1044             fprintf(fp, " %lu", rec->r.htbl.item[i] );
1045         putc('\n', fp);
1046         break;
1047       case RECTYPE_HLST:
1048         fprintf(fp, "hlst, next=%lu,", rec->r.hlst.next );
1049         for(i=0; i < ITEMS_PER_HLST_RECORD; i++ )
1050             fprintf(fp, " %lu", rec->r.hlst.rnum[i] );
1051         putc('\n', fp);
1052         break;
1053       default:
1054         fprintf(fp, "unknown type %d\n", rec->rectype );
1055         break;
1056     }
1057 }
1058
1059 /****************
1060  * read the record with number recnum
1061  * returns: -1 on error, 0 on success
1062  */
1063 int
1064 tdbio_read_record( ulong recnum, TRUSTREC *rec, int expected )
1065 {
1066     byte readbuf[TRUST_RECORD_LEN];
1067     const byte *buf, *p;
1068     int rc = 0;
1069     int n, i;
1070
1071     if( db_fd == -1 )
1072         open_db();
1073     buf = get_record_from_cache( recnum );
1074     if( !buf ) {
1075         if( lseek( db_fd, recnum * TRUST_RECORD_LEN, SEEK_SET ) == -1 ) {
1076             log_error(_("trustdb: lseek failed: %s\n"), strerror(errno) );
1077             return G10ERR_READ_FILE;
1078         }
1079         n = read( db_fd, readbuf, TRUST_RECORD_LEN);
1080         if( !n ) {
1081             return -1; /* eof */
1082         }
1083         else if( n != TRUST_RECORD_LEN ) {
1084             log_error(_("trustdb: read failed (n=%d): %s\n"), n,
1085                                                         strerror(errno) );
1086             return G10ERR_READ_FILE;
1087         }
1088         buf = readbuf;
1089     }
1090     rec->recnum = recnum;
1091     rec->dirty = 0;
1092     p = buf;
1093     rec->rectype = *p++;
1094     if( expected && rec->rectype != expected ) {
1095         log_error("%lu: read expected rec type %d, got %d\n",
1096                     recnum, expected, rec->rectype );
1097         return G10ERR_TRUSTDB;
1098     }
1099     p++;    /* skip reserved byte */
1100     switch( rec->rectype ) {
1101       case 0:  /* unused (free) record */
1102         break;
1103       case RECTYPE_VER: /* version record */
1104         if( memcmp(buf+1, "gpg", 3 ) ) {
1105             log_error( _("%s: not a trustdb file\n"), db_name );
1106             rc = G10ERR_TRUSTDB;
1107         }
1108         p += 2; /* skip "pgp" */
1109         rec->r.ver.version  = *p++;
1110         rec->r.ver.marginals = *p++;
1111         rec->r.ver.completes = *p++;
1112         rec->r.ver.cert_depth = *p++;
1113         p += 4; /* lock flags */
1114         rec->r.ver.created  = buftoulong(p); p += 4;
1115         rec->r.ver.modified = buftoulong(p); p += 4;
1116         rec->r.ver.validated= buftoulong(p); p += 4;
1117         rec->r.ver.keyhashtbl=buftoulong(p); p += 4;
1118         rec->r.ver.firstfree =buftoulong(p); p += 4;
1119         rec->r.ver.sdirhashtbl =buftoulong(p); p += 4;
1120         if( recnum ) {
1121             log_error( _("%s: version record with recnum %lu\n"), db_name,
1122                                                              (ulong)recnum );
1123             rc = G10ERR_TRUSTDB;
1124         }
1125         else if( rec->r.ver.version != 2 ) {
1126             log_error( _("%s: invalid file version %d\n"), db_name,
1127                                                         rec->r.ver.version );
1128             rc = G10ERR_TRUSTDB;
1129         }
1130         break;
1131       case RECTYPE_FREE:
1132         rec->r.free.next  = buftoulong(p); p += 4;
1133         break;
1134       case RECTYPE_DIR:   /*directory record */
1135         rec->r.dir.lid      = buftoulong(p); p += 4;
1136         rec->r.dir.keylist  = buftoulong(p); p += 4;
1137         rec->r.dir.uidlist  = buftoulong(p); p += 4;
1138         rec->r.dir.cacherec = buftoulong(p); p += 4;
1139         rec->r.dir.ownertrust = *p++;
1140         rec->r.dir.dirflags   = *p++;
1141         rec->r.dir.validity   = *p++;
1142         switch( rec->r.dir.validity ) {
1143           case 0:
1144           case TRUST_UNDEFINED:
1145           case TRUST_NEVER:
1146           case TRUST_MARGINAL:
1147           case TRUST_FULLY:
1148           case TRUST_ULTIMATE:
1149             break;
1150           default:
1151             log_info("lid %lu: invalid validity value - cleared\n", recnum);
1152         }
1153         if( rec->r.dir.lid != recnum ) {
1154             log_error( "%s: dir LID != recnum (%lu,%lu)\n",
1155                               db_name, rec->r.dir.lid, (ulong)recnum );
1156             rc = G10ERR_TRUSTDB;
1157         }
1158         break;
1159       case RECTYPE_KEY:   /* public key record */
1160         rec->r.key.lid      = buftoulong(p); p += 4;
1161         rec->r.key.next     = buftoulong(p); p += 4;
1162         p += 7;
1163         rec->r.key.keyflags = *p++;
1164         rec->r.key.pubkey_algo = *p++;
1165         rec->r.key.fingerprint_len = *p++;
1166         if( rec->r.key.fingerprint_len < 1 || rec->r.key.fingerprint_len > 20 )
1167             rec->r.key.fingerprint_len = 20;
1168         memcpy( rec->r.key.fingerprint, p, 20);
1169         break;
1170       case RECTYPE_UID:   /* user id record */
1171         rec->r.uid.lid      = buftoulong(p); p += 4;
1172         rec->r.uid.next     = buftoulong(p); p += 4;
1173         rec->r.uid.prefrec  = buftoulong(p); p += 4;
1174         rec->r.uid.siglist  = buftoulong(p); p += 4;
1175         rec->r.uid.uidflags = *p++;
1176         rec->r.uid.validity   = *p++;
1177         switch( rec->r.uid.validity ) {
1178           case 0:
1179           case TRUST_UNDEFINED:
1180           case TRUST_NEVER:
1181           case TRUST_MARGINAL:
1182           case TRUST_FULLY:
1183           case TRUST_ULTIMATE:
1184             break;
1185           default:
1186             log_info("lid %lu: invalid validity value - cleared\n", recnum);
1187         }
1188         memcpy( rec->r.uid.namehash, p, 20);
1189         break;
1190       case RECTYPE_PREF:  /* preference record */
1191         rec->r.pref.lid     = buftoulong(p); p += 4;
1192         rec->r.pref.next    = buftoulong(p); p += 4;
1193         memcpy( rec->r.pref.data, p, 30 );
1194         break;
1195       case RECTYPE_SIG:
1196         rec->r.sig.lid     = buftoulong(p); p += 4;
1197         rec->r.sig.next    = buftoulong(p); p += 4;
1198         for(i=0; i < SIGS_PER_RECORD; i++ ) {
1199             rec->r.sig.sig[i].lid  = buftoulong(p); p += 4;
1200             rec->r.sig.sig[i].flag = *p++;
1201         }
1202         break;
1203       case RECTYPE_SDIR:   /* shadow directory record */
1204         rec->r.sdir.lid     = buftoulong(p); p += 4;
1205         rec->r.sdir.keyid[0]= buftou32(p); p += 4;
1206         rec->r.sdir.keyid[1]= buftou32(p); p += 4;
1207         rec->r.sdir.pubkey_algo = *p++;
1208         p += 3;
1209         rec->r.sdir.hintlist = buftoulong(p);
1210         if( rec->r.sdir.lid != recnum ) {
1211             log_error( "%s: sdir LID != recnum (%lu,%lu)\n",
1212                                db_name, rec->r.sdir.lid, (ulong)recnum );
1213             rc = G10ERR_TRUSTDB;
1214         }
1215         break;
1216       case RECTYPE_CACH:   /* cache record */
1217         rec->r.cache.lid    = buftoulong(p); p += 4;
1218         memcpy(rec->r.cache.blockhash, p, 20); p += 20;
1219         rec->r.cache.trustlevel = *p++;
1220         break;
1221       case RECTYPE_HTBL:
1222         for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
1223             rec->r.htbl.item[i] = buftoulong(p); p += 4;
1224         }
1225         break;
1226       case RECTYPE_HLST:
1227         rec->r.hlst.next = buftoulong(p); p += 4;
1228         for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1229             rec->r.hlst.rnum[i] = buftoulong(p); p += 4;
1230         }
1231         break;
1232       default:
1233         log_error( "%s: invalid record type %d at recnum %lu\n",
1234                                    db_name, rec->rectype, (ulong)recnum );
1235         rc = G10ERR_TRUSTDB;
1236         break;
1237     }
1238
1239     return rc;
1240 }
1241
1242 /****************
1243  * Write the record at RECNUM
1244  */
1245 int
1246 tdbio_write_record( TRUSTREC *rec )
1247 {
1248     byte buf[TRUST_RECORD_LEN], *p;
1249     int rc = 0;
1250     int i;
1251     ulong recnum = rec->recnum;
1252
1253     if( db_fd == -1 )
1254         open_db();
1255
1256     memset(buf, 0, TRUST_RECORD_LEN);
1257     p = buf;
1258     *p++ = rec->rectype; p++;
1259     switch( rec->rectype ) {
1260       case 0:  /* unused record */
1261         break;
1262       case RECTYPE_VER: /* version record */
1263         if( recnum )
1264             BUG();
1265         memcpy(p-1, "gpg", 3 ); p += 2;
1266         *p++ = rec->r.ver.version;
1267         *p++ = rec->r.ver.marginals;
1268         *p++ = rec->r.ver.completes;
1269         *p++ = rec->r.ver.cert_depth;
1270         p += 4; /* skip lock flags */
1271         ulongtobuf(p, rec->r.ver.created); p += 4;
1272         ulongtobuf(p, rec->r.ver.modified); p += 4;
1273         ulongtobuf(p, rec->r.ver.validated); p += 4;
1274         ulongtobuf(p, rec->r.ver.keyhashtbl); p += 4;
1275         ulongtobuf(p, rec->r.ver.firstfree ); p += 4;
1276         ulongtobuf(p, rec->r.ver.sdirhashtbl ); p += 4;
1277         break;
1278
1279       case RECTYPE_FREE:
1280         ulongtobuf(p, rec->r.free.next); p += 4;
1281         break;
1282
1283       case RECTYPE_DIR:   /*directory record */
1284         ulongtobuf(p, rec->r.dir.lid); p += 4;
1285         ulongtobuf(p, rec->r.dir.keylist); p += 4;
1286         ulongtobuf(p, rec->r.dir.uidlist); p += 4;
1287         ulongtobuf(p, rec->r.dir.cacherec); p += 4;
1288         *p++ = rec->r.dir.ownertrust;
1289         *p++ = rec->r.dir.dirflags;
1290         *p++ = rec->r.dir.validity;
1291         assert( rec->r.dir.lid == recnum );
1292         break;
1293
1294       case RECTYPE_KEY:
1295         ulongtobuf(p, rec->r.key.lid); p += 4;
1296         ulongtobuf(p, rec->r.key.next); p += 4;
1297         p += 7;
1298         *p++ = rec->r.key.keyflags;
1299         *p++ = rec->r.key.pubkey_algo;
1300         *p++ = rec->r.key.fingerprint_len;
1301         memcpy( p, rec->r.key.fingerprint, 20); p += 20;
1302         break;
1303
1304       case RECTYPE_UID:   /* user id record */
1305         ulongtobuf(p, rec->r.uid.lid); p += 4;
1306         ulongtobuf(p, rec->r.uid.next); p += 4;
1307         ulongtobuf(p, rec->r.uid.prefrec); p += 4;
1308         ulongtobuf(p, rec->r.uid.siglist); p += 4;
1309         *p++ = rec->r.uid.uidflags;
1310         *p++ = rec->r.uid.validity;
1311         memcpy( p, rec->r.uid.namehash, 20 ); p += 20;
1312         break;
1313
1314       case RECTYPE_PREF:
1315         ulongtobuf(p, rec->r.pref.lid); p += 4;
1316         ulongtobuf(p, rec->r.pref.next); p += 4;
1317         memcpy( p, rec->r.pref.data, 30 );
1318         break;
1319
1320       case RECTYPE_SIG:
1321         ulongtobuf(p, rec->r.sig.lid); p += 4;
1322         ulongtobuf(p, rec->r.sig.next); p += 4;
1323         for(i=0; i < SIGS_PER_RECORD; i++ ) {
1324             ulongtobuf(p, rec->r.sig.sig[i].lid); p += 4;
1325             *p++ = rec->r.sig.sig[i].flag;
1326         }
1327         break;
1328
1329       case RECTYPE_SDIR:
1330         ulongtobuf( p, rec->r.sdir.lid); p += 4;
1331         u32tobuf( p, rec->r.sdir.keyid[0] ); p += 4;
1332         u32tobuf( p, rec->r.sdir.keyid[1] ); p += 4;
1333         *p++ = rec->r.sdir.pubkey_algo;
1334         p += 3;
1335         ulongtobuf( p, rec->r.sdir.hintlist );
1336         break;
1337
1338       case RECTYPE_CACH:
1339         ulongtobuf(p, rec->r.cache.lid); p += 4;
1340         memcpy(p, rec->r.cache.blockhash, 20); p += 20;
1341         *p++ = rec->r.cache.trustlevel;
1342         break;
1343
1344       case RECTYPE_HTBL:
1345         for(i=0; i < ITEMS_PER_HTBL_RECORD; i++ ) {
1346             ulongtobuf( p, rec->r.htbl.item[i]); p += 4;
1347         }
1348         break;
1349
1350       case RECTYPE_HLST:
1351         ulongtobuf( p, rec->r.hlst.next); p += 4;
1352         for(i=0; i < ITEMS_PER_HLST_RECORD; i++ ) {
1353             ulongtobuf( p, rec->r.hlst.rnum[i]); p += 4;
1354         }
1355         break;
1356
1357       default:
1358         BUG();
1359     }
1360
1361     rc = put_record_into_cache( recnum, buf );
1362     if( rc )
1363         ;
1364     if( rec->rectype == RECTYPE_KEY )
1365         rc = update_keyhashtbl( rec );
1366     else if( rec->rectype == RECTYPE_SDIR )
1367         rc = update_sdirhashtbl( rec );
1368
1369     return rc;
1370 }
1371
1372 int
1373 tdbio_delete_record( ulong recnum )
1374 {
1375     TRUSTREC vr, rec;
1376     int rc;
1377
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) );
1382
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;
1391 }
1392
1393 /****************
1394  * create a new record and return its record number
1395  */
1396 ulong
1397 tdbio_new_recnum()
1398 {
1399     off_t offset;
1400     ulong recnum;
1401     TRUSTREC vr, rec;
1402     int rc;
1403
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;
1416         }
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;
1424         }
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));
1433     }
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             log_error(_("trustdb rec %lu: lseek failed: %s\n"),
1448                                                 recnum, strerror(errno) );
1449             rc = G10ERR_WRITE_FILE;
1450         }
1451         else {
1452             int n = write( db_fd, &rec, TRUST_RECORD_LEN);
1453             if( n != TRUST_RECORD_LEN ) {
1454                 log_error(_("trustdb rec %lu: write failed (n=%d): %s\n"),
1455                                                  recnum, n, strerror(errno) );
1456                 rc = G10ERR_WRITE_FILE;
1457             }
1458         }
1459
1460         if( rc )
1461             log_fatal(_("%s: failed to append a record: %s\n"),
1462                                     db_name,    g10_errstr(rc));
1463     }
1464     return recnum ;
1465 }
1466
1467
1468
1469 /****************
1470  * Search the trustdb for a key which matches PK and return the dir record
1471  * The local_id of PK is set to the correct value
1472  */
1473 int
1474 tdbio_search_dir_bypk( PKT_public_key *pk, TRUSTREC *rec )
1475 {
1476     byte fingerprint[MAX_FINGERPRINT_LEN];
1477     size_t fingerlen;
1478     u32 keyid[2];
1479     int rc;
1480
1481     keyid_from_pk( pk, keyid );
1482     fingerprint_from_pk( pk, fingerprint, &fingerlen );
1483     rc = tdbio_search_dir_byfpr( fingerprint, fingerlen,
1484                                  pk->pubkey_algo, rec );
1485
1486     if( !rc ) {
1487         if( pk->local_id && pk->local_id != rec->recnum )
1488             log_error("%s: found record, but LID from memory does "
1489                        "not match recnum (%lu,%lu)\n",
1490                             db_name,  pk->local_id, rec->recnum );
1491         pk->local_id = rec->recnum;
1492     }
1493     return rc;
1494 }
1495
1496
1497 static int
1498 cmp_krec_fpr( void *dataptr, const TRUSTREC *rec )
1499 {
1500     const struct cmp_krec_fpr_struct *d = dataptr;
1501
1502     return rec->rectype == RECTYPE_KEY
1503            && ( !d->pubkey_algo || rec->r.key.pubkey_algo == d->pubkey_algo )
1504            && rec->r.key.fingerprint_len == d->fprlen
1505            && !memcmp( rec->r.key.fingerprint, d->fpr, d->fprlen );
1506 }
1507
1508 int
1509 tdbio_search_dir_byfpr( const byte *fingerprint, size_t fingerlen,
1510                         int pubkey_algo, TRUSTREC *rec )
1511 {
1512     struct cmp_krec_fpr_struct cmpdata;
1513     ulong recnum;
1514     int rc;
1515
1516     assert( fingerlen == 20 || fingerlen == 16 );
1517
1518     /* locate the key using the hash table */
1519     cmpdata.pubkey_algo = pubkey_algo;
1520     cmpdata.fpr = fingerprint;
1521     cmpdata.fprlen = fingerlen;
1522     rc = lookup_hashtable( get_keyhashrec(), fingerprint, fingerlen,
1523                            cmp_krec_fpr, &cmpdata, rec );
1524     if( !rc ) {
1525         recnum = rec->r.key.lid;
1526         /* Now read the dir record */
1527         rc = tdbio_read_record( recnum, rec, RECTYPE_DIR);
1528         if( rc )
1529             log_error("%s: can't read dirrec %lu: %s\n",
1530                                      db_name, recnum, g10_errstr(rc) );
1531     }
1532     return rc;
1533 }
1534
1535
1536
1537 static int
1538 cmp_sdir( void *dataptr, const TRUSTREC *rec )
1539 {
1540     const struct cmp_sdir_struct *d = dataptr;
1541
1542     return rec->rectype == RECTYPE_SDIR
1543            && ( !d->pubkey_algo || rec->r.sdir.pubkey_algo == d->pubkey_algo )
1544            && rec->r.sdir.keyid[0] == d->keyid[0]
1545            && rec->r.sdir.keyid[1] == d->keyid[1];
1546 }
1547
1548
1549 int
1550 tdbio_search_sdir( u32 *keyid, int pubkey_algo, TRUSTREC *rec )
1551 {
1552     struct cmp_sdir_struct cmpdata;
1553     int rc;
1554     byte key[8];
1555
1556     /* locate the shadow dir record using the hash table */
1557     u32tobuf( key   , keyid[0] );
1558     u32tobuf( key+4 , keyid[1] );
1559     cmpdata.pubkey_algo = pubkey_algo;
1560     cmpdata.keyid[0] = keyid[0];
1561     cmpdata.keyid[1] = keyid[1];
1562     rc = lookup_hashtable( get_sdirhashrec(), key, 8,
1563                            cmp_sdir, &cmpdata, rec );
1564     return rc;
1565 }
1566
1567