Fix bug#1034.
[gnupg.git] / g10 / keyring.c
blob2c894312da94110eb6a929b1fe03dddeb8b51805
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
55 struct keyring_name *next;
56 int secret;
57 int readonly;
58 DOTLOCK lockhd;
59 int is_locked;
60 int did_full_scan;
61 char fname[1];
63 typedef struct keyring_name const * CONST_KR_NAME;
65 static KR_NAME kr_names;
66 static int active_handles;
68 static OffsetHashTable kr_offtbl;
69 static int kr_offtbl_ready;
72 struct keyring_handle {
73 CONST_KR_NAME resource;
74 int secret; /* this is for a secret keyring */
75 struct {
76 CONST_KR_NAME kr;
77 IOBUF iobuf;
78 int eof;
79 int error;
80 } current;
81 struct {
82 CONST_KR_NAME kr;
83 off_t offset;
84 size_t pk_no;
85 size_t uid_no;
86 unsigned int n_packets; /*used for delete and update*/
87 } found;
88 struct {
89 char *name;
90 char *pattern;
91 } word_match;
96 static int do_copy (int mode, const char *fname, KBNODE root, int secret,
97 off_t start_offset, unsigned int n_packets );
101 static struct off_item *
102 new_offset_item (void)
104 struct off_item *k;
106 k = xmalloc_clear (sizeof *k);
107 return k;
110 #if 0
111 static void
112 release_offset_items (struct off_item *k)
114 struct off_item *k2;
116 for (; k; k = k2)
118 k2 = k->next;
119 xfree (k);
122 #endif
124 static OffsetHashTable
125 new_offset_hash_table (void)
127 struct off_item **tbl;
129 tbl = xmalloc_clear (2048 * sizeof *tbl);
130 return tbl;
133 #if 0
134 static void
135 release_offset_hash_table (OffsetHashTable tbl)
137 int i;
139 if (!tbl)
140 return;
141 for (i=0; i < 2048; i++)
142 release_offset_items (tbl[i]);
143 xfree (tbl);
145 #endif
147 static struct off_item *
148 lookup_offset_hash_table (OffsetHashTable tbl, u32 *kid)
150 struct off_item *k;
152 for (k = tbl[(kid[1] & 0x07ff)]; k; k = k->next)
153 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
154 return k;
155 return NULL;
158 static void
159 update_offset_hash_table (OffsetHashTable tbl, u32 *kid, off_t off)
161 struct off_item *k;
163 (void)off;
165 for (k = tbl[(kid[1] & 0x07ff)]; k; k = k->next)
167 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
169 /*k->off = off;*/
170 return;
174 k = new_offset_item ();
175 k->kid[0] = kid[0];
176 k->kid[1] = kid[1];
177 /*k->off = off;*/
178 k->next = tbl[(kid[1] & 0x07ff)];
179 tbl[(kid[1] & 0x07ff)] = k;
182 static void
183 update_offset_hash_table_from_kb (OffsetHashTable tbl, KBNODE node, off_t off)
185 for (; node; node = node->next)
187 if (node->pkt->pkttype == PKT_PUBLIC_KEY
188 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
190 u32 aki[2];
191 keyid_from_pk (node->pkt->pkt.public_key, aki);
192 update_offset_hash_table (tbl, aki, off);
198 * Register a filename for plain keyring files. ptr is set to a
199 * pointer to be used to create a handles etc, or the already-issued
200 * pointer if it has already been registered. The function returns 1
201 * if a new keyring was registered.
204 keyring_register_filename (const char *fname, int secret, int readonly,
205 void **ptr)
207 KR_NAME kr;
209 if (active_handles)
210 BUG (); /* We don't allow that */
212 for (kr=kr_names; kr; kr = kr->next)
214 if (same_file_p (kr->fname, fname))
216 /* Already registered. */
217 if (readonly)
218 kr->readonly = 1;
219 *ptr=kr;
220 return 0;
224 if (secret)
225 register_secured_file (fname);
227 kr = xmalloc (sizeof *kr + strlen (fname));
228 strcpy (kr->fname, fname);
229 kr->secret = !!secret;
230 kr->readonly = readonly;
231 kr->lockhd = NULL;
232 kr->is_locked = 0;
233 kr->did_full_scan = 0;
234 /* keep a list of all issued pointers */
235 kr->next = kr_names;
236 kr_names = kr;
238 /* create the offset table the first time a function here is used */
239 if (!kr_offtbl)
240 kr_offtbl = new_offset_hash_table ();
242 *ptr=kr;
244 return 1;
248 keyring_is_writable (void *token)
250 KR_NAME r = token;
252 return r? (r->readonly || !access (r->fname, W_OK)) : 0;
257 /* Create a new handle for the resource associated with TOKEN. SECRET
258 is just just as a cross-check.
260 The returned handle must be released using keyring_release (). */
261 KEYRING_HANDLE
262 keyring_new (void *token, int secret)
264 KEYRING_HANDLE hd;
265 KR_NAME resource = token;
267 assert (resource && !resource->secret == !secret);
269 hd = xmalloc_clear (sizeof *hd);
270 hd->resource = resource;
271 hd->secret = !!secret;
272 active_handles++;
273 return hd;
276 void
277 keyring_release (KEYRING_HANDLE hd)
279 if (!hd)
280 return;
281 assert (active_handles > 0);
282 active_handles--;
283 xfree (hd->word_match.name);
284 xfree (hd->word_match.pattern);
285 iobuf_close (hd->current.iobuf);
286 xfree (hd);
290 const char *
291 keyring_get_resource_name (KEYRING_HANDLE hd)
293 if (!hd || !hd->resource)
294 return NULL;
295 return hd->resource->fname;
300 * Lock the keyring with the given handle, or unlock if YES is false.
301 * We ignore the handle and lock all registered files.
303 int
304 keyring_lock (KEYRING_HANDLE hd, int yes)
306 KR_NAME kr;
307 int rc = 0;
309 (void)hd;
311 if (yes) {
312 /* first make sure the lock handles are created */
313 for (kr=kr_names; kr; kr = kr->next) {
314 if (!keyring_is_writable(kr))
315 continue;
316 if (!kr->lockhd) {
317 kr->lockhd = create_dotlock( kr->fname );
318 if (!kr->lockhd) {
319 log_info ("can't allocate lock for `%s'\n", kr->fname );
320 rc = G10ERR_GENERAL;
324 if (rc)
325 return rc;
327 /* and now set the locks */
328 for (kr=kr_names; kr; kr = kr->next) {
329 if (!keyring_is_writable(kr))
330 continue;
331 if (kr->is_locked)
333 else if (make_dotlock (kr->lockhd, -1) ) {
334 log_info ("can't lock `%s'\n", kr->fname );
335 rc = G10ERR_GENERAL;
337 else
338 kr->is_locked = 1;
342 if (rc || !yes) {
343 for (kr=kr_names; kr; kr = kr->next) {
344 if (!keyring_is_writable(kr))
345 continue;
346 if (!kr->is_locked)
348 else if (release_dotlock (kr->lockhd))
349 log_info ("can't unlock `%s'\n", kr->fname );
350 else
351 kr->is_locked = 0;
355 return rc;
361 * Return the last found keyring. Caller must free it.
362 * The returned keyblock has the kbode flag bit 0 set for the node with
363 * the public key used to locate the keyblock or flag bit 1 set for
364 * the user ID node.
367 keyring_get_keyblock (KEYRING_HANDLE hd, KBNODE *ret_kb)
369 PACKET *pkt;
370 int rc;
371 KBNODE keyblock = NULL, node, lastnode;
372 IOBUF a;
373 int in_cert = 0;
374 int pk_no = 0;
375 int uid_no = 0;
376 int save_mode;
378 if (ret_kb)
379 *ret_kb = NULL;
381 if (!hd->found.kr)
382 return -1; /* no successful search */
384 a = iobuf_open (hd->found.kr->fname);
385 if (!a)
387 log_error(_("can't open `%s'\n"), hd->found.kr->fname);
388 return G10ERR_KEYRING_OPEN;
391 if (iobuf_seek (a, hd->found.offset) ) {
392 log_error ("can't seek `%s'\n", hd->found.kr->fname);
393 iobuf_close(a);
394 return G10ERR_KEYRING_OPEN;
397 pkt = xmalloc (sizeof *pkt);
398 init_packet (pkt);
399 hd->found.n_packets = 0;;
400 lastnode = NULL;
401 save_mode = set_packet_list_mode(0);
402 while ((rc=parse_packet (a, pkt)) != -1) {
403 hd->found.n_packets++;
404 if (rc == G10ERR_UNKNOWN_PACKET) {
405 free_packet (pkt);
406 init_packet (pkt);
407 continue;
409 if (rc) {
410 log_error ("keyring_get_keyblock: read error: %s\n",
411 g10_errstr(rc) );
412 rc = G10ERR_INV_KEYRING;
413 break;
415 if (pkt->pkttype == PKT_COMPRESSED) {
416 log_error ("skipped compressed packet in keyring\n");
417 free_packet(pkt);
418 init_packet(pkt);
419 continue;
422 if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
423 || pkt->pkttype == PKT_SECRET_KEY)) {
424 hd->found.n_packets--; /* fix counter */
425 break; /* ready */
428 in_cert = 1;
429 if (pkt->pkttype == PKT_RING_TRUST)
431 /*(this code is duplicated after the loop)*/
432 if ( lastnode
433 && lastnode->pkt->pkttype == PKT_SIGNATURE
434 && (pkt->pkt.ring_trust->sigcache & 1) ) {
435 /* This is a ring trust packet with a checked signature
436 * status cache following directly a signature paket.
437 * Set the cache status into that signature packet. */
438 PKT_signature *sig = lastnode->pkt->pkt.signature;
440 sig->flags.checked = 1;
441 sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
443 /* Reset LASTNODE, so that we set the cache status only from
444 * the ring trust packet immediately following a signature. */
445 lastnode = NULL;
446 free_packet(pkt);
447 init_packet(pkt);
448 continue;
452 node = lastnode = new_kbnode (pkt);
453 if (!keyblock)
454 keyblock = node;
455 else
456 add_kbnode (keyblock, node);
457 switch (pkt->pkttype)
459 case PKT_PUBLIC_KEY:
460 case PKT_PUBLIC_SUBKEY:
461 case PKT_SECRET_KEY:
462 case PKT_SECRET_SUBKEY:
463 if (++pk_no == hd->found.pk_no)
464 node->flag |= 1;
465 break;
467 case PKT_USER_ID:
468 if (++uid_no == hd->found.uid_no)
469 node->flag |= 2;
470 break;
472 default:
473 break;
476 pkt = xmalloc (sizeof *pkt);
477 init_packet(pkt);
479 set_packet_list_mode(save_mode);
481 if (rc == -1 && keyblock)
482 rc = 0; /* got the entire keyblock */
484 if (rc || !ret_kb)
485 release_kbnode (keyblock);
486 else {
487 /*(duplicated form the loop body)*/
488 if ( pkt && pkt->pkttype == PKT_RING_TRUST
489 && lastnode
490 && lastnode->pkt->pkttype == PKT_SIGNATURE
491 && (pkt->pkt.ring_trust->sigcache & 1) ) {
492 PKT_signature *sig = lastnode->pkt->pkt.signature;
493 sig->flags.checked = 1;
494 sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
496 *ret_kb = keyblock;
498 free_packet (pkt);
499 xfree (pkt);
500 iobuf_close(a);
502 /* Make sure that future search operations fail immediately when
503 * we know that we are working on a invalid keyring
505 if (rc == G10ERR_INV_KEYRING)
506 hd->current.error = rc;
508 return rc;
512 keyring_update_keyblock (KEYRING_HANDLE hd, KBNODE kb)
514 int rc;
516 if (!hd->found.kr)
517 return -1; /* no successful prior search */
519 if (hd->found.kr->readonly)
520 return gpg_error (GPG_ERR_EACCES);
522 if (!hd->found.n_packets) {
523 /* need to know the number of packets - do a dummy get_keyblock*/
524 rc = keyring_get_keyblock (hd, NULL);
525 if (rc) {
526 log_error ("re-reading keyblock failed: %s\n", g10_errstr (rc));
527 return rc;
529 if (!hd->found.n_packets)
530 BUG ();
533 /* The open iobuf isn't needed anymore and in fact is a problem when
534 it comes to renaming the keyring files on some operating systems,
535 so close it here */
536 iobuf_close(hd->current.iobuf);
537 hd->current.iobuf = NULL;
539 /* do the update */
540 rc = do_copy (3, hd->found.kr->fname, kb, hd->secret,
541 hd->found.offset, hd->found.n_packets );
542 if (!rc) {
543 if (!hd->secret && kr_offtbl)
545 update_offset_hash_table_from_kb (kr_offtbl, kb, 0);
547 /* better reset the found info */
548 hd->found.kr = NULL;
549 hd->found.offset = 0;
551 return rc;
555 keyring_insert_keyblock (KEYRING_HANDLE hd, KBNODE kb)
557 int rc;
558 const char *fname;
560 if (!hd)
561 fname = NULL;
562 else if (hd->found.kr)
564 fname = hd->found.kr->fname;
565 if (hd->found.kr->readonly)
566 return gpg_error (GPG_ERR_EACCES);
568 else if (hd->current.kr)
570 fname = hd->current.kr->fname;
571 if (hd->current.kr->readonly)
572 return gpg_error (GPG_ERR_EACCES);
574 else
575 fname = hd->resource? hd->resource->fname:NULL;
577 if (!fname)
578 return G10ERR_GENERAL;
580 /* Close this one otherwise we will lose the position for
581 * a next search. Fixme: it would be better to adjust the position
582 * after the write opertions.
584 iobuf_close (hd->current.iobuf);
585 hd->current.iobuf = NULL;
587 /* do the insert */
588 rc = do_copy (1, fname, kb, hd->secret, 0, 0 );
589 if (!rc && !hd->secret && kr_offtbl)
591 update_offset_hash_table_from_kb (kr_offtbl, kb, 0);
594 return rc;
599 keyring_delete_keyblock (KEYRING_HANDLE hd)
601 int rc;
603 if (!hd->found.kr)
604 return -1; /* no successful prior search */
606 if (hd->found.kr->readonly)
607 return gpg_error (GPG_ERR_EACCES);
609 if (!hd->found.n_packets) {
610 /* need to know the number of packets - do a dummy get_keyblock*/
611 rc = keyring_get_keyblock (hd, NULL);
612 if (rc) {
613 log_error ("re-reading keyblock failed: %s\n", g10_errstr (rc));
614 return rc;
616 if (!hd->found.n_packets)
617 BUG ();
620 /* close this one otherwise we will lose the position for
621 * a next search. Fixme: it would be better to adjust the position
622 * after the write opertions.
624 iobuf_close (hd->current.iobuf);
625 hd->current.iobuf = NULL;
627 /* do the delete */
628 rc = do_copy (2, hd->found.kr->fname, NULL, hd->secret,
629 hd->found.offset, hd->found.n_packets );
630 if (!rc) {
631 /* better reset the found info */
632 hd->found.kr = NULL;
633 hd->found.offset = 0;
634 /* Delete is a rare operations, so we don't remove the keys
635 * from the offset table */
637 return rc;
643 * Start the next search on this handle right at the beginning
645 int
646 keyring_search_reset (KEYRING_HANDLE hd)
648 assert (hd);
650 hd->current.kr = NULL;
651 iobuf_close (hd->current.iobuf);
652 hd->current.iobuf = NULL;
653 hd->current.eof = 0;
654 hd->current.error = 0;
656 hd->found.kr = NULL;
657 hd->found.offset = 0;
658 return 0;
662 static int
663 prepare_search (KEYRING_HANDLE hd)
665 if (hd->current.error)
666 return hd->current.error; /* still in error state */
668 if (hd->current.kr && !hd->current.eof) {
669 if ( !hd->current.iobuf )
670 return G10ERR_GENERAL; /* position invalid after a modify */
671 return 0; /* okay */
674 if (!hd->current.kr && hd->current.eof)
675 return -1; /* still EOF */
677 if (!hd->current.kr) { /* start search with first keyring */
678 hd->current.kr = hd->resource;
679 if (!hd->current.kr) {
680 hd->current.eof = 1;
681 return -1; /* keyring not available */
683 assert (!hd->current.iobuf);
685 else { /* EOF */
686 iobuf_close (hd->current.iobuf);
687 hd->current.iobuf = NULL;
688 hd->current.kr = NULL;
689 hd->current.eof = 1;
690 return -1;
693 hd->current.eof = 0;
694 hd->current.iobuf = iobuf_open (hd->current.kr->fname);
695 if (!hd->current.iobuf)
697 hd->current.error = gpg_error_from_syserror ();
698 log_error(_("can't open `%s'\n"), hd->current.kr->fname );
699 return hd->current.error;
702 return 0;
706 /* A map of the all characters valid used for word_match()
707 * Valid characters are in in this table converted to uppercase.
708 * because the upper 128 bytes have special meaning, we assume
709 * that they are all valid.
710 * Note: We must use numerical values here in case that this program
711 * will be converted to those little blue HAL9000s with their strange
712 * EBCDIC character set (user ids are UTF-8).
713 * wk 2000-04-13: Hmmm, does this really make sense, given the fact that
714 * we can run gpg now on a S/390 running GNU/Linux, where the code
715 * translation is done by the device drivers?
717 static const byte word_match_chars[256] = {
718 /* 00 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
719 /* 08 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
720 /* 10 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
721 /* 18 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
722 /* 20 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
723 /* 28 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
724 /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
725 /* 38 */ 0x38, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
726 /* 40 */ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
727 /* 48 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
728 /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
729 /* 58 */ 0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
730 /* 60 */ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
731 /* 68 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
732 /* 70 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
733 /* 78 */ 0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
734 /* 80 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
735 /* 88 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
736 /* 90 */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
737 /* 98 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
738 /* a0 */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
739 /* a8 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
740 /* b0 */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
741 /* b8 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
742 /* c0 */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
743 /* c8 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
744 /* d0 */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
745 /* d8 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
746 /* e0 */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
747 /* e8 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
748 /* f0 */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
749 /* f8 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
752 /****************
753 * Do a word match (original user id starts with a '+').
754 * The pattern is already tokenized to a more suitable format:
755 * There are only the real words in it delimited by one space
756 * and all converted to uppercase.
758 * Returns: 0 if all words match.
760 * Note: This algorithm is a straightforward one and not very
761 * fast. It works for UTF-8 strings. The uidlen should
762 * be removed but due to the fact that old versions of
763 * pgp don't use UTF-8 we still use the length; this should
764 * be fixed in parse-packet (and replace \0 by some special
765 * UTF-8 encoding)
767 static int
768 word_match( const byte *uid, size_t uidlen, const byte *pattern )
770 size_t wlen, n;
771 const byte *p;
772 const byte *s;
774 for( s=pattern; *s; ) {
775 do {
776 /* skip leading delimiters */
777 while( uidlen && !word_match_chars[*uid] )
778 uid++, uidlen--;
779 /* get length of the word */
780 n = uidlen; p = uid;
781 while( n && word_match_chars[*p] )
782 p++, n--;
783 wlen = p - uid;
784 /* and compare against the current word from pattern */
785 for(n=0, p=uid; n < wlen && s[n] != ' ' && s[n] ; n++, p++ ) {
786 if( word_match_chars[*p] != s[n] )
787 break;
789 if( n == wlen && (s[n] == ' ' || !s[n]) )
790 break; /* found */
791 uid += wlen;
792 uidlen -= wlen;
793 } while( uidlen );
794 if( !uidlen )
795 return -1; /* not found */
797 /* advance to next word in pattern */
798 for(; *s != ' ' && *s ; s++ )
800 if( *s )
801 s++ ;
803 return 0; /* found */
806 /****************
807 * prepare word word_match; that is parse the name and
808 * build the pattern.
809 * caller has to free the returned pattern
811 static char*
812 prepare_word_match (const byte *name)
814 byte *pattern, *p;
815 int c;
817 /* the original length is always enough for the pattern */
818 p = pattern = xmalloc(strlen(name)+1);
819 do {
820 /* skip leading delimiters */
821 while( *name && !word_match_chars[*name] )
822 name++;
823 /* copy as long as we don't have a delimiter and convert
824 * to uppercase.
825 * fixme: how can we handle utf8 uppercasing */
826 for( ; *name && (c=word_match_chars[*name]); name++ )
827 *p++ = c;
828 *p++ = ' '; /* append pattern delimiter */
829 } while( *name );
830 p[-1] = 0; /* replace last pattern delimiter by EOS */
832 return pattern;
838 static int
839 compare_name (int mode, const char *name, const char *uid, size_t uidlen)
841 int i;
842 const char *s, *se;
844 if (mode == KEYDB_SEARCH_MODE_EXACT) {
845 for (i=0; name[i] && uidlen; i++, uidlen--)
846 if (uid[i] != name[i])
847 break;
848 if (!uidlen && !name[i])
849 return 0; /* found */
851 else if (mode == KEYDB_SEARCH_MODE_SUBSTR) {
852 if (ascii_memistr( uid, uidlen, name ))
853 return 0;
855 else if ( mode == KEYDB_SEARCH_MODE_MAIL
856 || mode == KEYDB_SEARCH_MODE_MAILSUB
857 || mode == KEYDB_SEARCH_MODE_MAILEND) {
858 for (i=0, s= uid; i < uidlen && *s != '<'; s++, i++)
860 if (i < uidlen) {
861 /* skip opening delim and one char and look for the closing one*/
862 s++; i++;
863 for (se=s+1, i++; i < uidlen && *se != '>'; se++, i++)
865 if (i < uidlen) {
866 i = se - s;
867 if (mode == KEYDB_SEARCH_MODE_MAIL) {
868 if( strlen(name)-2 == i
869 && !ascii_memcasecmp( s, name+1, i) )
870 return 0;
872 else if (mode == KEYDB_SEARCH_MODE_MAILSUB) {
873 if( ascii_memistr( s, i, name ) )
874 return 0;
876 else { /* email from end */
877 /* nyi */
882 else if (mode == KEYDB_SEARCH_MODE_WORDS)
883 return word_match (uid, uidlen, name);
884 else
885 BUG();
887 return -1; /* not found */
892 * Search through the keyring(s), starting at the current position,
893 * for a keyblock which contains one of the keys described in the DESC array.
895 int
896 keyring_search (KEYRING_HANDLE hd, KEYDB_SEARCH_DESC *desc,
897 size_t ndesc, size_t *descindex)
899 int rc;
900 PACKET pkt;
901 int save_mode;
902 off_t offset, main_offset;
903 size_t n;
904 int need_uid, need_words, need_keyid, need_fpr, any_skip;
905 int pk_no, uid_no;
906 int initial_skip;
907 int use_offtbl;
908 PKT_user_id *uid = NULL;
909 PKT_public_key *pk = NULL;
910 PKT_secret_key *sk = NULL;
911 u32 aki[2];
913 /* figure out what information we need */
914 need_uid = need_words = need_keyid = need_fpr = any_skip = 0;
915 for (n=0; n < ndesc; n++)
917 switch (desc[n].mode)
919 case KEYDB_SEARCH_MODE_EXACT:
920 case KEYDB_SEARCH_MODE_SUBSTR:
921 case KEYDB_SEARCH_MODE_MAIL:
922 case KEYDB_SEARCH_MODE_MAILSUB:
923 case KEYDB_SEARCH_MODE_MAILEND:
924 need_uid = 1;
925 break;
926 case KEYDB_SEARCH_MODE_WORDS:
927 need_uid = 1;
928 need_words = 1;
929 break;
930 case KEYDB_SEARCH_MODE_SHORT_KID:
931 case KEYDB_SEARCH_MODE_LONG_KID:
932 need_keyid = 1;
933 break;
934 case KEYDB_SEARCH_MODE_FPR16:
935 case KEYDB_SEARCH_MODE_FPR20:
936 case KEYDB_SEARCH_MODE_FPR:
937 need_fpr = 1;
938 break;
939 case KEYDB_SEARCH_MODE_FIRST:
940 /* always restart the search in this mode */
941 keyring_search_reset (hd);
942 break;
943 default: break;
945 if (desc[n].skipfnc)
947 any_skip = 1;
948 need_keyid = 1;
952 rc = prepare_search (hd);
953 if (rc)
954 return rc;
956 use_offtbl = !hd->secret && kr_offtbl;
957 if (!use_offtbl)
959 else if (!kr_offtbl_ready)
960 need_keyid = 1;
961 else if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID)
963 struct off_item *oi;
965 oi = lookup_offset_hash_table (kr_offtbl, desc[0].u.kid);
966 if (!oi)
967 { /* We know that we don't have this key */
968 hd->found.kr = NULL;
969 hd->current.eof = 1;
970 return -1;
972 /* We could now create a positive search status and return.
973 * However the problem is that another instance of gpg may
974 * have changed the keyring so that the offsets are not valid
975 * anymore - therefore we don't do it
979 if (need_words)
981 const char *name = NULL;
983 log_debug ("word search mode does not yet work\n");
984 /* FIXME: here is a long standing bug in our function and in addition we
985 just use the first search description */
986 for (n=0; n < ndesc && !name; n++)
988 if (desc[n].mode == KEYDB_SEARCH_MODE_WORDS)
989 name = desc[n].u.name;
991 assert (name);
992 if ( !hd->word_match.name || strcmp (hd->word_match.name, name) )
994 /* name changed */
995 xfree (hd->word_match.name);
996 xfree (hd->word_match.pattern);
997 hd->word_match.name = xstrdup (name);
998 hd->word_match.pattern = prepare_word_match (name);
1000 name = hd->word_match.pattern;
1003 init_packet(&pkt);
1004 save_mode = set_packet_list_mode(0);
1006 hd->found.kr = NULL;
1007 main_offset = 0;
1008 pk_no = uid_no = 0;
1009 initial_skip = 1; /* skip until we see the start of a keyblock */
1010 while (!(rc=search_packet (hd->current.iobuf, &pkt, &offset, need_uid)))
1012 byte afp[MAX_FINGERPRINT_LEN];
1013 size_t an;
1015 if (pkt.pkttype == PKT_PUBLIC_KEY || pkt.pkttype == PKT_SECRET_KEY)
1017 main_offset = offset;
1018 pk_no = uid_no = 0;
1019 initial_skip = 0;
1021 if (initial_skip)
1023 free_packet (&pkt);
1024 continue;
1027 pk = NULL;
1028 sk = NULL;
1029 uid = NULL;
1030 if ( pkt.pkttype == PKT_PUBLIC_KEY
1031 || pkt.pkttype == PKT_PUBLIC_SUBKEY)
1033 pk = pkt.pkt.public_key;
1034 ++pk_no;
1036 if (need_fpr) {
1037 fingerprint_from_pk (pk, afp, &an);
1038 while (an < 20) /* fill up to 20 bytes */
1039 afp[an++] = 0;
1041 if (need_keyid)
1042 keyid_from_pk (pk, aki);
1044 if (use_offtbl && !kr_offtbl_ready)
1045 update_offset_hash_table (kr_offtbl, aki, main_offset);
1047 else if (pkt.pkttype == PKT_USER_ID)
1049 uid = pkt.pkt.user_id;
1050 ++uid_no;
1052 else if ( pkt.pkttype == PKT_SECRET_KEY
1053 || pkt.pkttype == PKT_SECRET_SUBKEY)
1055 sk = pkt.pkt.secret_key;
1056 ++pk_no;
1058 if (need_fpr) {
1059 fingerprint_from_sk (sk, afp, &an);
1060 while (an < 20) /* fill up to 20 bytes */
1061 afp[an++] = 0;
1063 if (need_keyid)
1064 keyid_from_sk (sk, aki);
1068 for (n=0; n < ndesc; n++)
1070 switch (desc[n].mode) {
1071 case KEYDB_SEARCH_MODE_NONE:
1072 BUG ();
1073 break;
1074 case KEYDB_SEARCH_MODE_EXACT:
1075 case KEYDB_SEARCH_MODE_SUBSTR:
1076 case KEYDB_SEARCH_MODE_MAIL:
1077 case KEYDB_SEARCH_MODE_MAILSUB:
1078 case KEYDB_SEARCH_MODE_MAILEND:
1079 case KEYDB_SEARCH_MODE_WORDS:
1080 if ( uid && !compare_name (desc[n].mode,
1081 desc[n].u.name,
1082 uid->name, uid->len))
1083 goto found;
1084 break;
1086 case KEYDB_SEARCH_MODE_SHORT_KID:
1087 if ((pk||sk) && desc[n].u.kid[1] == aki[1])
1088 goto found;
1089 break;
1090 case KEYDB_SEARCH_MODE_LONG_KID:
1091 if ((pk||sk) && desc[n].u.kid[0] == aki[0]
1092 && desc[n].u.kid[1] == aki[1])
1093 goto found;
1094 break;
1095 case KEYDB_SEARCH_MODE_FPR16:
1096 if ((pk||sk) && !memcmp (desc[n].u.fpr, afp, 16))
1097 goto found;
1098 break;
1099 case KEYDB_SEARCH_MODE_FPR20:
1100 case KEYDB_SEARCH_MODE_FPR:
1101 if ((pk||sk) && !memcmp (desc[n].u.fpr, afp, 20))
1102 goto found;
1103 break;
1104 case KEYDB_SEARCH_MODE_FIRST:
1105 if (pk||sk)
1106 goto found;
1107 break;
1108 case KEYDB_SEARCH_MODE_NEXT:
1109 if (pk||sk)
1110 goto found;
1111 break;
1112 default:
1113 rc = G10ERR_INV_ARG;
1114 goto found;
1117 free_packet (&pkt);
1118 continue;
1119 found:
1120 /* Record which desc we matched on. Note this value is only
1121 meaningful if this function returns with no errors. */
1122 if(descindex)
1123 *descindex=n;
1124 for (n=any_skip?0:ndesc; n < ndesc; n++)
1126 if (desc[n].skipfnc
1127 && desc[n].skipfnc (desc[n].skipfncvalue, aki, uid))
1128 break;
1130 if (n == ndesc)
1131 goto real_found;
1132 free_packet (&pkt);
1134 real_found:
1135 if (!rc)
1137 hd->found.offset = main_offset;
1138 hd->found.kr = hd->current.kr;
1139 hd->found.pk_no = (pk||sk)? pk_no : 0;
1140 hd->found.uid_no = uid? uid_no : 0;
1142 else if (rc == -1)
1144 hd->current.eof = 1;
1145 /* if we scanned all keyrings, we are sure that
1146 * all known key IDs are in our offtbl, mark that. */
1147 if (use_offtbl && !kr_offtbl_ready)
1149 KR_NAME kr;
1151 /* First set the did_full_scan flag for this keyring (ignore
1152 secret keyrings) */
1153 for (kr=kr_names; kr; kr = kr->next)
1155 if (!kr->secret && hd->resource == kr)
1157 kr->did_full_scan = 1;
1158 break;
1161 /* Then check whether all flags are set and if so, mark the
1162 offtbl ready */
1163 for (kr=kr_names; kr; kr = kr->next)
1165 if (!kr->secret && !kr->did_full_scan)
1166 break;
1168 if (!kr)
1169 kr_offtbl_ready = 1;
1172 else
1173 hd->current.error = rc;
1175 free_packet(&pkt);
1176 set_packet_list_mode(save_mode);
1177 return rc;
1181 static int
1182 create_tmp_file (const char *template,
1183 char **r_bakfname, char **r_tmpfname, IOBUF *r_fp)
1185 char *bakfname, *tmpfname;
1186 mode_t oldmask;
1188 *r_bakfname = NULL;
1189 *r_tmpfname = NULL;
1191 # ifdef USE_ONLY_8DOT3
1192 /* Here is another Windoze bug?:
1193 * you cant rename("pubring.gpg.tmp", "pubring.gpg");
1194 * but rename("pubring.gpg.tmp", "pubring.aaa");
1195 * works. So we replace .gpg by .bak or .tmp
1197 if (strlen (template) > 4
1198 && !strcmp (template+strlen(template)-4, EXTSEP_S "gpg") )
1200 bakfname = xmalloc (strlen (template) + 1);
1201 strcpy (bakfname, template);
1202 strcpy (bakfname+strlen(template)-4, EXTSEP_S "bak");
1204 tmpfname = xmalloc (strlen( template ) + 1 );
1205 strcpy (tmpfname,template);
1206 strcpy (tmpfname+strlen(template)-4, EXTSEP_S "tmp");
1208 else
1209 { /* file does not end with gpg; hmmm */
1210 bakfname = xmalloc (strlen( template ) + 5);
1211 strcpy (stpcpy(bakfname, template), EXTSEP_S "bak");
1213 tmpfname = xmalloc (strlen( template ) + 5);
1214 strcpy (stpcpy(tmpfname, template), EXTSEP_S "tmp");
1216 # else /* Posix file names */
1217 bakfname = xmalloc (strlen( template ) + 2);
1218 strcpy (stpcpy (bakfname,template),"~");
1220 tmpfname = xmalloc (strlen( template ) + 5);
1221 strcpy (stpcpy(tmpfname,template), EXTSEP_S "tmp");
1222 # endif /* Posix filename */
1224 /* Create the temp file with limited access */
1225 oldmask=umask(077);
1226 if (is_secured_filename (tmpfname))
1228 *r_fp = NULL;
1229 errno = EPERM;
1231 else
1232 *r_fp = iobuf_create (tmpfname);
1233 umask(oldmask);
1234 if (!*r_fp)
1236 int rc = gpg_error_from_syserror ();
1237 log_error(_("can't create `%s': %s\n"), tmpfname, strerror(errno) );
1238 xfree (tmpfname);
1239 xfree (bakfname);
1240 return rc;
1243 *r_bakfname = bakfname;
1244 *r_tmpfname = tmpfname;
1245 return 0;
1249 static int
1250 rename_tmp_file (const char *bakfname, const char *tmpfname,
1251 const char *fname, int secret )
1253 int rc = 0;
1255 /* It's a secret keyring, so let's force a fsync just to be safe on
1256 filesystems that may not sync data and metadata together
1257 (e.g. ext4). */
1258 if (secret && iobuf_ioctl (NULL, 4, 0, (char*)tmpfname))
1260 rc = gpg_error_from_syserror ();
1261 goto fail;
1264 /* Invalidate close caches. */
1265 if (iobuf_ioctl (NULL, 2, 0, (char*)tmpfname ))
1267 rc = gpg_error_from_syserror ();
1268 goto fail;
1270 iobuf_ioctl (NULL, 2, 0, (char*)bakfname );
1271 iobuf_ioctl (NULL, 2, 0, (char*)fname );
1273 /* first make a backup file except for secret keyrings */
1274 if (!secret)
1276 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
1277 remove (bakfname);
1278 #endif
1279 if (rename (fname, bakfname) )
1281 rc = gpg_error_from_syserror ();
1282 log_error ("renaming `%s' to `%s' failed: %s\n",
1283 fname, bakfname, strerror(errno) );
1284 return rc;
1288 /* then rename the file */
1289 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
1290 remove( fname );
1291 #endif
1292 if (secret)
1293 unregister_secured_file (fname);
1294 if (rename (tmpfname, fname) )
1296 rc = gpg_error_from_syserror ();
1297 log_error (_("renaming `%s' to `%s' failed: %s\n"),
1298 tmpfname, fname, strerror(errno) );
1299 register_secured_file (fname);
1300 goto fail;
1303 /* Now make sure the file has the same permissions as the original */
1305 #ifndef HAVE_DOSISH_SYSTEM
1307 struct stat statbuf;
1309 statbuf.st_mode=S_IRUSR | S_IWUSR;
1311 if (((secret && !opt.preserve_permissions)
1312 || !stat (bakfname,&statbuf))
1313 && !chmod (fname,statbuf.st_mode))
1315 else
1316 log_error ("WARNING: unable to restore permissions to `%s': %s",
1317 fname, strerror(errno));
1319 #endif
1321 return 0;
1323 fail:
1324 if (secret)
1326 log_info(_("WARNING: 2 files with confidential information exists.\n"));
1327 log_info(_("%s is the unchanged one\n"), fname );
1328 log_info(_("%s is the new one\n"), tmpfname );
1329 log_info(_("Please fix this possible security flaw\n"));
1331 return rc;
1335 static int
1336 write_keyblock (IOBUF fp, KBNODE keyblock)
1338 KBNODE kbctx = NULL, node;
1339 int rc;
1341 while ( (node = walk_kbnode (keyblock, &kbctx, 0)) )
1343 if (node->pkt->pkttype == PKT_RING_TRUST)
1344 continue; /* we write it later on our own */
1346 if ( (rc = build_packet (fp, node->pkt) ))
1348 log_error ("build_packet(%d) failed: %s\n",
1349 node->pkt->pkttype, g10_errstr(rc) );
1350 return rc;
1352 if (node->pkt->pkttype == PKT_SIGNATURE)
1353 { /* always write a signature cache packet */
1354 PKT_signature *sig = node->pkt->pkt.signature;
1355 unsigned int cacheval = 0;
1357 if (sig->flags.checked)
1359 cacheval |= 1;
1360 if (sig->flags.valid)
1361 cacheval |= 2;
1363 iobuf_put (fp, 0xb0); /* old style packet 12, 1 byte len*/
1364 iobuf_put (fp, 2); /* 2 bytes */
1365 iobuf_put (fp, 0); /* unused */
1366 if (iobuf_put (fp, cacheval))
1368 rc = gpg_error_from_syserror ();
1369 log_error ("writing sigcache packet failed\n");
1370 return rc;
1374 return 0;
1378 * Walk over all public keyrings, check the signatures and replace the
1379 * keyring with a new one where the signature cache is then updated.
1380 * This is only done for the public keyrings.
1383 keyring_rebuild_cache (void *token,int noisy)
1385 KEYRING_HANDLE hd;
1386 KEYDB_SEARCH_DESC desc;
1387 KBNODE keyblock = NULL, node;
1388 const char *lastresname = NULL, *resname;
1389 IOBUF tmpfp = NULL;
1390 char *tmpfilename = NULL;
1391 char *bakfilename = NULL;
1392 int rc;
1393 ulong count = 0, sigcount = 0;
1395 hd = keyring_new (token, 0);
1396 memset (&desc, 0, sizeof desc);
1397 desc.mode = KEYDB_SEARCH_MODE_FIRST;
1399 rc=keyring_lock (hd, 1);
1400 if(rc)
1401 goto leave;
1403 while ( !(rc = keyring_search (hd, &desc, 1, NULL)) )
1405 desc.mode = KEYDB_SEARCH_MODE_NEXT;
1406 resname = keyring_get_resource_name (hd);
1407 if (lastresname != resname )
1408 { /* we have switched to a new keyring - commit changes */
1409 if (tmpfp)
1411 if (iobuf_close (tmpfp))
1413 rc = gpg_error_from_syserror ();
1414 log_error ("error closing `%s': %s\n",
1415 tmpfilename, strerror (errno));
1416 goto leave;
1418 /* because we have switched resources, we can be sure that
1419 * the original file is closed */
1420 tmpfp = NULL;
1422 rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1423 lastresname, 0) : 0;
1424 xfree (tmpfilename); tmpfilename = NULL;
1425 xfree (bakfilename); bakfilename = NULL;
1426 if (rc)
1427 goto leave;
1428 lastresname = resname;
1429 if (noisy && !opt.quiet)
1430 log_info (_("caching keyring `%s'\n"), resname);
1431 rc = create_tmp_file (resname, &bakfilename, &tmpfilename, &tmpfp);
1432 if (rc)
1433 goto leave;
1436 release_kbnode (keyblock);
1437 rc = keyring_get_keyblock (hd, &keyblock);
1438 if (rc)
1440 log_error ("keyring_get_keyblock failed: %s\n", g10_errstr(rc));
1441 goto leave;
1443 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
1445 /* check all signature to set the signature's cache flags */
1446 for (node=keyblock; node; node=node->next)
1448 /* Note that this doesn't cache the result of a revocation
1449 issued by a designated revoker. This is because the pk
1450 in question does not carry the revkeys as we haven't
1451 merged the key and selfsigs. It is questionable whether
1452 this matters very much since there are very very few
1453 designated revoker revocation packets out there. */
1455 if (node->pkt->pkttype == PKT_SIGNATURE)
1457 PKT_signature *sig=node->pkt->pkt.signature;
1459 if(!opt.no_sig_cache && sig->flags.checked && sig->flags.valid
1460 && (openpgp_md_test_algo(sig->digest_algo)
1461 || openpgp_pk_test_algo(sig->pubkey_algo)))
1462 sig->flags.checked=sig->flags.valid=0;
1463 else
1464 check_key_signature (keyblock, node, NULL);
1466 sigcount++;
1470 /* write the keyblock to the temporary file */
1471 rc = write_keyblock (tmpfp, keyblock);
1472 if (rc)
1473 goto leave;
1475 if ( !(++count % 50) && noisy && !opt.quiet)
1476 log_info(_("%lu keys cached so far (%lu signatures)\n"),
1477 count, sigcount );
1479 } /* end main loop */
1480 if (rc == -1)
1481 rc = 0;
1482 if (rc)
1484 log_error ("keyring_search failed: %s\n", g10_errstr(rc));
1485 goto leave;
1487 if(noisy || opt.verbose)
1488 log_info(_("%lu keys cached (%lu signatures)\n"), count, sigcount );
1489 if (tmpfp)
1491 if (iobuf_close (tmpfp))
1493 rc = gpg_error_from_syserror ();
1494 log_error ("error closing `%s': %s\n",
1495 tmpfilename, strerror (errno));
1496 goto leave;
1498 /* because we have switched resources, we can be sure that
1499 * the original file is closed */
1500 tmpfp = NULL;
1502 rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1503 lastresname, 0) : 0;
1504 xfree (tmpfilename); tmpfilename = NULL;
1505 xfree (bakfilename); bakfilename = NULL;
1507 leave:
1508 if (tmpfp)
1509 iobuf_cancel (tmpfp);
1510 xfree (tmpfilename);
1511 xfree (bakfilename);
1512 release_kbnode (keyblock);
1513 keyring_lock (hd, 0);
1514 keyring_release (hd);
1515 return rc;
1519 /****************
1520 * Perform insert/delete/update operation.
1521 * mode 1 = insert
1522 * 2 = delete
1523 * 3 = update
1525 static int
1526 do_copy (int mode, const char *fname, KBNODE root, int secret,
1527 off_t start_offset, unsigned int n_packets )
1529 IOBUF fp, newfp;
1530 int rc=0;
1531 char *bakfname = NULL;
1532 char *tmpfname = NULL;
1534 /* Open the source file. Because we do a rename, we have to check the
1535 permissions of the file */
1536 if (access (fname, W_OK))
1537 return gpg_error_from_syserror ();
1539 fp = iobuf_open (fname);
1540 if (mode == 1 && !fp && errno == ENOENT) {
1541 /* insert mode but file does not exist: create a new file */
1542 KBNODE kbctx, node;
1543 mode_t oldmask;
1545 oldmask=umask(077);
1546 if (!secret && is_secured_filename (fname)) {
1547 newfp = NULL;
1548 errno = EPERM;
1550 else
1551 newfp = iobuf_create (fname);
1552 umask(oldmask);
1553 if( !newfp )
1555 rc = gpg_error_from_syserror ();
1556 log_error (_("can't create `%s': %s\n"), fname, strerror(errno));
1557 return rc;
1559 if( !opt.quiet )
1560 log_info(_("%s: keyring created\n"), fname );
1562 kbctx=NULL;
1563 while ( (node = walk_kbnode( root, &kbctx, 0 )) ) {
1564 if( (rc = build_packet( newfp, node->pkt )) ) {
1565 log_error("build_packet(%d) failed: %s\n",
1566 node->pkt->pkttype, g10_errstr(rc) );
1567 iobuf_cancel(newfp);
1568 return rc;
1571 if( iobuf_close(newfp) ) {
1572 rc = gpg_error_from_syserror ();
1573 log_error ("%s: close failed: %s\n", fname, strerror(errno));
1574 return rc;
1576 return 0; /* ready */
1579 if( !fp )
1581 rc = gpg_error_from_syserror ();
1582 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
1583 goto leave;
1586 /* Create the new file. */
1587 rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp);
1588 if (rc) {
1589 iobuf_close(fp);
1590 goto leave;
1592 if (secret)
1593 register_secured_file (tmpfname);
1595 if( mode == 1 ) { /* insert */
1596 /* copy everything to the new file */
1597 rc = copy_all_packets (fp, newfp);
1598 if( rc != -1 ) {
1599 log_error("%s: copy to `%s' failed: %s\n",
1600 fname, tmpfname, g10_errstr(rc) );
1601 iobuf_close(fp);
1602 if (secret)
1603 unregister_secured_file (tmpfname);
1604 iobuf_cancel(newfp);
1605 goto leave;
1607 rc = 0;
1610 if( mode == 2 || mode == 3 ) { /* delete or update */
1611 /* copy first part to the new file */
1612 rc = copy_some_packets( fp, newfp, start_offset );
1613 if( rc ) { /* should never get EOF here */
1614 log_error ("%s: copy to `%s' failed: %s\n",
1615 fname, tmpfname, g10_errstr(rc) );
1616 iobuf_close(fp);
1617 if (secret)
1618 unregister_secured_file (tmpfname);
1619 iobuf_cancel(newfp);
1620 goto leave;
1622 /* skip this keyblock */
1623 assert( n_packets );
1624 rc = skip_some_packets( fp, n_packets );
1625 if( rc ) {
1626 log_error("%s: skipping %u packets failed: %s\n",
1627 fname, n_packets, g10_errstr(rc));
1628 iobuf_close(fp);
1629 if (secret)
1630 unregister_secured_file (tmpfname);
1631 iobuf_cancel(newfp);
1632 goto leave;
1636 if( mode == 1 || mode == 3 ) { /* insert or update */
1637 rc = write_keyblock (newfp, root);
1638 if (rc) {
1639 iobuf_close(fp);
1640 if (secret)
1641 unregister_secured_file (tmpfname);
1642 iobuf_cancel(newfp);
1643 goto leave;
1647 if( mode == 2 || mode == 3 ) { /* delete or update */
1648 /* copy the rest */
1649 rc = copy_all_packets( fp, newfp );
1650 if( rc != -1 ) {
1651 log_error("%s: copy to `%s' failed: %s\n",
1652 fname, tmpfname, g10_errstr(rc) );
1653 iobuf_close(fp);
1654 if (secret)
1655 unregister_secured_file (tmpfname);
1656 iobuf_cancel(newfp);
1657 goto leave;
1659 rc = 0;
1662 /* close both files */
1663 if( iobuf_close(fp) ) {
1664 rc = gpg_error_from_syserror ();
1665 log_error("%s: close failed: %s\n", fname, strerror(errno) );
1666 goto leave;
1668 if( iobuf_close(newfp) ) {
1669 rc = gpg_error_from_syserror ();
1670 log_error("%s: close failed: %s\n", tmpfname, strerror(errno) );
1671 goto leave;
1674 rc = rename_tmp_file (bakfname, tmpfname, fname, secret);
1676 leave:
1677 xfree(bakfname);
1678 xfree(tmpfname);
1679 return rc;