Ported changes from 1.4.
[gnupg.git] / g10 / keyring.c
blob00a5bb986292202d5fbf3a4d255668db84076b4b
1 /* keyring.c - keyring file handling
2 * Copyright (C) 2001, 2004, 2009 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include <config.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <assert.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
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"
39 /* off_item is a funny named for an object used to keep track of known
40 * keys. The idea was to use the offset to seek to the known keyblock, but
41 * this is not possible if more than one process is using the keyring.
43 struct off_item {
44 struct off_item *next;
45 u32 kid[2];
46 /*off_t off;*/
49 typedef struct off_item **OffsetHashTable;
52 typedef struct keyring_name *KR_NAME;
53 struct keyring_name {
54 struct keyring_name *next;
55 int secret;
56 DOTLOCK lockhd;
57 int is_locked;
58 int did_full_scan;
59 char fname[1];
61 typedef struct keyring_name const * CONST_KR_NAME;
63 static KR_NAME kr_names;
64 static int active_handles;
66 static OffsetHashTable kr_offtbl;
67 static int kr_offtbl_ready;
70 struct keyring_handle {
71 CONST_KR_NAME resource;
72 int secret; /* this is for a secret keyring */
73 struct {
74 CONST_KR_NAME kr;
75 IOBUF iobuf;
76 int eof;
77 int error;
78 } current;
79 struct {
80 CONST_KR_NAME kr;
81 off_t offset;
82 size_t pk_no;
83 size_t uid_no;
84 unsigned int n_packets; /*used for delete and update*/
85 } found;
86 struct {
87 char *name;
88 char *pattern;
89 } word_match;
94 static int do_copy (int mode, const char *fname, KBNODE root, int secret,
95 off_t start_offset, unsigned int n_packets );
99 static struct off_item *
100 new_offset_item (void)
102 struct off_item *k;
104 k = xmalloc_clear (sizeof *k);
105 return k;
108 #if 0
109 static void
110 release_offset_items (struct off_item *k)
112 struct off_item *k2;
114 for (; k; k = k2)
116 k2 = k->next;
117 xfree (k);
120 #endif
122 static OffsetHashTable
123 new_offset_hash_table (void)
125 struct off_item **tbl;
127 tbl = xmalloc_clear (2048 * sizeof *tbl);
128 return tbl;
131 #if 0
132 static void
133 release_offset_hash_table (OffsetHashTable tbl)
135 int i;
137 if (!tbl)
138 return;
139 for (i=0; i < 2048; i++)
140 release_offset_items (tbl[i]);
141 xfree (tbl);
143 #endif
145 static struct off_item *
146 lookup_offset_hash_table (OffsetHashTable tbl, u32 *kid)
148 struct off_item *k;
150 for (k = tbl[(kid[1] & 0x07ff)]; k; k = k->next)
151 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
152 return k;
153 return NULL;
156 static void
157 update_offset_hash_table (OffsetHashTable tbl, u32 *kid, off_t off)
159 struct off_item *k;
161 (void)off;
163 for (k = tbl[(kid[1] & 0x07ff)]; k; k = k->next)
165 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
167 /*k->off = off;*/
168 return;
172 k = new_offset_item ();
173 k->kid[0] = kid[0];
174 k->kid[1] = kid[1];
175 /*k->off = off;*/
176 k->next = tbl[(kid[1] & 0x07ff)];
177 tbl[(kid[1] & 0x07ff)] = k;
180 static void
181 update_offset_hash_table_from_kb (OffsetHashTable tbl, KBNODE node, off_t off)
183 for (; node; node = node->next)
185 if (node->pkt->pkttype == PKT_PUBLIC_KEY
186 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
188 u32 aki[2];
189 keyid_from_pk (node->pkt->pkt.public_key, aki);
190 update_offset_hash_table (tbl, aki, off);
196 * Register a filename for plain keyring files. ptr is set to a
197 * pointer to be used to create a handles etc, or the already-issued
198 * pointer if it has already been registered. The function returns 1
199 * if a new keyring was registered.
202 keyring_register_filename (const char *fname, int secret, void **ptr)
204 KR_NAME kr;
206 if (active_handles)
207 BUG (); /* We don't allow that */
209 for (kr=kr_names; kr; kr = kr->next)
211 if (same_file_p (kr->fname, fname))
213 *ptr=kr;
214 return 0; /* Already registered. */
218 if (secret)
219 register_secured_file (fname);
221 kr = xmalloc (sizeof *kr + strlen (fname));
222 strcpy (kr->fname, fname);
223 kr->secret = !!secret;
224 kr->lockhd = NULL;
225 kr->is_locked = 0;
226 kr->did_full_scan = 0;
227 /* keep a list of all issued pointers */
228 kr->next = kr_names;
229 kr_names = kr;
231 /* create the offset table the first time a function here is used */
232 if (!kr_offtbl)
233 kr_offtbl = new_offset_hash_table ();
235 *ptr=kr;
237 return 1;
241 keyring_is_writable (void *token)
243 KR_NAME r = token;
245 return r? !access (r->fname, W_OK) : 0;
250 /* Create a new handle for the resource associated with TOKEN. SECRET
251 is just just as a cross-check.
253 The returned handle must be released using keyring_release (). */
254 KEYRING_HANDLE
255 keyring_new (void *token, int secret)
257 KEYRING_HANDLE hd;
258 KR_NAME resource = token;
260 assert (resource && !resource->secret == !secret);
262 hd = xmalloc_clear (sizeof *hd);
263 hd->resource = resource;
264 hd->secret = !!secret;
265 active_handles++;
266 return hd;
269 void
270 keyring_release (KEYRING_HANDLE hd)
272 if (!hd)
273 return;
274 assert (active_handles > 0);
275 active_handles--;
276 xfree (hd->word_match.name);
277 xfree (hd->word_match.pattern);
278 iobuf_close (hd->current.iobuf);
279 xfree (hd);
283 const char *
284 keyring_get_resource_name (KEYRING_HANDLE hd)
286 if (!hd || !hd->resource)
287 return NULL;
288 return hd->resource->fname;
293 * Lock the keyring with the given handle, or unlock if YES is false.
294 * We ignore the handle and lock all registered files.
296 int
297 keyring_lock (KEYRING_HANDLE hd, int yes)
299 KR_NAME kr;
300 int rc = 0;
302 (void)hd;
304 if (yes) {
305 /* first make sure the lock handles are created */
306 for (kr=kr_names; kr; kr = kr->next) {
307 if (!keyring_is_writable(kr))
308 continue;
309 if (!kr->lockhd) {
310 kr->lockhd = create_dotlock( kr->fname );
311 if (!kr->lockhd) {
312 log_info ("can't allocate lock for `%s'\n", kr->fname );
313 rc = G10ERR_GENERAL;
317 if (rc)
318 return rc;
320 /* and now set the locks */
321 for (kr=kr_names; kr; kr = kr->next) {
322 if (!keyring_is_writable(kr))
323 continue;
324 if (kr->is_locked)
326 else if (make_dotlock (kr->lockhd, -1) ) {
327 log_info ("can't lock `%s'\n", kr->fname );
328 rc = G10ERR_GENERAL;
330 else
331 kr->is_locked = 1;
335 if (rc || !yes) {
336 for (kr=kr_names; kr; kr = kr->next) {
337 if (!keyring_is_writable(kr))
338 continue;
339 if (!kr->is_locked)
341 else if (release_dotlock (kr->lockhd))
342 log_info ("can't unlock `%s'\n", kr->fname );
343 else
344 kr->is_locked = 0;
348 return rc;
354 * Return the last found keyring. Caller must free it.
355 * The returned keyblock has the kbode flag bit 0 set for the node with
356 * the public key used to locate the keyblock or flag bit 1 set for
357 * the user ID node.
360 keyring_get_keyblock (KEYRING_HANDLE hd, KBNODE *ret_kb)
362 PACKET *pkt;
363 int rc;
364 KBNODE keyblock = NULL, node, lastnode;
365 IOBUF a;
366 int in_cert = 0;
367 int pk_no = 0;
368 int uid_no = 0;
369 int save_mode;
371 if (ret_kb)
372 *ret_kb = NULL;
374 if (!hd->found.kr)
375 return -1; /* no successful search */
377 a = iobuf_open (hd->found.kr->fname);
378 if (!a)
380 log_error(_("can't open `%s'\n"), hd->found.kr->fname);
381 return G10ERR_KEYRING_OPEN;
384 if (iobuf_seek (a, hd->found.offset) ) {
385 log_error ("can't seek `%s'\n", hd->found.kr->fname);
386 iobuf_close(a);
387 return G10ERR_KEYRING_OPEN;
390 pkt = xmalloc (sizeof *pkt);
391 init_packet (pkt);
392 hd->found.n_packets = 0;;
393 lastnode = NULL;
394 save_mode = set_packet_list_mode(0);
395 while ((rc=parse_packet (a, pkt)) != -1) {
396 hd->found.n_packets++;
397 if (rc == G10ERR_UNKNOWN_PACKET) {
398 free_packet (pkt);
399 init_packet (pkt);
400 continue;
402 if (rc) {
403 log_error ("keyring_get_keyblock: read error: %s\n",
404 g10_errstr(rc) );
405 rc = G10ERR_INV_KEYRING;
406 break;
408 if (pkt->pkttype == PKT_COMPRESSED) {
409 log_error ("skipped compressed packet in keyring\n");
410 free_packet(pkt);
411 init_packet(pkt);
412 continue;
415 if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
416 || pkt->pkttype == PKT_SECRET_KEY)) {
417 hd->found.n_packets--; /* fix counter */
418 break; /* ready */
421 in_cert = 1;
422 if (pkt->pkttype == PKT_RING_TRUST) {
423 /*(this code is duplicated after the loop)*/
424 if ( lastnode
425 && lastnode->pkt->pkttype == PKT_SIGNATURE
426 && (pkt->pkt.ring_trust->sigcache & 1) ) {
427 /* this is a ring trust packet with a checked signature
428 * status cache following directly a signature paket.
429 * Set the cache status into that signature packet */
430 PKT_signature *sig = lastnode->pkt->pkt.signature;
432 sig->flags.checked = 1;
433 sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
435 /* reset lastnode, so that we set the cache status only from
436 * the ring trust packet immediately folling a signature */
437 lastnode = NULL;
439 else {
440 node = lastnode = new_kbnode (pkt);
441 if (!keyblock)
442 keyblock = node;
443 else
444 add_kbnode (keyblock, node);
446 if ( pkt->pkttype == PKT_PUBLIC_KEY
447 || pkt->pkttype == PKT_PUBLIC_SUBKEY
448 || pkt->pkttype == PKT_SECRET_KEY
449 || pkt->pkttype == PKT_SECRET_SUBKEY) {
450 if (++pk_no == hd->found.pk_no)
451 node->flag |= 1;
453 else if ( pkt->pkttype == PKT_USER_ID) {
454 if (++uid_no == hd->found.uid_no)
455 node->flag |= 2;
459 pkt = xmalloc (sizeof *pkt);
460 init_packet(pkt);
462 set_packet_list_mode(save_mode);
464 if (rc == -1 && keyblock)
465 rc = 0; /* got the entire keyblock */
467 if (rc || !ret_kb)
468 release_kbnode (keyblock);
469 else {
470 /*(duplicated form the loop body)*/
471 if ( pkt && pkt->pkttype == PKT_RING_TRUST
472 && lastnode
473 && lastnode->pkt->pkttype == PKT_SIGNATURE
474 && (pkt->pkt.ring_trust->sigcache & 1) ) {
475 PKT_signature *sig = lastnode->pkt->pkt.signature;
476 sig->flags.checked = 1;
477 sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
479 *ret_kb = keyblock;
481 free_packet (pkt);
482 xfree (pkt);
483 iobuf_close(a);
485 /* Make sure that future search operations fail immediately when
486 * we know that we are working on a invalid keyring
488 if (rc == G10ERR_INV_KEYRING)
489 hd->current.error = rc;
491 return rc;
495 keyring_update_keyblock (KEYRING_HANDLE hd, KBNODE kb)
497 int rc;
499 if (!hd->found.kr)
500 return -1; /* no successful prior search */
502 if (!hd->found.n_packets) {
503 /* need to know the number of packets - do a dummy get_keyblock*/
504 rc = keyring_get_keyblock (hd, NULL);
505 if (rc) {
506 log_error ("re-reading keyblock failed: %s\n", g10_errstr (rc));
507 return rc;
509 if (!hd->found.n_packets)
510 BUG ();
513 /* The open iobuf isn't needed anymore and in fact is a problem when
514 it comes to renaming the keyring files on some operating systems,
515 so close it here */
516 iobuf_close(hd->current.iobuf);
517 hd->current.iobuf = NULL;
519 /* do the update */
520 rc = do_copy (3, hd->found.kr->fname, kb, hd->secret,
521 hd->found.offset, hd->found.n_packets );
522 if (!rc) {
523 if (!hd->secret && kr_offtbl)
525 update_offset_hash_table_from_kb (kr_offtbl, kb, 0);
527 /* better reset the found info */
528 hd->found.kr = NULL;
529 hd->found.offset = 0;
531 return rc;
535 keyring_insert_keyblock (KEYRING_HANDLE hd, KBNODE kb)
537 int rc;
538 const char *fname;
540 if (!hd)
541 fname = NULL;
542 else if (hd->found.kr)
543 fname = hd->found.kr->fname;
544 else if (hd->current.kr)
545 fname = hd->current.kr->fname;
546 else
547 fname = hd->resource? hd->resource->fname:NULL;
549 if (!fname)
550 return G10ERR_GENERAL;
552 /* close this one otherwise we will lose the position for
553 * a next search. Fixme: it would be better to adjust the position
554 * after the write opertions.
556 iobuf_close (hd->current.iobuf);
557 hd->current.iobuf = NULL;
559 /* do the insert */
560 rc = do_copy (1, fname, kb, hd->secret, 0, 0 );
561 if (!rc && !hd->secret && kr_offtbl)
563 update_offset_hash_table_from_kb (kr_offtbl, kb, 0);
566 return rc;
571 keyring_delete_keyblock (KEYRING_HANDLE hd)
573 int rc;
575 if (!hd->found.kr)
576 return -1; /* no successful prior search */
578 if (!hd->found.n_packets) {
579 /* need to know the number of packets - do a dummy get_keyblock*/
580 rc = keyring_get_keyblock (hd, NULL);
581 if (rc) {
582 log_error ("re-reading keyblock failed: %s\n", g10_errstr (rc));
583 return rc;
585 if (!hd->found.n_packets)
586 BUG ();
589 /* close this one otherwise we will lose the position for
590 * a next search. Fixme: it would be better to adjust the position
591 * after the write opertions.
593 iobuf_close (hd->current.iobuf);
594 hd->current.iobuf = NULL;
596 /* do the delete */
597 rc = do_copy (2, hd->found.kr->fname, NULL, hd->secret,
598 hd->found.offset, hd->found.n_packets );
599 if (!rc) {
600 /* better reset the found info */
601 hd->found.kr = NULL;
602 hd->found.offset = 0;
603 /* Delete is a rare operations, so we don't remove the keys
604 * from the offset table */
606 return rc;
612 * Start the next search on this handle right at the beginning
614 int
615 keyring_search_reset (KEYRING_HANDLE hd)
617 assert (hd);
619 hd->current.kr = NULL;
620 iobuf_close (hd->current.iobuf);
621 hd->current.iobuf = NULL;
622 hd->current.eof = 0;
623 hd->current.error = 0;
625 hd->found.kr = NULL;
626 hd->found.offset = 0;
627 return 0;
631 static int
632 prepare_search (KEYRING_HANDLE hd)
634 if (hd->current.error)
635 return hd->current.error; /* still in error state */
637 if (hd->current.kr && !hd->current.eof) {
638 if ( !hd->current.iobuf )
639 return G10ERR_GENERAL; /* position invalid after a modify */
640 return 0; /* okay */
643 if (!hd->current.kr && hd->current.eof)
644 return -1; /* still EOF */
646 if (!hd->current.kr) { /* start search with first keyring */
647 hd->current.kr = hd->resource;
648 if (!hd->current.kr) {
649 hd->current.eof = 1;
650 return -1; /* keyring not available */
652 assert (!hd->current.iobuf);
654 else { /* EOF */
655 iobuf_close (hd->current.iobuf);
656 hd->current.iobuf = NULL;
657 hd->current.kr = NULL;
658 hd->current.eof = 1;
659 return -1;
662 hd->current.eof = 0;
663 hd->current.iobuf = iobuf_open (hd->current.kr->fname);
664 if (!hd->current.iobuf)
666 hd->current.error = gpg_error_from_syserror ();
667 log_error(_("can't open `%s'\n"), hd->current.kr->fname );
668 return hd->current.error;
671 return 0;
675 /* A map of the all characters valid used for word_match()
676 * Valid characters are in in this table converted to uppercase.
677 * because the upper 128 bytes have special meaning, we assume
678 * that they are all valid.
679 * Note: We must use numerical values here in case that this program
680 * will be converted to those little blue HAL9000s with their strange
681 * EBCDIC character set (user ids are UTF-8).
682 * wk 2000-04-13: Hmmm, does this really make sense, given the fact that
683 * we can run gpg now on a S/390 running GNU/Linux, where the code
684 * translation is done by the device drivers?
686 static const byte word_match_chars[256] = {
687 /* 00 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
688 /* 08 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
689 /* 10 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
690 /* 18 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
691 /* 20 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
692 /* 28 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
693 /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
694 /* 38 */ 0x38, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
695 /* 40 */ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
696 /* 48 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
697 /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
698 /* 58 */ 0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
699 /* 60 */ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
700 /* 68 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
701 /* 70 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
702 /* 78 */ 0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
703 /* 80 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
704 /* 88 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
705 /* 90 */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
706 /* 98 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
707 /* a0 */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
708 /* a8 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
709 /* b0 */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
710 /* b8 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
711 /* c0 */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
712 /* c8 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
713 /* d0 */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
714 /* d8 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
715 /* e0 */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
716 /* e8 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
717 /* f0 */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
718 /* f8 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
721 /****************
722 * Do a word match (original user id starts with a '+').
723 * The pattern is already tokenized to a more suitable format:
724 * There are only the real words in it delimited by one space
725 * and all converted to uppercase.
727 * Returns: 0 if all words match.
729 * Note: This algorithm is a straightforward one and not very
730 * fast. It works for UTF-8 strings. The uidlen should
731 * be removed but due to the fact that old versions of
732 * pgp don't use UTF-8 we still use the length; this should
733 * be fixed in parse-packet (and replace \0 by some special
734 * UTF-8 encoding)
736 static int
737 word_match( const byte *uid, size_t uidlen, const byte *pattern )
739 size_t wlen, n;
740 const byte *p;
741 const byte *s;
743 for( s=pattern; *s; ) {
744 do {
745 /* skip leading delimiters */
746 while( uidlen && !word_match_chars[*uid] )
747 uid++, uidlen--;
748 /* get length of the word */
749 n = uidlen; p = uid;
750 while( n && word_match_chars[*p] )
751 p++, n--;
752 wlen = p - uid;
753 /* and compare against the current word from pattern */
754 for(n=0, p=uid; n < wlen && s[n] != ' ' && s[n] ; n++, p++ ) {
755 if( word_match_chars[*p] != s[n] )
756 break;
758 if( n == wlen && (s[n] == ' ' || !s[n]) )
759 break; /* found */
760 uid += wlen;
761 uidlen -= wlen;
762 } while( uidlen );
763 if( !uidlen )
764 return -1; /* not found */
766 /* advance to next word in pattern */
767 for(; *s != ' ' && *s ; s++ )
769 if( *s )
770 s++ ;
772 return 0; /* found */
775 /****************
776 * prepare word word_match; that is parse the name and
777 * build the pattern.
778 * caller has to free the returned pattern
780 static char*
781 prepare_word_match (const byte *name)
783 byte *pattern, *p;
784 int c;
786 /* the original length is always enough for the pattern */
787 p = pattern = xmalloc(strlen(name)+1);
788 do {
789 /* skip leading delimiters */
790 while( *name && !word_match_chars[*name] )
791 name++;
792 /* copy as long as we don't have a delimiter and convert
793 * to uppercase.
794 * fixme: how can we handle utf8 uppercasing */
795 for( ; *name && (c=word_match_chars[*name]); name++ )
796 *p++ = c;
797 *p++ = ' '; /* append pattern delimiter */
798 } while( *name );
799 p[-1] = 0; /* replace last pattern delimiter by EOS */
801 return pattern;
807 static int
808 compare_name (int mode, const char *name, const char *uid, size_t uidlen)
810 int i;
811 const char *s, *se;
813 if (mode == KEYDB_SEARCH_MODE_EXACT) {
814 for (i=0; name[i] && uidlen; i++, uidlen--)
815 if (uid[i] != name[i])
816 break;
817 if (!uidlen && !name[i])
818 return 0; /* found */
820 else if (mode == KEYDB_SEARCH_MODE_SUBSTR) {
821 if (ascii_memistr( uid, uidlen, name ))
822 return 0;
824 else if ( mode == KEYDB_SEARCH_MODE_MAIL
825 || mode == KEYDB_SEARCH_MODE_MAILSUB
826 || mode == KEYDB_SEARCH_MODE_MAILEND) {
827 for (i=0, s= uid; i < uidlen && *s != '<'; s++, i++)
829 if (i < uidlen) {
830 /* skip opening delim and one char and look for the closing one*/
831 s++; i++;
832 for (se=s+1, i++; i < uidlen && *se != '>'; se++, i++)
834 if (i < uidlen) {
835 i = se - s;
836 if (mode == KEYDB_SEARCH_MODE_MAIL) {
837 if( strlen(name)-2 == i
838 && !ascii_memcasecmp( s, name+1, i) )
839 return 0;
841 else if (mode == KEYDB_SEARCH_MODE_MAILSUB) {
842 if( ascii_memistr( s, i, name ) )
843 return 0;
845 else { /* email from end */
846 /* nyi */
851 else if (mode == KEYDB_SEARCH_MODE_WORDS)
852 return word_match (uid, uidlen, name);
853 else
854 BUG();
856 return -1; /* not found */
861 * Search through the keyring(s), starting at the current position,
862 * for a keyblock which contains one of the keys described in the DESC array.
864 int
865 keyring_search (KEYRING_HANDLE hd, KEYDB_SEARCH_DESC *desc,
866 size_t ndesc, size_t *descindex)
868 int rc;
869 PACKET pkt;
870 int save_mode;
871 off_t offset, main_offset;
872 size_t n;
873 int need_uid, need_words, need_keyid, need_fpr, any_skip;
874 int pk_no, uid_no;
875 int initial_skip;
876 int use_offtbl;
877 PKT_user_id *uid = NULL;
878 PKT_public_key *pk = NULL;
879 PKT_secret_key *sk = NULL;
880 u32 aki[2];
882 /* figure out what information we need */
883 need_uid = need_words = need_keyid = need_fpr = any_skip = 0;
884 for (n=0; n < ndesc; n++)
886 switch (desc[n].mode)
888 case KEYDB_SEARCH_MODE_EXACT:
889 case KEYDB_SEARCH_MODE_SUBSTR:
890 case KEYDB_SEARCH_MODE_MAIL:
891 case KEYDB_SEARCH_MODE_MAILSUB:
892 case KEYDB_SEARCH_MODE_MAILEND:
893 need_uid = 1;
894 break;
895 case KEYDB_SEARCH_MODE_WORDS:
896 need_uid = 1;
897 need_words = 1;
898 break;
899 case KEYDB_SEARCH_MODE_SHORT_KID:
900 case KEYDB_SEARCH_MODE_LONG_KID:
901 need_keyid = 1;
902 break;
903 case KEYDB_SEARCH_MODE_FPR16:
904 case KEYDB_SEARCH_MODE_FPR20:
905 case KEYDB_SEARCH_MODE_FPR:
906 need_fpr = 1;
907 break;
908 case KEYDB_SEARCH_MODE_FIRST:
909 /* always restart the search in this mode */
910 keyring_search_reset (hd);
911 break;
912 default: break;
914 if (desc[n].skipfnc)
916 any_skip = 1;
917 need_keyid = 1;
921 rc = prepare_search (hd);
922 if (rc)
923 return rc;
925 use_offtbl = !hd->secret && kr_offtbl;
926 if (!use_offtbl)
928 else if (!kr_offtbl_ready)
929 need_keyid = 1;
930 else if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID)
932 struct off_item *oi;
934 oi = lookup_offset_hash_table (kr_offtbl, desc[0].u.kid);
935 if (!oi)
936 { /* We know that we don't have this key */
937 hd->found.kr = NULL;
938 hd->current.eof = 1;
939 return -1;
941 /* We could now create a positive search status and return.
942 * However the problem is that another instance of gpg may
943 * have changed the keyring so that the offsets are not valid
944 * anymore - therefore we don't do it
948 if (need_words)
950 const char *name = NULL;
952 log_debug ("word search mode does not yet work\n");
953 /* FIXME: here is a long standing bug in our function and in addition we
954 just use the first search description */
955 for (n=0; n < ndesc && !name; n++)
957 if (desc[n].mode == KEYDB_SEARCH_MODE_WORDS)
958 name = desc[n].u.name;
960 assert (name);
961 if ( !hd->word_match.name || strcmp (hd->word_match.name, name) )
963 /* name changed */
964 xfree (hd->word_match.name);
965 xfree (hd->word_match.pattern);
966 hd->word_match.name = xstrdup (name);
967 hd->word_match.pattern = prepare_word_match (name);
969 name = hd->word_match.pattern;
972 init_packet(&pkt);
973 save_mode = set_packet_list_mode(0);
975 hd->found.kr = NULL;
976 main_offset = 0;
977 pk_no = uid_no = 0;
978 initial_skip = 1; /* skip until we see the start of a keyblock */
979 while (!(rc=search_packet (hd->current.iobuf, &pkt, &offset, need_uid)))
981 byte afp[MAX_FINGERPRINT_LEN];
982 size_t an;
984 if (pkt.pkttype == PKT_PUBLIC_KEY || pkt.pkttype == PKT_SECRET_KEY)
986 main_offset = offset;
987 pk_no = uid_no = 0;
988 initial_skip = 0;
990 if (initial_skip)
992 free_packet (&pkt);
993 continue;
996 pk = NULL;
997 sk = NULL;
998 uid = NULL;
999 if ( pkt.pkttype == PKT_PUBLIC_KEY
1000 || pkt.pkttype == PKT_PUBLIC_SUBKEY)
1002 pk = pkt.pkt.public_key;
1003 ++pk_no;
1005 if (need_fpr) {
1006 fingerprint_from_pk (pk, afp, &an);
1007 while (an < 20) /* fill up to 20 bytes */
1008 afp[an++] = 0;
1010 if (need_keyid)
1011 keyid_from_pk (pk, aki);
1013 if (use_offtbl && !kr_offtbl_ready)
1014 update_offset_hash_table (kr_offtbl, aki, main_offset);
1016 else if (pkt.pkttype == PKT_USER_ID)
1018 uid = pkt.pkt.user_id;
1019 ++uid_no;
1021 else if ( pkt.pkttype == PKT_SECRET_KEY
1022 || pkt.pkttype == PKT_SECRET_SUBKEY)
1024 sk = pkt.pkt.secret_key;
1025 ++pk_no;
1027 if (need_fpr) {
1028 fingerprint_from_sk (sk, afp, &an);
1029 while (an < 20) /* fill up to 20 bytes */
1030 afp[an++] = 0;
1032 if (need_keyid)
1033 keyid_from_sk (sk, aki);
1037 for (n=0; n < ndesc; n++)
1039 switch (desc[n].mode) {
1040 case KEYDB_SEARCH_MODE_NONE:
1041 BUG ();
1042 break;
1043 case KEYDB_SEARCH_MODE_EXACT:
1044 case KEYDB_SEARCH_MODE_SUBSTR:
1045 case KEYDB_SEARCH_MODE_MAIL:
1046 case KEYDB_SEARCH_MODE_MAILSUB:
1047 case KEYDB_SEARCH_MODE_MAILEND:
1048 case KEYDB_SEARCH_MODE_WORDS:
1049 if ( uid && !compare_name (desc[n].mode,
1050 desc[n].u.name,
1051 uid->name, uid->len))
1052 goto found;
1053 break;
1055 case KEYDB_SEARCH_MODE_SHORT_KID:
1056 if ((pk||sk) && desc[n].u.kid[1] == aki[1])
1057 goto found;
1058 break;
1059 case KEYDB_SEARCH_MODE_LONG_KID:
1060 if ((pk||sk) && desc[n].u.kid[0] == aki[0]
1061 && desc[n].u.kid[1] == aki[1])
1062 goto found;
1063 break;
1064 case KEYDB_SEARCH_MODE_FPR16:
1065 if ((pk||sk) && !memcmp (desc[n].u.fpr, afp, 16))
1066 goto found;
1067 break;
1068 case KEYDB_SEARCH_MODE_FPR20:
1069 case KEYDB_SEARCH_MODE_FPR:
1070 if ((pk||sk) && !memcmp (desc[n].u.fpr, afp, 20))
1071 goto found;
1072 break;
1073 case KEYDB_SEARCH_MODE_FIRST:
1074 if (pk||sk)
1075 goto found;
1076 break;
1077 case KEYDB_SEARCH_MODE_NEXT:
1078 if (pk||sk)
1079 goto found;
1080 break;
1081 default:
1082 rc = G10ERR_INV_ARG;
1083 goto found;
1086 free_packet (&pkt);
1087 continue;
1088 found:
1089 /* Record which desc we matched on. Note this value is only
1090 meaningful if this function returns with no errors. */
1091 if(descindex)
1092 *descindex=n;
1093 for (n=any_skip?0:ndesc; n < ndesc; n++)
1095 if (desc[n].skipfnc
1096 && desc[n].skipfnc (desc[n].skipfncvalue, aki, uid))
1097 break;
1099 if (n == ndesc)
1100 goto real_found;
1101 free_packet (&pkt);
1103 real_found:
1104 if (!rc)
1106 hd->found.offset = main_offset;
1107 hd->found.kr = hd->current.kr;
1108 hd->found.pk_no = (pk||sk)? pk_no : 0;
1109 hd->found.uid_no = uid? uid_no : 0;
1111 else if (rc == -1)
1113 hd->current.eof = 1;
1114 /* if we scanned all keyrings, we are sure that
1115 * all known key IDs are in our offtbl, mark that. */
1116 if (use_offtbl && !kr_offtbl_ready)
1118 KR_NAME kr;
1120 /* First set the did_full_scan flag for this keyring (ignore
1121 secret keyrings) */
1122 for (kr=kr_names; kr; kr = kr->next)
1124 if (!kr->secret && hd->resource == kr)
1126 kr->did_full_scan = 1;
1127 break;
1130 /* Then check whether all flags are set and if so, mark the
1131 offtbl ready */
1132 for (kr=kr_names; kr; kr = kr->next)
1134 if (!kr->secret && !kr->did_full_scan)
1135 break;
1137 if (!kr)
1138 kr_offtbl_ready = 1;
1141 else
1142 hd->current.error = rc;
1144 free_packet(&pkt);
1145 set_packet_list_mode(save_mode);
1146 return rc;
1150 static int
1151 create_tmp_file (const char *template,
1152 char **r_bakfname, char **r_tmpfname, IOBUF *r_fp)
1154 char *bakfname, *tmpfname;
1155 mode_t oldmask;
1157 *r_bakfname = NULL;
1158 *r_tmpfname = NULL;
1160 # ifdef USE_ONLY_8DOT3
1161 /* Here is another Windoze bug?:
1162 * you cant rename("pubring.gpg.tmp", "pubring.gpg");
1163 * but rename("pubring.gpg.tmp", "pubring.aaa");
1164 * works. So we replace .gpg by .bak or .tmp
1166 if (strlen (template) > 4
1167 && !strcmp (template+strlen(template)-4, EXTSEP_S "gpg") )
1169 bakfname = xmalloc (strlen (template) + 1);
1170 strcpy (bakfname, template);
1171 strcpy (bakfname+strlen(template)-4, EXTSEP_S "bak");
1173 tmpfname = xmalloc (strlen( template ) + 1 );
1174 strcpy (tmpfname,template);
1175 strcpy (tmpfname+strlen(template)-4, EXTSEP_S "tmp");
1177 else
1178 { /* file does not end with gpg; hmmm */
1179 bakfname = xmalloc (strlen( template ) + 5);
1180 strcpy (stpcpy(bakfname, template), EXTSEP_S "bak");
1182 tmpfname = xmalloc (strlen( template ) + 5);
1183 strcpy (stpcpy(tmpfname, template), EXTSEP_S "tmp");
1185 # else /* Posix file names */
1186 bakfname = xmalloc (strlen( template ) + 2);
1187 strcpy (stpcpy (bakfname,template),"~");
1189 tmpfname = xmalloc (strlen( template ) + 5);
1190 strcpy (stpcpy(tmpfname,template), EXTSEP_S "tmp");
1191 # endif /* Posix filename */
1193 /* Create the temp file with limited access */
1194 oldmask=umask(077);
1195 if (is_secured_filename (tmpfname))
1197 *r_fp = NULL;
1198 errno = EPERM;
1200 else
1201 *r_fp = iobuf_create (tmpfname);
1202 umask(oldmask);
1203 if (!*r_fp)
1205 int rc = gpg_error_from_syserror ();
1206 log_error(_("can't create `%s': %s\n"), tmpfname, strerror(errno) );
1207 xfree (tmpfname);
1208 xfree (bakfname);
1209 return rc;
1212 *r_bakfname = bakfname;
1213 *r_tmpfname = tmpfname;
1214 return 0;
1218 static int
1219 rename_tmp_file (const char *bakfname, const char *tmpfname,
1220 const char *fname, int secret )
1222 int rc = 0;
1224 /* It's a secret keyring, so let's force a fsync just to be safe on
1225 filesystems that may not sync data and metadata together
1226 (e.g. ext4). */
1227 if (secret && iobuf_ioctl (NULL, 4, 0, (char*)tmpfname))
1229 rc = gpg_error_from_syserror ();
1230 goto fail;
1233 /* Invalidate close caches. */
1234 if (iobuf_ioctl (NULL, 2, 0, (char*)tmpfname ))
1236 rc = gpg_error_from_syserror ();
1237 goto fail;
1239 iobuf_ioctl (NULL, 2, 0, (char*)bakfname );
1240 iobuf_ioctl (NULL, 2, 0, (char*)fname );
1242 /* first make a backup file except for secret keyrings */
1243 if (!secret)
1245 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
1246 remove (bakfname);
1247 #endif
1248 if (rename (fname, bakfname) )
1250 rc = gpg_error_from_syserror ();
1251 log_error ("renaming `%s' to `%s' failed: %s\n",
1252 fname, bakfname, strerror(errno) );
1253 return rc;
1257 /* then rename the file */
1258 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
1259 remove( fname );
1260 #endif
1261 if (secret)
1262 unregister_secured_file (fname);
1263 if (rename (tmpfname, fname) )
1265 rc = gpg_error_from_syserror ();
1266 log_error (_("renaming `%s' to `%s' failed: %s\n"),
1267 tmpfname, fname, strerror(errno) );
1268 register_secured_file (fname);
1269 goto fail;
1272 /* Now make sure the file has the same permissions as the original */
1274 #ifndef HAVE_DOSISH_SYSTEM
1276 struct stat statbuf;
1278 statbuf.st_mode=S_IRUSR | S_IWUSR;
1280 if (((secret && !opt.preserve_permissions)
1281 || !stat (bakfname,&statbuf))
1282 && !chmod (fname,statbuf.st_mode))
1284 else
1285 log_error ("WARNING: unable to restore permissions to `%s': %s",
1286 fname, strerror(errno));
1288 #endif
1290 return 0;
1292 fail:
1293 if (secret)
1295 log_info(_("WARNING: 2 files with confidential information exists.\n"));
1296 log_info(_("%s is the unchanged one\n"), fname );
1297 log_info(_("%s is the new one\n"), tmpfname );
1298 log_info(_("Please fix this possible security flaw\n"));
1300 return rc;
1304 static int
1305 write_keyblock (IOBUF fp, KBNODE keyblock)
1307 KBNODE kbctx = NULL, node;
1308 int rc;
1310 while ( (node = walk_kbnode (keyblock, &kbctx, 0)) )
1312 if (node->pkt->pkttype == PKT_RING_TRUST)
1313 continue; /* we write it later on our own */
1315 if ( (rc = build_packet (fp, node->pkt) ))
1317 log_error ("build_packet(%d) failed: %s\n",
1318 node->pkt->pkttype, g10_errstr(rc) );
1319 return rc;
1321 if (node->pkt->pkttype == PKT_SIGNATURE)
1322 { /* always write a signature cache packet */
1323 PKT_signature *sig = node->pkt->pkt.signature;
1324 unsigned int cacheval = 0;
1326 if (sig->flags.checked)
1328 cacheval |= 1;
1329 if (sig->flags.valid)
1330 cacheval |= 2;
1332 iobuf_put (fp, 0xb0); /* old style packet 12, 1 byte len*/
1333 iobuf_put (fp, 2); /* 2 bytes */
1334 iobuf_put (fp, 0); /* unused */
1335 if (iobuf_put (fp, cacheval))
1337 rc = gpg_error_from_syserror ();
1338 log_error ("writing sigcache packet failed\n");
1339 return rc;
1343 return 0;
1347 * Walk over all public keyrings, check the signatures and replace the
1348 * keyring with a new one where the signature cache is then updated.
1349 * This is only done for the public keyrings.
1352 keyring_rebuild_cache (void *token,int noisy)
1354 KEYRING_HANDLE hd;
1355 KEYDB_SEARCH_DESC desc;
1356 KBNODE keyblock = NULL, node;
1357 const char *lastresname = NULL, *resname;
1358 IOBUF tmpfp = NULL;
1359 char *tmpfilename = NULL;
1360 char *bakfilename = NULL;
1361 int rc;
1362 ulong count = 0, sigcount = 0;
1364 hd = keyring_new (token, 0);
1365 memset (&desc, 0, sizeof desc);
1366 desc.mode = KEYDB_SEARCH_MODE_FIRST;
1368 rc=keyring_lock (hd, 1);
1369 if(rc)
1370 goto leave;
1372 while ( !(rc = keyring_search (hd, &desc, 1, NULL)) )
1374 desc.mode = KEYDB_SEARCH_MODE_NEXT;
1375 resname = keyring_get_resource_name (hd);
1376 if (lastresname != resname )
1377 { /* we have switched to a new keyring - commit changes */
1378 if (tmpfp)
1380 if (iobuf_close (tmpfp))
1382 rc = gpg_error_from_syserror ();
1383 log_error ("error closing `%s': %s\n",
1384 tmpfilename, strerror (errno));
1385 goto leave;
1387 /* because we have switched resources, we can be sure that
1388 * the original file is closed */
1389 tmpfp = NULL;
1391 rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1392 lastresname, 0) : 0;
1393 xfree (tmpfilename); tmpfilename = NULL;
1394 xfree (bakfilename); bakfilename = NULL;
1395 if (rc)
1396 goto leave;
1397 lastresname = resname;
1398 if (noisy && !opt.quiet)
1399 log_info (_("caching keyring `%s'\n"), resname);
1400 rc = create_tmp_file (resname, &bakfilename, &tmpfilename, &tmpfp);
1401 if (rc)
1402 goto leave;
1405 release_kbnode (keyblock);
1406 rc = keyring_get_keyblock (hd, &keyblock);
1407 if (rc)
1409 log_error ("keyring_get_keyblock failed: %s\n", g10_errstr(rc));
1410 goto leave;
1412 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
1414 /* check all signature to set the signature's cache flags */
1415 for (node=keyblock; node; node=node->next)
1417 /* Note that this doesn't cache the result of a revocation
1418 issued by a designated revoker. This is because the pk
1419 in question does not carry the revkeys as we haven't
1420 merged the key and selfsigs. It is questionable whether
1421 this matters very much since there are very very few
1422 designated revoker revocation packets out there. */
1424 if (node->pkt->pkttype == PKT_SIGNATURE)
1426 PKT_signature *sig=node->pkt->pkt.signature;
1428 if(!opt.no_sig_cache && sig->flags.checked && sig->flags.valid
1429 && (openpgp_md_test_algo(sig->digest_algo)
1430 || openpgp_pk_test_algo(sig->pubkey_algo)))
1431 sig->flags.checked=sig->flags.valid=0;
1432 else
1433 check_key_signature (keyblock, node, NULL);
1435 sigcount++;
1439 /* write the keyblock to the temporary file */
1440 rc = write_keyblock (tmpfp, keyblock);
1441 if (rc)
1442 goto leave;
1444 if ( !(++count % 50) && noisy && !opt.quiet)
1445 log_info(_("%lu keys cached so far (%lu signatures)\n"),
1446 count, sigcount );
1448 } /* end main loop */
1449 if (rc == -1)
1450 rc = 0;
1451 if (rc)
1453 log_error ("keyring_search failed: %s\n", g10_errstr(rc));
1454 goto leave;
1456 if(noisy || opt.verbose)
1457 log_info(_("%lu keys cached (%lu signatures)\n"), count, sigcount );
1458 if (tmpfp)
1460 if (iobuf_close (tmpfp))
1462 rc = gpg_error_from_syserror ();
1463 log_error ("error closing `%s': %s\n",
1464 tmpfilename, strerror (errno));
1465 goto leave;
1467 /* because we have switched resources, we can be sure that
1468 * the original file is closed */
1469 tmpfp = NULL;
1471 rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1472 lastresname, 0) : 0;
1473 xfree (tmpfilename); tmpfilename = NULL;
1474 xfree (bakfilename); bakfilename = NULL;
1476 leave:
1477 if (tmpfp)
1478 iobuf_cancel (tmpfp);
1479 xfree (tmpfilename);
1480 xfree (bakfilename);
1481 release_kbnode (keyblock);
1482 keyring_lock (hd, 0);
1483 keyring_release (hd);
1484 return rc;
1488 /****************
1489 * Perform insert/delete/update operation.
1490 * mode 1 = insert
1491 * 2 = delete
1492 * 3 = update
1494 static int
1495 do_copy (int mode, const char *fname, KBNODE root, int secret,
1496 off_t start_offset, unsigned int n_packets )
1498 IOBUF fp, newfp;
1499 int rc=0;
1500 char *bakfname = NULL;
1501 char *tmpfname = NULL;
1503 /* Open the source file. Because we do a rename, we have to check the
1504 permissions of the file */
1505 if (access (fname, W_OK))
1506 return gpg_error_from_syserror ();
1508 fp = iobuf_open (fname);
1509 if (mode == 1 && !fp && errno == ENOENT) {
1510 /* insert mode but file does not exist: create a new file */
1511 KBNODE kbctx, node;
1512 mode_t oldmask;
1514 oldmask=umask(077);
1515 if (!secret && is_secured_filename (fname)) {
1516 newfp = NULL;
1517 errno = EPERM;
1519 else
1520 newfp = iobuf_create (fname);
1521 umask(oldmask);
1522 if( !newfp )
1524 rc = gpg_error_from_syserror ();
1525 log_error (_("can't create `%s': %s\n"), fname, strerror(errno));
1526 return rc;
1528 if( !opt.quiet )
1529 log_info(_("%s: keyring created\n"), fname );
1531 kbctx=NULL;
1532 while ( (node = walk_kbnode( root, &kbctx, 0 )) ) {
1533 if( (rc = build_packet( newfp, node->pkt )) ) {
1534 log_error("build_packet(%d) failed: %s\n",
1535 node->pkt->pkttype, g10_errstr(rc) );
1536 iobuf_cancel(newfp);
1537 return rc;
1540 if( iobuf_close(newfp) ) {
1541 rc = gpg_error_from_syserror ();
1542 log_error ("%s: close failed: %s\n", fname, strerror(errno));
1543 return rc;
1545 return 0; /* ready */
1548 if( !fp )
1550 rc = gpg_error_from_syserror ();
1551 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
1552 goto leave;
1555 /* Create the new file. */
1556 rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp);
1557 if (rc) {
1558 iobuf_close(fp);
1559 goto leave;
1561 if (secret)
1562 register_secured_file (tmpfname);
1564 if( mode == 1 ) { /* insert */
1565 /* copy everything to the new file */
1566 rc = copy_all_packets (fp, newfp);
1567 if( rc != -1 ) {
1568 log_error("%s: copy to `%s' failed: %s\n",
1569 fname, tmpfname, g10_errstr(rc) );
1570 iobuf_close(fp);
1571 if (secret)
1572 unregister_secured_file (tmpfname);
1573 iobuf_cancel(newfp);
1574 goto leave;
1576 rc = 0;
1579 if( mode == 2 || mode == 3 ) { /* delete or update */
1580 /* copy first part to the new file */
1581 rc = copy_some_packets( fp, newfp, start_offset );
1582 if( rc ) { /* should never get EOF here */
1583 log_error ("%s: copy to `%s' failed: %s\n",
1584 fname, tmpfname, g10_errstr(rc) );
1585 iobuf_close(fp);
1586 if (secret)
1587 unregister_secured_file (tmpfname);
1588 iobuf_cancel(newfp);
1589 goto leave;
1591 /* skip this keyblock */
1592 assert( n_packets );
1593 rc = skip_some_packets( fp, n_packets );
1594 if( rc ) {
1595 log_error("%s: skipping %u packets failed: %s\n",
1596 fname, n_packets, g10_errstr(rc));
1597 iobuf_close(fp);
1598 if (secret)
1599 unregister_secured_file (tmpfname);
1600 iobuf_cancel(newfp);
1601 goto leave;
1605 if( mode == 1 || mode == 3 ) { /* insert or update */
1606 rc = write_keyblock (newfp, root);
1607 if (rc) {
1608 iobuf_close(fp);
1609 if (secret)
1610 unregister_secured_file (tmpfname);
1611 iobuf_cancel(newfp);
1612 goto leave;
1616 if( mode == 2 || mode == 3 ) { /* delete or update */
1617 /* copy the rest */
1618 rc = copy_all_packets( fp, newfp );
1619 if( rc != -1 ) {
1620 log_error("%s: copy to `%s' failed: %s\n",
1621 fname, tmpfname, g10_errstr(rc) );
1622 iobuf_close(fp);
1623 if (secret)
1624 unregister_secured_file (tmpfname);
1625 iobuf_cancel(newfp);
1626 goto leave;
1628 rc = 0;
1631 /* close both files */
1632 if( iobuf_close(fp) ) {
1633 rc = gpg_error_from_syserror ();
1634 log_error("%s: close failed: %s\n", fname, strerror(errno) );
1635 goto leave;
1637 if( iobuf_close(newfp) ) {
1638 rc = gpg_error_from_syserror ();
1639 log_error("%s: close failed: %s\n", tmpfname, strerror(errno) );
1640 goto leave;
1643 rc = rename_tmp_file (bakfname, tmpfname, fname, secret);
1645 leave:
1646 xfree(bakfname);
1647 xfree(tmpfname);
1648 return rc;