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