chiark / gitweb /
gpg: Fix searching for mail addresses in keyrings.
[gnupg2.git] / g10 / keyring.c
1 /* keyring.c - keyring file handling
2  * Copyright (C) 1998-2010 Free Software Foundation, Inc.
3  * Copyright (C) 1997-2015 Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29
30 #include "gpg.h"
31 #include "util.h"
32 #include "keyring.h"
33 #include "packet.h"
34 #include "keydb.h"
35 #include "options.h"
36 #include "main.h" /*for check_key_signature()*/
37 #include "i18n.h"
38 #include "../kbx/keybox.h"
39
40
41 typedef struct keyring_resource *KR_RESOURCE;
42 struct keyring_resource
43 {
44   struct keyring_resource *next;
45   int read_only;
46   dotlock_t lockhd;
47   int is_locked;
48   int did_full_scan;
49   char fname[1];
50 };
51 typedef struct keyring_resource const * CONST_KR_RESOURCE;
52
53 static KR_RESOURCE kr_resources;
54
55 struct keyring_handle
56 {
57   CONST_KR_RESOURCE resource;
58   struct {
59     CONST_KR_RESOURCE kr;
60     IOBUF iobuf;
61     int eof;
62     int error;
63   } current;
64   struct {
65     CONST_KR_RESOURCE kr;
66     off_t offset;
67     size_t pk_no;
68     size_t uid_no;
69     unsigned int n_packets; /*used for delete and update*/
70   } found, saved_found;
71   struct {
72     char *name;
73     char *pattern;
74   } word_match;
75 };
76
77 /* The number of extant handles.  */
78 static int active_handles;
79
80 static int do_copy (int mode, const char *fname, KBNODE root,
81                     off_t start_offset, unsigned int n_packets );
82
83
84 \f
85 /* We keep a cache of entries that we have entered in the DB.  This
86    includes not only public keys, but also subkeys.
87
88    Note: we'd like to keep the offset of the items that are present,
89    however, this doesn't work, because another concurrent GnuPG
90    process could modify the keyring.  */
91 struct key_present {
92   struct key_present *next;
93   u32 kid[2];
94 };
95
96 /* For the hash table, we use separate chaining with linked lists.
97    This means that we have an array of N linked lists (buckets), which
98    is indexed by KEYID[1] mod N.  Elements present in the keyring will
99    be on the list; elements not present in the keyring will not be on
100    the list.
101
102    Note: since the hash table stores both present and not present
103    information, it cannot be used until we complete a full scan of the
104    keyring.  This is indicated by key_present_hash_ready.  */
105 typedef struct key_present **key_present_hash_t;
106 static key_present_hash_t key_present_hash;
107 static int key_present_hash_ready;
108
109 #define KEY_PRESENT_HASH_BUCKETS 2048
110
111 /* Allocate a new value for a key present hash table.  */
112 static struct key_present *
113 key_present_value_new (void)
114 {
115   struct key_present *k;
116
117   k = xmalloc_clear (sizeof *k);
118   return k;
119 }
120
121 /* Allocate a new key present hash table.  */
122 static key_present_hash_t
123 key_present_hash_new (void)
124 {
125   struct key_present **tbl;
126
127   tbl = xmalloc_clear (KEY_PRESENT_HASH_BUCKETS * sizeof *tbl);
128   return tbl;
129 }
130
131 /* Return whether the value described by KID if it is in the hash
132    table.  Otherwise, return NULL.  */
133 static struct key_present *
134 key_present_hash_lookup (key_present_hash_t tbl, u32 *kid)
135 {
136   struct key_present *k;
137
138   for (k = tbl[(kid[1] % (KEY_PRESENT_HASH_BUCKETS - 1))]; k; k = k->next)
139     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
140       return k;
141   return NULL;
142 }
143
144 /* Add the key to the hash table TBL if it is not already present.  */
145 static void
146 key_present_hash_update (key_present_hash_t tbl, u32 *kid)
147 {
148   struct key_present *k;
149
150   for (k = tbl[(kid[1] % (KEY_PRESENT_HASH_BUCKETS - 1))]; k; k = k->next)
151     {
152       if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
153         return;
154     }
155
156   k = key_present_value_new ();
157   k->kid[0] = kid[0];
158   k->kid[1] = kid[1];
159   k->next = tbl[(kid[1] % (KEY_PRESENT_HASH_BUCKETS - 1))];
160   tbl[(kid[1] % (KEY_PRESENT_HASH_BUCKETS - 1))] = k;
161 }
162
163 /* Add all the keys (public and subkeys) present in the keyblock to
164    the hash TBL.  */
165 static void
166 key_present_hash_update_from_kb (key_present_hash_t tbl, KBNODE node)
167 {
168   for (; node; node = node->next)
169     {
170       if (node->pkt->pkttype == PKT_PUBLIC_KEY
171           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
172         {
173           u32 aki[2];
174           keyid_from_pk (node->pkt->pkt.public_key, aki);
175           key_present_hash_update (tbl, aki);
176         }
177     }
178 }
179 \f
180 /*
181  * Register a filename for plain keyring files.  ptr is set to a
182  * pointer to be used to create a handles etc, or the already-issued
183  * pointer if it has already been registered.  The function returns 1
184  * if a new keyring was registered.
185 */
186 int
187 keyring_register_filename (const char *fname, int read_only, void **ptr)
188 {
189     KR_RESOURCE kr;
190
191     if (active_handles)
192       /* There are open handles.  */
193       BUG ();
194
195     for (kr=kr_resources; kr; kr = kr->next)
196       {
197         if (same_file_p (kr->fname, fname))
198           {
199             /* Already registered. */
200             if (read_only)
201               kr->read_only = 1;
202             *ptr=kr;
203             return 0;
204           }
205       }
206
207     kr = xmalloc (sizeof *kr + strlen (fname));
208     strcpy (kr->fname, fname);
209     kr->read_only = read_only;
210     kr->lockhd = NULL;
211     kr->is_locked = 0;
212     kr->did_full_scan = 0;
213     /* keep a list of all issued pointers */
214     kr->next = kr_resources;
215     kr_resources = kr;
216
217     /* create the offset table the first time a function here is used */
218     if (!key_present_hash)
219       key_present_hash = key_present_hash_new ();
220
221     *ptr=kr;
222
223     return 1;
224 }
225
226 int
227 keyring_is_writable (void *token)
228 {
229   KR_RESOURCE r = token;
230
231   return r? (r->read_only || !access (r->fname, W_OK)) : 0;
232 }
233
234
235 \f
236 /* Create a new handle for the resource associated with TOKEN.
237    On error NULL is returned and ERRNO is set.
238    The returned handle must be released using keyring_release (). */
239 KEYRING_HANDLE
240 keyring_new (void *token)
241 {
242   KEYRING_HANDLE hd;
243   KR_RESOURCE resource = token;
244
245   log_assert (resource);
246
247   hd = xtrycalloc (1, sizeof *hd);
248   if (!hd)
249     return hd;
250   hd->resource = resource;
251   active_handles++;
252   return hd;
253 }
254
255 void
256 keyring_release (KEYRING_HANDLE hd)
257 {
258     if (!hd)
259         return;
260     log_assert (active_handles > 0);
261     active_handles--;
262     xfree (hd->word_match.name);
263     xfree (hd->word_match.pattern);
264     iobuf_close (hd->current.iobuf);
265     xfree (hd);
266 }
267
268
269 /* Save the current found state in HD for later retrieval by
270    keybox_pop_found_state.  Only one state may be saved.  */
271 void
272 keyring_push_found_state (KEYRING_HANDLE hd)
273 {
274   hd->saved_found = hd->found;
275   hd->found.kr = NULL;
276 }
277
278
279 /* Restore the saved found state in HD.  */
280 void
281 keyring_pop_found_state (KEYRING_HANDLE hd)
282 {
283   hd->found = hd->saved_found;
284   hd->saved_found.kr = NULL;
285 }
286
287
288 const char *
289 keyring_get_resource_name (KEYRING_HANDLE hd)
290 {
291     if (!hd || !hd->resource)
292       return NULL;
293     return hd->resource->fname;
294 }
295
296
297 /*
298  * Lock the keyring with the given handle, or unlock if YES is false.
299  * We ignore the handle and lock all registered files.
300  */
301 int
302 keyring_lock (KEYRING_HANDLE hd, int yes)
303 {
304     KR_RESOURCE kr;
305     int rc = 0;
306
307     (void)hd;
308
309     if (yes) {
310         /* first make sure the lock handles are created */
311         for (kr=kr_resources; kr; kr = kr->next) {
312             if (!keyring_is_writable(kr))
313                 continue;
314             if (!kr->lockhd) {
315                 kr->lockhd = dotlock_create (kr->fname, 0);
316                 if (!kr->lockhd) {
317                     log_info ("can't allocate lock for '%s'\n", kr->fname );
318                     rc = GPG_ERR_GENERAL;
319                 }
320             }
321         }
322         if (rc)
323             return rc;
324
325         /* and now set the locks */
326         for (kr=kr_resources; kr; kr = kr->next) {
327             if (!keyring_is_writable(kr))
328                 continue;
329             if (kr->is_locked)
330                 continue;
331
332 #ifdef HAVE_W32_SYSTEM
333             /* Under Windows we need to CloseHandle the file before we
334              * try to lock it.  This is because another process might
335              * have taken the lock and is using keybox_file_rename to
336              * rename the base file.  How if our dotlock_take below is
337              * waiting for the lock but we have the base file still
338              * open, keybox_file_rename will never succeed as we are
339              * in a deadlock.  */
340             iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0,
341                          (char*)kr->fname);
342 #endif /*HAVE_W32_SYSTEM*/
343             if (dotlock_take (kr->lockhd, -1) ) {
344                 log_info ("can't lock '%s'\n", kr->fname );
345                 rc = GPG_ERR_GENERAL;
346             }
347             else
348                 kr->is_locked = 1;
349         }
350     }
351
352     if (rc || !yes) {
353         for (kr=kr_resources; kr; kr = kr->next) {
354             if (!keyring_is_writable(kr))
355                 continue;
356             if (!kr->is_locked)
357                 continue;
358
359             if (dotlock_release (kr->lockhd))
360                 log_info ("can't unlock '%s'\n", kr->fname );
361             else
362                 kr->is_locked = 0;
363         }
364     }
365
366     return rc;
367 }
368
369
370 \f
371 /*
372  * Return the last found keyblock.  Caller must free it.
373  * The returned keyblock has the kbode flag bit 0 set for the node with
374  * the public key used to locate the keyblock or flag bit 1 set for
375  * the user ID node.
376  */
377 int
378 keyring_get_keyblock (KEYRING_HANDLE hd, KBNODE *ret_kb)
379 {
380     PACKET *pkt;
381     int rc;
382     KBNODE keyblock = NULL, node, lastnode;
383     IOBUF a;
384     int in_cert = 0;
385     int pk_no = 0;
386     int uid_no = 0;
387     int save_mode;
388
389     if (ret_kb)
390         *ret_kb = NULL;
391
392     if (!hd->found.kr)
393         return -1; /* no successful search */
394
395     a = iobuf_open (hd->found.kr->fname);
396     if (!a)
397       {
398         log_error(_("can't open '%s'\n"), hd->found.kr->fname);
399         return GPG_ERR_KEYRING_OPEN;
400       }
401
402     if (iobuf_seek (a, hd->found.offset) ) {
403         log_error ("can't seek '%s'\n", hd->found.kr->fname);
404         iobuf_close(a);
405         return GPG_ERR_KEYRING_OPEN;
406     }
407
408     pkt = xmalloc (sizeof *pkt);
409     init_packet (pkt);
410     hd->found.n_packets = 0;;
411     lastnode = NULL;
412     save_mode = set_packet_list_mode(0);
413     while ((rc=parse_packet (a, pkt)) != -1) {
414         hd->found.n_packets++;
415         if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET) {
416             free_packet (pkt);
417             init_packet (pkt);
418             continue;
419         }
420         if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY)
421           {
422             if (in_cert)
423               /* It is not this key that is problematic, but the
424                  following key.  */
425               {
426                 rc = 0;
427                 hd->found.n_packets --;
428               }
429             else
430               /* Upper layer needs to handle this.  */
431               {
432               }
433             break;
434           }
435         if (rc) {
436             log_error ("keyring_get_keyblock: read error: %s\n",
437                        gpg_strerror (rc) );
438             rc = GPG_ERR_INV_KEYRING;
439             break;
440         }
441
442         /* Filter allowed packets.  */
443         switch (pkt->pkttype)
444           {
445           case PKT_PUBLIC_KEY:
446           case PKT_PUBLIC_SUBKEY:
447           case PKT_SECRET_KEY:
448           case PKT_SECRET_SUBKEY:
449           case PKT_USER_ID:
450           case PKT_ATTRIBUTE:
451           case PKT_SIGNATURE:
452             break; /* Allowed per RFC.  */
453           case PKT_RING_TRUST:
454           case PKT_OLD_COMMENT:
455           case PKT_COMMENT:
456           case PKT_GPG_CONTROL:
457             break; /* Allowed by us.  */
458
459           default:
460             log_error ("skipped packet of type %d in keyring\n",
461                        (int)pkt->pkttype);
462             free_packet(pkt);
463             init_packet(pkt);
464             continue;
465           }
466
467         if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
468                         || pkt->pkttype == PKT_SECRET_KEY)) {
469             hd->found.n_packets--; /* fix counter */
470             break; /* ready */
471         }
472
473         in_cert = 1;
474         if (pkt->pkttype == PKT_RING_TRUST)
475           {
476             /*(this code is duplicated after the loop)*/
477             if ( lastnode
478                  && lastnode->pkt->pkttype == PKT_SIGNATURE
479                  && (pkt->pkt.ring_trust->sigcache & 1) ) {
480                 /* This is a ring trust packet with a checked signature
481                  * status cache following directly a signature paket.
482                  * Set the cache status into that signature packet.  */
483                 PKT_signature *sig = lastnode->pkt->pkt.signature;
484
485                 sig->flags.checked = 1;
486                 sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
487             }
488             /* Reset LASTNODE, so that we set the cache status only from
489              * the ring trust packet immediately following a signature. */
490             lastnode = NULL;
491             free_packet(pkt);
492             init_packet(pkt);
493             continue;
494           }
495
496
497         node = lastnode = new_kbnode (pkt);
498         if (!keyblock)
499           keyblock = node;
500         else
501           add_kbnode (keyblock, node);
502         switch (pkt->pkttype)
503           {
504           case PKT_PUBLIC_KEY:
505           case PKT_PUBLIC_SUBKEY:
506           case PKT_SECRET_KEY:
507           case PKT_SECRET_SUBKEY:
508             if (++pk_no == hd->found.pk_no)
509               node->flag |= 1;
510             break;
511
512           case PKT_USER_ID:
513             if (++uid_no == hd->found.uid_no)
514               node->flag |= 2;
515             break;
516
517           default:
518             break;
519           }
520
521         pkt = xmalloc (sizeof *pkt);
522         init_packet(pkt);
523     }
524     set_packet_list_mode(save_mode);
525
526     if (rc == -1 && keyblock)
527         rc = 0; /* got the entire keyblock */
528
529     if (rc || !ret_kb)
530         release_kbnode (keyblock);
531     else {
532         /*(duplicated from the loop body)*/
533         if ( pkt && pkt->pkttype == PKT_RING_TRUST
534              && lastnode
535              && lastnode->pkt->pkttype == PKT_SIGNATURE
536              && (pkt->pkt.ring_trust->sigcache & 1) ) {
537             PKT_signature *sig = lastnode->pkt->pkt.signature;
538             sig->flags.checked = 1;
539             sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
540         }
541         *ret_kb = keyblock;
542     }
543     free_packet (pkt);
544     xfree (pkt);
545     iobuf_close(a);
546
547     /* Make sure that future search operations fail immediately when
548      * we know that we are working on a invalid keyring
549      */
550     if (gpg_err_code (rc) == GPG_ERR_INV_KEYRING)
551         hd->current.error = rc;
552
553     return rc;
554 }
555
556 int
557 keyring_update_keyblock (KEYRING_HANDLE hd, KBNODE kb)
558 {
559     int rc;
560
561     if (!hd->found.kr)
562         return -1; /* no successful prior search */
563
564     if (hd->found.kr->read_only)
565       return gpg_error (GPG_ERR_EACCES);
566
567     if (!hd->found.n_packets) {
568         /* need to know the number of packets - do a dummy get_keyblock*/
569         rc = keyring_get_keyblock (hd, NULL);
570         if (rc) {
571             log_error ("re-reading keyblock failed: %s\n", gpg_strerror (rc));
572             return rc;
573         }
574         if (!hd->found.n_packets)
575             BUG ();
576     }
577
578     /* The open iobuf isn't needed anymore and in fact is a problem when
579        it comes to renaming the keyring files on some operating systems,
580        so close it here */
581     iobuf_close(hd->current.iobuf);
582     hd->current.iobuf = NULL;
583
584     /* do the update */
585     rc = do_copy (3, hd->found.kr->fname, kb,
586                   hd->found.offset, hd->found.n_packets );
587     if (!rc) {
588       if (key_present_hash)
589         {
590           key_present_hash_update_from_kb (key_present_hash, kb);
591         }
592       /* better reset the found info */
593       hd->found.kr = NULL;
594       hd->found.offset = 0;
595     }
596     return rc;
597 }
598
599 int
600 keyring_insert_keyblock (KEYRING_HANDLE hd, KBNODE kb)
601 {
602     int rc;
603     const char *fname;
604
605     if (!hd)
606         fname = NULL;
607     else if (hd->found.kr)
608       {
609         fname = hd->found.kr->fname;
610         if (hd->found.kr->read_only)
611           return gpg_error (GPG_ERR_EACCES);
612       }
613     else if (hd->current.kr)
614       {
615         fname = hd->current.kr->fname;
616         if (hd->current.kr->read_only)
617           return gpg_error (GPG_ERR_EACCES);
618       }
619     else
620         fname = hd->resource? hd->resource->fname:NULL;
621
622     if (!fname)
623         return GPG_ERR_GENERAL;
624
625     /* Close this one otherwise we will lose the position for
626      * a next search.  Fixme: it would be better to adjust the position
627      * after the write opertions.
628      */
629     iobuf_close (hd->current.iobuf);
630     hd->current.iobuf = NULL;
631
632     /* do the insert */
633     rc = do_copy (1, fname, kb, 0, 0 );
634     if (!rc && key_present_hash)
635       {
636         key_present_hash_update_from_kb (key_present_hash, kb);
637       }
638
639     return rc;
640 }
641
642
643 int
644 keyring_delete_keyblock (KEYRING_HANDLE hd)
645 {
646     int rc;
647
648     if (!hd->found.kr)
649         return -1; /* no successful prior search */
650
651     if (hd->found.kr->read_only)
652       return gpg_error (GPG_ERR_EACCES);
653
654     if (!hd->found.n_packets) {
655         /* need to know the number of packets - do a dummy get_keyblock*/
656         rc = keyring_get_keyblock (hd, NULL);
657         if (rc) {
658             log_error ("re-reading keyblock failed: %s\n", gpg_strerror (rc));
659             return rc;
660         }
661         if (!hd->found.n_packets)
662             BUG ();
663     }
664
665     /* close this one otherwise we will lose the position for
666      * a next search.  Fixme: it would be better to adjust the position
667      * after the write opertions.
668      */
669     iobuf_close (hd->current.iobuf);
670     hd->current.iobuf = NULL;
671
672     /* do the delete */
673     rc = do_copy (2, hd->found.kr->fname, NULL,
674                   hd->found.offset, hd->found.n_packets );
675     if (!rc) {
676         /* better reset the found info */
677         hd->found.kr = NULL;
678         hd->found.offset = 0;
679         /* Delete is a rare operations, so we don't remove the keys
680          * from the offset table */
681     }
682     return rc;
683 }
684
685
686 \f
687 /*
688  * Start the next search on this handle right at the beginning
689  */
690 int
691 keyring_search_reset (KEYRING_HANDLE hd)
692 {
693     log_assert (hd);
694
695     hd->current.kr = NULL;
696     iobuf_close (hd->current.iobuf);
697     hd->current.iobuf = NULL;
698     hd->current.eof = 0;
699     hd->current.error = 0;
700
701     hd->found.kr = NULL;
702     hd->found.offset = 0;
703     return 0;
704 }
705
706
707 static int
708 prepare_search (KEYRING_HANDLE hd)
709 {
710     if (hd->current.error) {
711         /* If the last key was a legacy key, we simply ignore the error so that
712            we can easily use search_next.  */
713         if (gpg_err_code (hd->current.error) == GPG_ERR_LEGACY_KEY)
714           {
715             if (DBG_LOOKUP)
716               log_debug ("%s: last error was GPG_ERR_LEGACY_KEY, clearing\n",
717                          __func__);
718             hd->current.error = 0;
719           }
720         else
721           {
722             if (DBG_LOOKUP)
723               log_debug ("%s: returning last error: %s\n",
724                          __func__, gpg_strerror (hd->current.error));
725             return hd->current.error; /* still in error state */
726           }
727     }
728
729     if (hd->current.kr && !hd->current.eof) {
730         if ( !hd->current.iobuf )
731           {
732             if (DBG_LOOKUP)
733               log_debug ("%s: missing iobuf!\n", __func__);
734             return GPG_ERR_GENERAL; /* Position invalid after a modify.  */
735           }
736         return 0; /* okay */
737     }
738
739     if (!hd->current.kr && hd->current.eof)
740       {
741         if (DBG_LOOKUP)
742           log_debug ("%s: EOF!\n", __func__);
743         return -1; /* still EOF */
744       }
745
746     if (!hd->current.kr) { /* start search with first keyring */
747         hd->current.kr = hd->resource;
748         if (!hd->current.kr) {
749           if (DBG_LOOKUP)
750             log_debug ("%s: keyring not available!\n", __func__);
751           hd->current.eof = 1;
752           return -1; /* keyring not available */
753         }
754         log_assert (!hd->current.iobuf);
755     }
756     else { /* EOF */
757         if (DBG_LOOKUP)
758           log_debug ("%s: EOF\n", __func__);
759         iobuf_close (hd->current.iobuf);
760         hd->current.iobuf = NULL;
761         hd->current.kr = NULL;
762         hd->current.eof = 1;
763         return -1;
764     }
765
766     hd->current.eof = 0;
767     hd->current.iobuf = iobuf_open (hd->current.kr->fname);
768     if (!hd->current.iobuf)
769       {
770         hd->current.error = gpg_error_from_syserror ();
771         log_error(_("can't open '%s'\n"), hd->current.kr->fname );
772         return hd->current.error;
773       }
774
775     return 0;
776 }
777
778 \f
779 /* A map of the all characters valid used for word_match()
780  * Valid characters are in in this table converted to uppercase.
781  * because the upper 128 bytes have special meaning, we assume
782  * that they are all valid.
783  * Note: We must use numerical values here in case that this program
784  * will be converted to those little blue HAL9000s with their strange
785  * EBCDIC character set (user ids are UTF-8).
786  * wk 2000-04-13: Hmmm, does this really make sense, given the fact that
787  * we can run gpg now on a S/390 running GNU/Linux, where the code
788  * translation is done by the device drivers?
789  */
790 static const byte word_match_chars[256] = {
791   /* 00 */  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
792   /* 08 */  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
793   /* 10 */  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
794   /* 18 */  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
795   /* 20 */  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
796   /* 28 */  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
797   /* 30 */  0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
798   /* 38 */  0x38, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
799   /* 40 */  0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
800   /* 48 */  0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
801   /* 50 */  0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
802   /* 58 */  0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
803   /* 60 */  0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
804   /* 68 */  0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
805   /* 70 */  0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
806   /* 78 */  0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
807   /* 80 */  0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
808   /* 88 */  0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
809   /* 90 */  0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
810   /* 98 */  0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
811   /* a0 */  0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
812   /* a8 */  0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
813   /* b0 */  0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
814   /* b8 */  0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
815   /* c0 */  0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
816   /* c8 */  0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
817   /* d0 */  0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
818   /* d8 */  0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
819   /* e0 */  0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
820   /* e8 */  0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
821   /* f0 */  0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
822   /* f8 */  0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
823 };
824
825 /****************
826  * Do a word match (original user id starts with a '+').
827  * The pattern is already tokenized to a more suitable format:
828  * There are only the real words in it delimited by one space
829  * and all converted to uppercase.
830  *
831  * Returns: 0 if all words match.
832  *
833  * Note: This algorithm is a straightforward one and not very
834  *       fast.  It works for UTF-8 strings.  The uidlen should
835  *       be removed but due to the fact that old versions of
836  *       pgp don't use UTF-8 we still use the length; this should
837  *       be fixed in parse-packet (and replace \0 by some special
838  *       UTF-8 encoding)
839  */
840 static int
841 word_match( const byte *uid, size_t uidlen, const byte *pattern )
842 {
843     size_t wlen, n;
844     const byte *p;
845     const byte *s;
846
847     for( s=pattern; *s; ) {
848         do {
849             /* skip leading delimiters */
850             while( uidlen && !word_match_chars[*uid] )
851                 uid++, uidlen--;
852             /* get length of the word */
853             n = uidlen; p = uid;
854             while( n && word_match_chars[*p] )
855                 p++, n--;
856             wlen = p - uid;
857             /* and compare against the current word from pattern */
858             for(n=0, p=uid; n < wlen && s[n] != ' ' && s[n] ; n++, p++ ) {
859                 if( word_match_chars[*p] != s[n] )
860                     break;
861             }
862             if( n == wlen && (s[n] == ' ' || !s[n]) )
863                 break; /* found */
864             uid += wlen;
865             uidlen -= wlen;
866         } while( uidlen );
867         if( !uidlen )
868             return -1; /* not found */
869
870         /* advance to next word in pattern */
871         for(; *s != ' ' && *s ; s++ )
872             ;
873         if( *s )
874             s++ ;
875     }
876     return 0; /* found */
877 }
878
879 /****************
880  * prepare word word_match; that is parse the name and
881  * build the pattern.
882  * caller has to free the returned pattern
883  */
884 static char*
885 prepare_word_match (const byte *name)
886 {
887     byte *pattern, *p;
888     int c;
889
890     /* the original length is always enough for the pattern */
891     p = pattern = xmalloc(strlen(name)+1);
892     do {
893         /* skip leading delimiters */
894         while( *name && !word_match_chars[*name] )
895             name++;
896         /* copy as long as we don't have a delimiter and convert
897          * to uppercase.
898          * fixme: how can we handle utf8 uppercasing */
899         for( ; *name &&  (c=word_match_chars[*name]); name++ )
900             *p++ = c;
901         *p++ = ' '; /* append pattern delimiter */
902     } while( *name );
903     p[-1] = 0; /* replace last pattern delimiter by EOS */
904
905     return pattern;
906 }
907
908
909
910
911 static int
912 compare_name (int mode, const char *name, const char *uid, size_t uidlen)
913 {
914     int i;
915     const char *s, *se;
916
917     if (mode == KEYDB_SEARCH_MODE_EXACT) {
918         for (i=0; name[i] && uidlen; i++, uidlen--)
919             if (uid[i] != name[i])
920                 break;
921         if (!uidlen && !name[i])
922             return 0; /* found */
923     }
924     else if (mode == KEYDB_SEARCH_MODE_SUBSTR) {
925         if (ascii_memistr( uid, uidlen, name ))
926             return 0;
927     }
928     else if (   mode == KEYDB_SEARCH_MODE_MAIL
929              || mode == KEYDB_SEARCH_MODE_MAILSUB
930              || mode == KEYDB_SEARCH_MODE_MAILEND) {
931         int have_angles = 1;
932         for (i=0, s= uid; i < uidlen && *s != '<'; s++, i++)
933             ;
934         if (i == uidlen)
935           {
936             /* The UID is a plain addr-spec (cf. RFC2822 section 4.3).  */
937             have_angles = 0;
938             s = uid;
939             i = 0;
940           }
941         if (i < uidlen)  {
942             if (have_angles)
943               {
944                 /* skip opening delim and one char and look for the closing one*/
945                 s++; i++;
946                 for (se=s+1, i++; i < uidlen && *se != '>'; se++, i++)
947                   ;
948               }
949             else
950               se = s + uidlen;
951
952             if (i < uidlen) {
953                 i = se - s;
954                 if (mode == KEYDB_SEARCH_MODE_MAIL) {
955                     if( strlen(name)-2 == i
956                         && !ascii_memcasecmp( s, name+1, i) )
957                         return 0;
958                 }
959                 else if (mode == KEYDB_SEARCH_MODE_MAILSUB) {
960                     if( ascii_memistr( s, i, name ) )
961                         return 0;
962                 }
963                 else { /* email from end */
964                     /* nyi */
965                 }
966             }
967         }
968     }
969     else if (mode == KEYDB_SEARCH_MODE_WORDS)
970         return word_match (uid, uidlen, name);
971     else
972         BUG();
973
974     return -1; /* not found */
975 }
976
977 \f
978 /*
979  * Search through the keyring(s), starting at the current position,
980  * for a keyblock which contains one of the keys described in the DESC array.
981  */
982 int
983 keyring_search (KEYRING_HANDLE hd, KEYDB_SEARCH_DESC *desc,
984                 size_t ndesc, size_t *descindex, int ignore_legacy)
985 {
986   int rc;
987   PACKET pkt;
988   int save_mode;
989   off_t offset, main_offset;
990   size_t n;
991   int need_uid, need_words, need_keyid, need_fpr, any_skip;
992   int pk_no, uid_no;
993   int initial_skip;
994   int scanned_from_start;
995   int use_key_present_hash;
996   PKT_user_id *uid = NULL;
997   PKT_public_key *pk = NULL;
998   u32 aki[2];
999
1000   /* figure out what information we need */
1001   need_uid = need_words = need_keyid = need_fpr = any_skip = 0;
1002   for (n=0; n < ndesc; n++)
1003     {
1004       switch (desc[n].mode)
1005         {
1006         case KEYDB_SEARCH_MODE_EXACT:
1007         case KEYDB_SEARCH_MODE_SUBSTR:
1008         case KEYDB_SEARCH_MODE_MAIL:
1009         case KEYDB_SEARCH_MODE_MAILSUB:
1010         case KEYDB_SEARCH_MODE_MAILEND:
1011           need_uid = 1;
1012           break;
1013         case KEYDB_SEARCH_MODE_WORDS:
1014           need_uid = 1;
1015           need_words = 1;
1016           break;
1017         case KEYDB_SEARCH_MODE_SHORT_KID:
1018         case KEYDB_SEARCH_MODE_LONG_KID:
1019           need_keyid = 1;
1020           break;
1021         case KEYDB_SEARCH_MODE_FPR16:
1022         case KEYDB_SEARCH_MODE_FPR20:
1023         case KEYDB_SEARCH_MODE_FPR:
1024           need_fpr = 1;
1025           break;
1026         case KEYDB_SEARCH_MODE_FIRST:
1027           /* always restart the search in this mode */
1028           keyring_search_reset (hd);
1029           break;
1030         default: break;
1031         }
1032       if (desc[n].skipfnc)
1033         {
1034           any_skip = 1;
1035           need_keyid = 1;
1036         }
1037     }
1038
1039   if (DBG_LOOKUP)
1040     log_debug ("%s: need_uid = %d; need_words = %d; need_keyid = %d; need_fpr = %d; any_skip = %d\n",
1041                __func__, need_uid, need_words, need_keyid, need_fpr, any_skip);
1042
1043   rc = prepare_search (hd);
1044   if (rc)
1045     {
1046       if (DBG_LOOKUP)
1047         log_debug ("%s: prepare_search failed: %s (%d)\n",
1048                    __func__, gpg_strerror (rc), gpg_err_code (rc));
1049       return rc;
1050     }
1051
1052   use_key_present_hash = !!key_present_hash;
1053   if (!use_key_present_hash)
1054     {
1055       if (DBG_LOOKUP)
1056         log_debug ("%s: no offset table.\n", __func__);
1057     }
1058   else if (!key_present_hash_ready)
1059     {
1060       if (DBG_LOOKUP)
1061         log_debug ("%s: initializing offset table. (need_keyid: %d => 1)\n",
1062                    __func__, need_keyid);
1063       need_keyid = 1;
1064     }
1065   else if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID)
1066     {
1067       struct key_present *oi;
1068
1069       if (DBG_LOOKUP)
1070         log_debug ("%s: look up by long key id, checking cache\n", __func__);
1071
1072       oi = key_present_hash_lookup (key_present_hash, desc[0].u.kid);
1073       if (!oi)
1074         { /* We know that we don't have this key */
1075           if (DBG_LOOKUP)
1076             log_debug ("%s: cache says not present\n", __func__);
1077           hd->found.kr = NULL;
1078           hd->current.eof = 1;
1079           return -1;
1080         }
1081       /* We could now create a positive search status and return.
1082        * However the problem is that another instance of gpg may
1083        * have changed the keyring so that the offsets are not valid
1084        * anymore - therefore we don't do it
1085        */
1086     }
1087
1088   if (need_words)
1089     {
1090       const char *name = NULL;
1091
1092       log_debug ("word search mode does not yet work\n");
1093       /* FIXME: here is a long standing bug in our function and in addition we
1094          just use the first search description */
1095       for (n=0; n < ndesc && !name; n++)
1096         {
1097           if (desc[n].mode == KEYDB_SEARCH_MODE_WORDS)
1098             name = desc[n].u.name;
1099         }
1100       log_assert (name);
1101       if ( !hd->word_match.name || strcmp (hd->word_match.name, name) )
1102         {
1103           /* name changed */
1104           xfree (hd->word_match.name);
1105           xfree (hd->word_match.pattern);
1106           hd->word_match.name = xstrdup (name);
1107           hd->word_match.pattern = prepare_word_match (name);
1108         }
1109       /*  name = hd->word_match.pattern; */
1110     }
1111
1112   init_packet(&pkt);
1113   save_mode = set_packet_list_mode(0);
1114
1115   hd->found.kr = NULL;
1116   main_offset = 0;
1117   pk_no = uid_no = 0;
1118   initial_skip = 1; /* skip until we see the start of a keyblock */
1119   scanned_from_start = iobuf_tell (hd->current.iobuf) == 0;
1120   if (DBG_LOOKUP)
1121     log_debug ("%s: %ssearching from start of resource.\n",
1122                __func__, scanned_from_start ? "" : "not ");
1123   while (1)
1124     {
1125       byte afp[MAX_FINGERPRINT_LEN];
1126       size_t an;
1127
1128       rc = search_packet (hd->current.iobuf, &pkt, &offset, need_uid);
1129       if (ignore_legacy && gpg_err_code (rc) == GPG_ERR_LEGACY_KEY)
1130         {
1131           free_packet (&pkt);
1132           continue;
1133         }
1134       if (rc)
1135         break;
1136
1137       if (pkt.pkttype == PKT_PUBLIC_KEY  || pkt.pkttype == PKT_SECRET_KEY)
1138         {
1139           main_offset = offset;
1140           pk_no = uid_no = 0;
1141           initial_skip = 0;
1142         }
1143       if (initial_skip)
1144         {
1145           free_packet (&pkt);
1146           continue;
1147         }
1148
1149       pk = NULL;
1150       uid = NULL;
1151       if (   pkt.pkttype == PKT_PUBLIC_KEY
1152              || pkt.pkttype == PKT_PUBLIC_SUBKEY
1153              || pkt.pkttype == PKT_SECRET_KEY
1154              || pkt.pkttype == PKT_SECRET_SUBKEY)
1155         {
1156           pk = pkt.pkt.public_key;
1157           ++pk_no;
1158
1159           if (need_fpr) {
1160             fingerprint_from_pk (pk, afp, &an);
1161             while (an < 20) /* fill up to 20 bytes */
1162               afp[an++] = 0;
1163           }
1164           if (need_keyid)
1165             keyid_from_pk (pk, aki);
1166
1167           if (use_key_present_hash
1168               && !key_present_hash_ready
1169               && scanned_from_start)
1170             key_present_hash_update (key_present_hash, aki);
1171         }
1172       else if (pkt.pkttype == PKT_USER_ID)
1173         {
1174           uid = pkt.pkt.user_id;
1175           ++uid_no;
1176         }
1177
1178       for (n=0; n < ndesc; n++)
1179         {
1180           switch (desc[n].mode) {
1181           case KEYDB_SEARCH_MODE_NONE:
1182             BUG ();
1183             break;
1184           case KEYDB_SEARCH_MODE_EXACT:
1185           case KEYDB_SEARCH_MODE_SUBSTR:
1186           case KEYDB_SEARCH_MODE_MAIL:
1187           case KEYDB_SEARCH_MODE_MAILSUB:
1188           case KEYDB_SEARCH_MODE_MAILEND:
1189           case KEYDB_SEARCH_MODE_WORDS:
1190             if ( uid && !compare_name (desc[n].mode,
1191                                        desc[n].u.name,
1192                                        uid->name, uid->len))
1193               goto found;
1194             break;
1195
1196           case KEYDB_SEARCH_MODE_SHORT_KID:
1197             if (pk && desc[n].u.kid[1] == aki[1])
1198               goto found;
1199             break;
1200           case KEYDB_SEARCH_MODE_LONG_KID:
1201             if (pk && desc[n].u.kid[0] == aki[0]
1202                 && desc[n].u.kid[1] == aki[1])
1203               goto found;
1204             break;
1205           case KEYDB_SEARCH_MODE_FPR16:
1206             if (pk && !memcmp (desc[n].u.fpr, afp, 16))
1207               goto found;
1208             break;
1209           case KEYDB_SEARCH_MODE_FPR20:
1210           case KEYDB_SEARCH_MODE_FPR:
1211             if (pk && !memcmp (desc[n].u.fpr, afp, 20))
1212               goto found;
1213             break;
1214           case KEYDB_SEARCH_MODE_FIRST:
1215             if (pk)
1216               goto found;
1217             break;
1218           case KEYDB_SEARCH_MODE_NEXT:
1219             if (pk)
1220               goto found;
1221             break;
1222           default:
1223             rc = GPG_ERR_INV_ARG;
1224             goto found;
1225           }
1226         }
1227       free_packet (&pkt);
1228       continue;
1229     found:
1230       if (rc)
1231         goto real_found;
1232
1233       if (DBG_LOOKUP)
1234         log_debug ("%s: packet starting at offset %lld matched descriptor %zu\n"
1235                    , __func__, (long long)offset, n);
1236
1237       /* Record which desc we matched on.  Note this value is only
1238          meaningful if this function returns with no errors. */
1239       if(descindex)
1240         *descindex=n;
1241       for (n=any_skip?0:ndesc; n < ndesc; n++)
1242         {
1243           if (desc[n].skipfnc
1244               && desc[n].skipfnc (desc[n].skipfncvalue, aki, uid_no))
1245             {
1246               if (DBG_LOOKUP)
1247                 log_debug ("%s: skipping match: desc %zd's skip function returned TRUE\n",
1248                            __func__, n);
1249               break;
1250             }
1251         }
1252       if (n == ndesc)
1253         goto real_found;
1254       free_packet (&pkt);
1255     }
1256  real_found:
1257   if (!rc)
1258     {
1259       if (DBG_LOOKUP)
1260         log_debug ("%s: returning success\n", __func__);
1261       hd->found.offset = main_offset;
1262       hd->found.kr = hd->current.kr;
1263       hd->found.pk_no = pk? pk_no : 0;
1264       hd->found.uid_no = uid? uid_no : 0;
1265     }
1266   else if (rc == -1)
1267     {
1268       if (DBG_LOOKUP)
1269         log_debug ("%s: no matches (EOF)\n", __func__);
1270
1271       hd->current.eof = 1;
1272       /* if we scanned all keyrings, we are sure that
1273        * all known key IDs are in our offtbl, mark that. */
1274       if (use_key_present_hash
1275           && !key_present_hash_ready
1276           && scanned_from_start)
1277         {
1278           KR_RESOURCE kr;
1279
1280           /* First set the did_full_scan flag for this keyring.  */
1281           for (kr=kr_resources; kr; kr = kr->next)
1282             {
1283               if (hd->resource == kr)
1284                 {
1285                   kr->did_full_scan = 1;
1286                   break;
1287                 }
1288             }
1289           /* Then check whether all flags are set and if so, mark the
1290              offtbl ready */
1291           for (kr=kr_resources; kr; kr = kr->next)
1292             {
1293               if (!kr->did_full_scan)
1294                 break;
1295             }
1296           if (!kr)
1297             key_present_hash_ready = 1;
1298         }
1299     }
1300   else
1301     {
1302       if (DBG_LOOKUP)
1303         log_debug ("%s: error encountered during search: %s (%d)\n",
1304                    __func__, gpg_strerror (rc), rc);
1305       hd->current.error = rc;
1306     }
1307
1308   free_packet(&pkt);
1309   set_packet_list_mode(save_mode);
1310   return rc;
1311 }
1312
1313
1314 static int
1315 create_tmp_file (const char *template,
1316                  char **r_bakfname, char **r_tmpfname, IOBUF *r_fp)
1317 {
1318   gpg_error_t err;
1319   mode_t oldmask;
1320
1321   err = keybox_tmp_names (template, 1, r_bakfname, r_tmpfname);
1322   if (err)
1323     return err;
1324
1325   /* Create the temp file with limited access.  Note that the umask
1326      call is not anymore needed because iobuf_create now takes care of
1327      it.  However, it does not harm and thus we keep it.  */
1328   oldmask = umask (077);
1329   if (is_secured_filename (*r_tmpfname))
1330     {
1331       *r_fp = NULL;
1332       gpg_err_set_errno (EPERM);
1333     }
1334   else
1335     *r_fp = iobuf_create (*r_tmpfname, 1);
1336   umask (oldmask);
1337   if (!*r_fp)
1338     {
1339       err = gpg_error_from_syserror ();
1340       log_error (_("can't create '%s': %s\n"), *r_tmpfname, gpg_strerror (err));
1341       xfree (*r_tmpfname);
1342       *r_tmpfname = NULL;
1343       xfree (*r_bakfname);
1344       *r_bakfname = NULL;
1345     }
1346
1347   return err;
1348 }
1349
1350
1351 static int
1352 rename_tmp_file (const char *bakfname, const char *tmpfname, const char *fname)
1353 {
1354   int rc = 0;
1355   int block = 0;
1356
1357   /* Invalidate close caches.  */
1358   if (iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)tmpfname ))
1359     {
1360       rc = gpg_error_from_syserror ();
1361       goto fail;
1362     }
1363   iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)bakfname );
1364   iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname );
1365
1366   /* First make a backup file. */
1367   block = 1;
1368   rc = gnupg_rename_file (fname, bakfname, &block);
1369   if (rc)
1370     goto fail;
1371
1372   /* then rename the file */
1373   rc = gnupg_rename_file (tmpfname, fname, NULL);
1374   if (block)
1375     {
1376       gnupg_unblock_all_signals ();
1377       block = 0;
1378     }
1379   if (rc)
1380     {
1381       register_secured_file (fname);
1382       goto fail;
1383     }
1384
1385   /* Now make sure the file has the same permissions as the original */
1386 #ifndef HAVE_DOSISH_SYSTEM
1387   {
1388     struct stat statbuf;
1389
1390     statbuf.st_mode=S_IRUSR | S_IWUSR;
1391
1392     if (!stat (bakfname, &statbuf) && !chmod (fname, statbuf.st_mode))
1393       ;
1394     else
1395       log_error ("WARNING: unable to restore permissions to '%s': %s",
1396                  fname, strerror(errno));
1397   }
1398 #endif
1399
1400   return 0;
1401
1402  fail:
1403   if (block)
1404     gnupg_unblock_all_signals ();
1405   return rc;
1406 }
1407
1408
1409 static int
1410 write_keyblock (IOBUF fp, KBNODE keyblock)
1411 {
1412   KBNODE kbctx = NULL, node;
1413   int rc;
1414
1415   while ( (node = walk_kbnode (keyblock, &kbctx, 0)) )
1416     {
1417       if (node->pkt->pkttype == PKT_RING_TRUST)
1418         continue; /* we write it later on our own */
1419
1420       if ( (rc = build_packet (fp, node->pkt) ))
1421         {
1422           log_error ("build_packet(%d) failed: %s\n",
1423                      node->pkt->pkttype, gpg_strerror (rc) );
1424           return rc;
1425         }
1426       if (node->pkt->pkttype == PKT_SIGNATURE)
1427         { /* always write a signature cache packet */
1428           PKT_signature *sig = node->pkt->pkt.signature;
1429           unsigned int cacheval = 0;
1430
1431           if (sig->flags.checked)
1432             {
1433               cacheval |= 1;
1434               if (sig->flags.valid)
1435                 cacheval |= 2;
1436             }
1437           iobuf_put (fp, 0xb0); /* old style packet 12, 1 byte len*/
1438           iobuf_put (fp, 2);    /* 2 bytes */
1439           iobuf_put (fp, 0);    /* unused */
1440           if (iobuf_put (fp, cacheval))
1441             {
1442               rc = gpg_error_from_syserror ();
1443               log_error ("writing sigcache packet failed\n");
1444               return rc;
1445             }
1446         }
1447     }
1448   return 0;
1449 }
1450
1451 /*
1452  * Walk over all public keyrings, check the signatures and replace the
1453  * keyring with a new one where the signature cache is then updated.
1454  * This is only done for the public keyrings.
1455  */
1456 int
1457 keyring_rebuild_cache (void *token,int noisy)
1458 {
1459   KEYRING_HANDLE hd;
1460   KEYDB_SEARCH_DESC desc;
1461   KBNODE keyblock = NULL, node;
1462   const char *lastresname = NULL, *resname;
1463   IOBUF tmpfp = NULL;
1464   char *tmpfilename = NULL;
1465   char *bakfilename = NULL;
1466   int rc;
1467   ulong count = 0, sigcount = 0;
1468
1469   hd = keyring_new (token);
1470   if (!hd)
1471     return gpg_error_from_syserror ();
1472   memset (&desc, 0, sizeof desc);
1473   desc.mode = KEYDB_SEARCH_MODE_FIRST;
1474
1475   rc=keyring_lock (hd, 1);
1476   if(rc)
1477     goto leave;
1478
1479   for (;;)
1480     {
1481       rc = keyring_search (hd, &desc, 1, NULL, 1 /* ignore_legacy */);
1482       if (rc)
1483         break;  /* ready.  */
1484
1485       desc.mode = KEYDB_SEARCH_MODE_NEXT;
1486       resname = keyring_get_resource_name (hd);
1487       if (lastresname != resname )
1488         { /* we have switched to a new keyring - commit changes */
1489           if (tmpfp)
1490             {
1491               if (iobuf_close (tmpfp))
1492                 {
1493                   rc = gpg_error_from_syserror ();
1494                   log_error ("error closing '%s': %s\n",
1495                              tmpfilename, strerror (errno));
1496                   goto leave;
1497                 }
1498               /* because we have switched resources, we can be sure that
1499                * the original file is closed */
1500               tmpfp = NULL;
1501             }
1502           /* Static analyzer note: BAKFILENAME is never NULL here
1503              because it is controlled by LASTRESNAME.  */
1504           rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1505                                              lastresname) : 0;
1506           xfree (tmpfilename);  tmpfilename = NULL;
1507           xfree (bakfilename);  bakfilename = NULL;
1508           if (rc)
1509             goto leave;
1510           lastresname = resname;
1511           if (noisy && !opt.quiet)
1512             log_info (_("caching keyring '%s'\n"), resname);
1513           rc = create_tmp_file (resname, &bakfilename, &tmpfilename, &tmpfp);
1514           if (rc)
1515             goto leave;
1516         }
1517
1518       release_kbnode (keyblock);
1519       rc = keyring_get_keyblock (hd, &keyblock);
1520       if (rc)
1521         {
1522           if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY)
1523             continue;  /* Skip legacy keys.  */
1524           log_error ("keyring_get_keyblock failed: %s\n", gpg_strerror (rc));
1525           goto leave;
1526         }
1527       if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1528         {
1529           /* We had a few reports about corrupted keyrings; if we have
1530              been called directly from the command line we delete such
1531              a keyblock instead of bailing out.  */
1532           log_error ("unexpected keyblock found (pkttype=%d)%s\n",
1533                      keyblock->pkt->pkttype, noisy? " - deleted":"");
1534           if (noisy)
1535             continue;
1536           log_info ("Hint: backup your keys and try running '%s'\n",
1537                     "gpg --rebuild-keydb-caches");
1538           rc = gpg_error (GPG_ERR_INV_KEYRING);
1539           goto leave;
1540         }
1541
1542       if (keyblock->pkt->pkt.public_key->version < 4)
1543         {
1544           /* We do not copy/cache v3 keys or any other unknown
1545              packets.  It is better to remove them from the keyring.
1546              The code required to keep them in the keyring would be
1547              too complicated.  Given that we do not touch the old
1548              secring.gpg a suitable backup for decryption of v3 stuff
1549              using an older gpg version will always be available.
1550              Note: This test is actually superfluous because we
1551              already acted upon GPG_ERR_LEGACY_KEY.      */
1552         }
1553       else
1554         {
1555           /* Check all signature to set the signature's cache flags. */
1556           for (node=keyblock; node; node=node->next)
1557             {
1558               /* Note that this doesn't cache the result of a
1559                  revocation issued by a designated revoker.  This is
1560                  because the pk in question does not carry the revkeys
1561                  as we haven't merged the key and selfsigs.  It is
1562                  questionable whether this matters very much since
1563                  there are very very few designated revoker revocation
1564                  packets out there. */
1565               if (node->pkt->pkttype == PKT_SIGNATURE)
1566                 {
1567                   PKT_signature *sig=node->pkt->pkt.signature;
1568
1569                   if(!opt.no_sig_cache && sig->flags.checked && sig->flags.valid
1570                      && (openpgp_md_test_algo(sig->digest_algo)
1571                          || openpgp_pk_test_algo(sig->pubkey_algo)))
1572                     sig->flags.checked=sig->flags.valid=0;
1573                   else
1574                     check_key_signature (keyblock, node, NULL);
1575
1576                   sigcount++;
1577                 }
1578             }
1579
1580           /* Write the keyblock to the temporary file.  */
1581           rc = write_keyblock (tmpfp, keyblock);
1582           if (rc)
1583             goto leave;
1584
1585           if ( !(++count % 50) && noisy && !opt.quiet)
1586             log_info (ngettext("%lu keys cached so far (%lu signature)\n",
1587                                "%lu keys cached so far (%lu signatures)\n",
1588                                sigcount),
1589                       count, sigcount);
1590         }
1591     } /* end main loop */
1592   if (rc == -1)
1593     rc = 0;
1594   if (rc)
1595     {
1596       log_error ("keyring_search failed: %s\n", gpg_strerror (rc));
1597       goto leave;
1598     }
1599
1600   if (noisy || opt.verbose)
1601     {
1602       log_info (ngettext("%lu key cached",
1603                          "%lu keys cached", count), count);
1604       log_printf (ngettext(" (%lu signature)\n",
1605                            " (%lu signatures)\n", sigcount), sigcount);
1606     }
1607
1608   if (tmpfp)
1609     {
1610       if (iobuf_close (tmpfp))
1611         {
1612           rc = gpg_error_from_syserror ();
1613           log_error ("error closing '%s': %s\n",
1614                      tmpfilename, strerror (errno));
1615           goto leave;
1616         }
1617       /* because we have switched resources, we can be sure that
1618        * the original file is closed */
1619       tmpfp = NULL;
1620     }
1621   rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1622                                      lastresname) : 0;
1623   xfree (tmpfilename);  tmpfilename = NULL;
1624   xfree (bakfilename);  bakfilename = NULL;
1625
1626  leave:
1627   if (tmpfp)
1628     iobuf_cancel (tmpfp);
1629   xfree (tmpfilename);
1630   xfree (bakfilename);
1631   release_kbnode (keyblock);
1632   keyring_lock (hd, 0);
1633   keyring_release (hd);
1634   return rc;
1635 }
1636
1637 \f
1638 /****************
1639  * Perform insert/delete/update operation.
1640  * mode 1 = insert
1641  *      2 = delete
1642  *      3 = update
1643  */
1644 static int
1645 do_copy (int mode, const char *fname, KBNODE root,
1646          off_t start_offset, unsigned int n_packets )
1647 {
1648     IOBUF fp, newfp;
1649     int rc=0;
1650     char *bakfname = NULL;
1651     char *tmpfname = NULL;
1652
1653     /* Open the source file. Because we do a rename, we have to check the
1654        permissions of the file */
1655     if (access (fname, W_OK))
1656       return gpg_error_from_syserror ();
1657
1658     fp = iobuf_open (fname);
1659     if (mode == 1 && !fp && errno == ENOENT) {
1660         /* insert mode but file does not exist: create a new file */
1661         KBNODE kbctx, node;
1662         mode_t oldmask;
1663
1664         oldmask=umask(077);
1665         if (is_secured_filename (fname)) {
1666             newfp = NULL;
1667             gpg_err_set_errno (EPERM);
1668         }
1669         else
1670             newfp = iobuf_create (fname, 1);
1671         umask(oldmask);
1672         if( !newfp )
1673           {
1674             rc = gpg_error_from_syserror ();
1675             log_error (_("can't create '%s': %s\n"), fname, strerror(errno));
1676             return rc;
1677           }
1678         if( !opt.quiet )
1679             log_info(_("%s: keyring created\n"), fname );
1680
1681         kbctx=NULL;
1682         while ( (node = walk_kbnode( root, &kbctx, 0 )) ) {
1683             if( (rc = build_packet( newfp, node->pkt )) ) {
1684                 log_error("build_packet(%d) failed: %s\n",
1685                             node->pkt->pkttype, gpg_strerror (rc) );
1686                 iobuf_cancel(newfp);
1687                 return rc;
1688             }
1689         }
1690         if( iobuf_close(newfp) ) {
1691             rc = gpg_error_from_syserror ();
1692             log_error ("%s: close failed: %s\n", fname, strerror(errno));
1693             return rc;
1694         }
1695         return 0; /* ready */
1696     }
1697
1698     if( !fp )
1699       {
1700         rc = gpg_error_from_syserror ();
1701         log_error(_("can't open '%s': %s\n"), fname, strerror(errno) );
1702         goto leave;
1703       }
1704
1705     /* Create the new file.  */
1706     rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp);
1707     if (rc) {
1708         iobuf_close(fp);
1709         goto leave;
1710     }
1711
1712     if( mode == 1 ) { /* insert */
1713         /* copy everything to the new file */
1714         rc = copy_all_packets (fp, newfp);
1715         if( rc != -1 ) {
1716             log_error("%s: copy to '%s' failed: %s\n",
1717                       fname, tmpfname, gpg_strerror (rc) );
1718             iobuf_close(fp);
1719             iobuf_cancel(newfp);
1720             goto leave;
1721         }
1722     }
1723
1724     if( mode == 2 || mode == 3 ) { /* delete or update */
1725         /* copy first part to the new file */
1726         rc = copy_some_packets( fp, newfp, start_offset );
1727         if( rc ) { /* should never get EOF here */
1728             log_error ("%s: copy to '%s' failed: %s\n",
1729                        fname, tmpfname, gpg_strerror (rc) );
1730             iobuf_close(fp);
1731             iobuf_cancel(newfp);
1732             goto leave;
1733         }
1734         /* skip this keyblock */
1735         log_assert( n_packets );
1736         rc = skip_some_packets( fp, n_packets );
1737         if( rc ) {
1738             log_error("%s: skipping %u packets failed: %s\n",
1739                             fname, n_packets, gpg_strerror (rc));
1740             iobuf_close(fp);
1741             iobuf_cancel(newfp);
1742             goto leave;
1743         }
1744     }
1745
1746     if( mode == 1 || mode == 3 ) { /* insert or update */
1747         rc = write_keyblock (newfp, root);
1748         if (rc) {
1749           iobuf_close(fp);
1750           iobuf_cancel(newfp);
1751           goto leave;
1752         }
1753     }
1754
1755     if( mode == 2 || mode == 3 ) { /* delete or update */
1756         /* copy the rest */
1757         rc = copy_all_packets( fp, newfp );
1758         if( rc != -1 ) {
1759             log_error("%s: copy to '%s' failed: %s\n",
1760                       fname, tmpfname, gpg_strerror (rc) );
1761             iobuf_close(fp);
1762             iobuf_cancel(newfp);
1763             goto leave;
1764         }
1765     }
1766
1767     /* close both files */
1768     if( iobuf_close(fp) ) {
1769         rc = gpg_error_from_syserror ();
1770         log_error("%s: close failed: %s\n", fname, strerror(errno) );
1771         goto leave;
1772     }
1773     if( iobuf_close(newfp) ) {
1774         rc = gpg_error_from_syserror ();
1775         log_error("%s: close failed: %s\n", tmpfname, strerror(errno) );
1776         goto leave;
1777     }
1778
1779     rc = rename_tmp_file (bakfname, tmpfname, fname);
1780
1781   leave:
1782     xfree(bakfname);
1783     xfree(tmpfname);
1784     return rc;
1785 }