Make gpgv error message about a missing keyring more useful. This fixes
[gnupg.git] / g10 / keyring.c
blobc01834a6acc9273f2344c4a7208f17ac91f820c2
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) {
430 /*(this code is duplicated after the loop)*/
431 if ( lastnode
432 && lastnode->pkt->pkttype == PKT_SIGNATURE
433 && (pkt->pkt.ring_trust->sigcache & 1) ) {
434 /* this is a ring trust packet with a checked signature
435 * status cache following directly a signature paket.
436 * Set the cache status into that signature packet */
437 PKT_signature *sig = lastnode->pkt->pkt.signature;
439 sig->flags.checked = 1;
440 sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
442 /* reset lastnode, so that we set the cache status only from
443 * the ring trust packet immediately folling a signature */
444 lastnode = NULL;
446 else {
447 node = lastnode = new_kbnode (pkt);
448 if (!keyblock)
449 keyblock = node;
450 else
451 add_kbnode (keyblock, node);
453 if ( pkt->pkttype == PKT_PUBLIC_KEY
454 || pkt->pkttype == PKT_PUBLIC_SUBKEY
455 || pkt->pkttype == PKT_SECRET_KEY
456 || pkt->pkttype == PKT_SECRET_SUBKEY) {
457 if (++pk_no == hd->found.pk_no)
458 node->flag |= 1;
460 else if ( pkt->pkttype == PKT_USER_ID) {
461 if (++uid_no == hd->found.uid_no)
462 node->flag |= 2;
466 pkt = xmalloc (sizeof *pkt);
467 init_packet(pkt);
469 set_packet_list_mode(save_mode);
471 if (rc == -1 && keyblock)
472 rc = 0; /* got the entire keyblock */
474 if (rc || !ret_kb)
475 release_kbnode (keyblock);
476 else {
477 /*(duplicated form the loop body)*/
478 if ( pkt && pkt->pkttype == PKT_RING_TRUST
479 && lastnode
480 && lastnode->pkt->pkttype == PKT_SIGNATURE
481 && (pkt->pkt.ring_trust->sigcache & 1) ) {
482 PKT_signature *sig = lastnode->pkt->pkt.signature;
483 sig->flags.checked = 1;
484 sig->flags.valid = !!(pkt->pkt.ring_trust->sigcache & 2);
486 *ret_kb = keyblock;
488 free_packet (pkt);
489 xfree (pkt);
490 iobuf_close(a);
492 /* Make sure that future search operations fail immediately when
493 * we know that we are working on a invalid keyring
495 if (rc == G10ERR_INV_KEYRING)
496 hd->current.error = rc;
498 return rc;
502 keyring_update_keyblock (KEYRING_HANDLE hd, KBNODE kb)
504 int rc;
506 if (!hd->found.kr)
507 return -1; /* no successful prior search */
509 if (hd->found.kr->readonly)
510 return gpg_error (GPG_ERR_EACCES);
512 if (!hd->found.n_packets) {
513 /* need to know the number of packets - do a dummy get_keyblock*/
514 rc = keyring_get_keyblock (hd, NULL);
515 if (rc) {
516 log_error ("re-reading keyblock failed: %s\n", g10_errstr (rc));
517 return rc;
519 if (!hd->found.n_packets)
520 BUG ();
523 /* The open iobuf isn't needed anymore and in fact is a problem when
524 it comes to renaming the keyring files on some operating systems,
525 so close it here */
526 iobuf_close(hd->current.iobuf);
527 hd->current.iobuf = NULL;
529 /* do the update */
530 rc = do_copy (3, hd->found.kr->fname, kb, hd->secret,
531 hd->found.offset, hd->found.n_packets );
532 if (!rc) {
533 if (!hd->secret && kr_offtbl)
535 update_offset_hash_table_from_kb (kr_offtbl, kb, 0);
537 /* better reset the found info */
538 hd->found.kr = NULL;
539 hd->found.offset = 0;
541 return rc;
545 keyring_insert_keyblock (KEYRING_HANDLE hd, KBNODE kb)
547 int rc;
548 const char *fname;
550 if (!hd)
551 fname = NULL;
552 else if (hd->found.kr)
554 fname = hd->found.kr->fname;
555 if (hd->found.kr->readonly)
556 return gpg_error (GPG_ERR_EACCES);
558 else if (hd->current.kr)
560 fname = hd->current.kr->fname;
561 if (hd->current.kr->readonly)
562 return gpg_error (GPG_ERR_EACCES);
564 else
565 fname = hd->resource? hd->resource->fname:NULL;
567 if (!fname)
568 return G10ERR_GENERAL;
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.
574 iobuf_close (hd->current.iobuf);
575 hd->current.iobuf = NULL;
577 /* do the insert */
578 rc = do_copy (1, fname, kb, hd->secret, 0, 0 );
579 if (!rc && !hd->secret && kr_offtbl)
581 update_offset_hash_table_from_kb (kr_offtbl, kb, 0);
584 return rc;
589 keyring_delete_keyblock (KEYRING_HANDLE hd)
591 int rc;
593 if (!hd->found.kr)
594 return -1; /* no successful prior search */
596 if (hd->found.kr->readonly)
597 return gpg_error (GPG_ERR_EACCES);
599 if (!hd->found.n_packets) {
600 /* need to know the number of packets - do a dummy get_keyblock*/
601 rc = keyring_get_keyblock (hd, NULL);
602 if (rc) {
603 log_error ("re-reading keyblock failed: %s\n", g10_errstr (rc));
604 return rc;
606 if (!hd->found.n_packets)
607 BUG ();
610 /* close this one otherwise we will lose the position for
611 * a next search. Fixme: it would be better to adjust the position
612 * after the write opertions.
614 iobuf_close (hd->current.iobuf);
615 hd->current.iobuf = NULL;
617 /* do the delete */
618 rc = do_copy (2, hd->found.kr->fname, NULL, hd->secret,
619 hd->found.offset, hd->found.n_packets );
620 if (!rc) {
621 /* better reset the found info */
622 hd->found.kr = NULL;
623 hd->found.offset = 0;
624 /* Delete is a rare operations, so we don't remove the keys
625 * from the offset table */
627 return rc;
633 * Start the next search on this handle right at the beginning
635 int
636 keyring_search_reset (KEYRING_HANDLE hd)
638 assert (hd);
640 hd->current.kr = NULL;
641 iobuf_close (hd->current.iobuf);
642 hd->current.iobuf = NULL;
643 hd->current.eof = 0;
644 hd->current.error = 0;
646 hd->found.kr = NULL;
647 hd->found.offset = 0;
648 return 0;
652 static int
653 prepare_search (KEYRING_HANDLE hd)
655 if (hd->current.error)
656 return hd->current.error; /* still in error state */
658 if (hd->current.kr && !hd->current.eof) {
659 if ( !hd->current.iobuf )
660 return G10ERR_GENERAL; /* position invalid after a modify */
661 return 0; /* okay */
664 if (!hd->current.kr && hd->current.eof)
665 return -1; /* still EOF */
667 if (!hd->current.kr) { /* start search with first keyring */
668 hd->current.kr = hd->resource;
669 if (!hd->current.kr) {
670 hd->current.eof = 1;
671 return -1; /* keyring not available */
673 assert (!hd->current.iobuf);
675 else { /* EOF */
676 iobuf_close (hd->current.iobuf);
677 hd->current.iobuf = NULL;
678 hd->current.kr = NULL;
679 hd->current.eof = 1;
680 return -1;
683 hd->current.eof = 0;
684 hd->current.iobuf = iobuf_open (hd->current.kr->fname);
685 if (!hd->current.iobuf)
687 hd->current.error = gpg_error_from_syserror ();
688 log_error(_("can't open `%s'\n"), hd->current.kr->fname );
689 return hd->current.error;
692 return 0;
696 /* A map of the all characters valid used for word_match()
697 * Valid characters are in in this table converted to uppercase.
698 * because the upper 128 bytes have special meaning, we assume
699 * that they are all valid.
700 * Note: We must use numerical values here in case that this program
701 * will be converted to those little blue HAL9000s with their strange
702 * EBCDIC character set (user ids are UTF-8).
703 * wk 2000-04-13: Hmmm, does this really make sense, given the fact that
704 * we can run gpg now on a S/390 running GNU/Linux, where the code
705 * translation is done by the device drivers?
707 static const byte word_match_chars[256] = {
708 /* 00 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
709 /* 08 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
710 /* 10 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
711 /* 18 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
712 /* 20 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
713 /* 28 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
714 /* 30 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
715 /* 38 */ 0x38, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
716 /* 40 */ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
717 /* 48 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
718 /* 50 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
719 /* 58 */ 0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
720 /* 60 */ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
721 /* 68 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
722 /* 70 */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
723 /* 78 */ 0x58, 0x59, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00,
724 /* 80 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
725 /* 88 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
726 /* 90 */ 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
727 /* 98 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
728 /* a0 */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
729 /* a8 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
730 /* b0 */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
731 /* b8 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
732 /* c0 */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
733 /* c8 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
734 /* d0 */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
735 /* d8 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
736 /* e0 */ 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
737 /* e8 */ 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
738 /* f0 */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
739 /* f8 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
742 /****************
743 * Do a word match (original user id starts with a '+').
744 * The pattern is already tokenized to a more suitable format:
745 * There are only the real words in it delimited by one space
746 * and all converted to uppercase.
748 * Returns: 0 if all words match.
750 * Note: This algorithm is a straightforward one and not very
751 * fast. It works for UTF-8 strings. The uidlen should
752 * be removed but due to the fact that old versions of
753 * pgp don't use UTF-8 we still use the length; this should
754 * be fixed in parse-packet (and replace \0 by some special
755 * UTF-8 encoding)
757 static int
758 word_match( const byte *uid, size_t uidlen, const byte *pattern )
760 size_t wlen, n;
761 const byte *p;
762 const byte *s;
764 for( s=pattern; *s; ) {
765 do {
766 /* skip leading delimiters */
767 while( uidlen && !word_match_chars[*uid] )
768 uid++, uidlen--;
769 /* get length of the word */
770 n = uidlen; p = uid;
771 while( n && word_match_chars[*p] )
772 p++, n--;
773 wlen = p - uid;
774 /* and compare against the current word from pattern */
775 for(n=0, p=uid; n < wlen && s[n] != ' ' && s[n] ; n++, p++ ) {
776 if( word_match_chars[*p] != s[n] )
777 break;
779 if( n == wlen && (s[n] == ' ' || !s[n]) )
780 break; /* found */
781 uid += wlen;
782 uidlen -= wlen;
783 } while( uidlen );
784 if( !uidlen )
785 return -1; /* not found */
787 /* advance to next word in pattern */
788 for(; *s != ' ' && *s ; s++ )
790 if( *s )
791 s++ ;
793 return 0; /* found */
796 /****************
797 * prepare word word_match; that is parse the name and
798 * build the pattern.
799 * caller has to free the returned pattern
801 static char*
802 prepare_word_match (const byte *name)
804 byte *pattern, *p;
805 int c;
807 /* the original length is always enough for the pattern */
808 p = pattern = xmalloc(strlen(name)+1);
809 do {
810 /* skip leading delimiters */
811 while( *name && !word_match_chars[*name] )
812 name++;
813 /* copy as long as we don't have a delimiter and convert
814 * to uppercase.
815 * fixme: how can we handle utf8 uppercasing */
816 for( ; *name && (c=word_match_chars[*name]); name++ )
817 *p++ = c;
818 *p++ = ' '; /* append pattern delimiter */
819 } while( *name );
820 p[-1] = 0; /* replace last pattern delimiter by EOS */
822 return pattern;
828 static int
829 compare_name (int mode, const char *name, const char *uid, size_t uidlen)
831 int i;
832 const char *s, *se;
834 if (mode == KEYDB_SEARCH_MODE_EXACT) {
835 for (i=0; name[i] && uidlen; i++, uidlen--)
836 if (uid[i] != name[i])
837 break;
838 if (!uidlen && !name[i])
839 return 0; /* found */
841 else if (mode == KEYDB_SEARCH_MODE_SUBSTR) {
842 if (ascii_memistr( uid, uidlen, name ))
843 return 0;
845 else if ( mode == KEYDB_SEARCH_MODE_MAIL
846 || mode == KEYDB_SEARCH_MODE_MAILSUB
847 || mode == KEYDB_SEARCH_MODE_MAILEND) {
848 for (i=0, s= uid; i < uidlen && *s != '<'; s++, i++)
850 if (i < uidlen) {
851 /* skip opening delim and one char and look for the closing one*/
852 s++; i++;
853 for (se=s+1, i++; i < uidlen && *se != '>'; se++, i++)
855 if (i < uidlen) {
856 i = se - s;
857 if (mode == KEYDB_SEARCH_MODE_MAIL) {
858 if( strlen(name)-2 == i
859 && !ascii_memcasecmp( s, name+1, i) )
860 return 0;
862 else if (mode == KEYDB_SEARCH_MODE_MAILSUB) {
863 if( ascii_memistr( s, i, name ) )
864 return 0;
866 else { /* email from end */
867 /* nyi */
872 else if (mode == KEYDB_SEARCH_MODE_WORDS)
873 return word_match (uid, uidlen, name);
874 else
875 BUG();
877 return -1; /* not found */
882 * Search through the keyring(s), starting at the current position,
883 * for a keyblock which contains one of the keys described in the DESC array.
885 int
886 keyring_search (KEYRING_HANDLE hd, KEYDB_SEARCH_DESC *desc,
887 size_t ndesc, size_t *descindex)
889 int rc;
890 PACKET pkt;
891 int save_mode;
892 off_t offset, main_offset;
893 size_t n;
894 int need_uid, need_words, need_keyid, need_fpr, any_skip;
895 int pk_no, uid_no;
896 int initial_skip;
897 int use_offtbl;
898 PKT_user_id *uid = NULL;
899 PKT_public_key *pk = NULL;
900 PKT_secret_key *sk = NULL;
901 u32 aki[2];
903 /* figure out what information we need */
904 need_uid = need_words = need_keyid = need_fpr = any_skip = 0;
905 for (n=0; n < ndesc; n++)
907 switch (desc[n].mode)
909 case KEYDB_SEARCH_MODE_EXACT:
910 case KEYDB_SEARCH_MODE_SUBSTR:
911 case KEYDB_SEARCH_MODE_MAIL:
912 case KEYDB_SEARCH_MODE_MAILSUB:
913 case KEYDB_SEARCH_MODE_MAILEND:
914 need_uid = 1;
915 break;
916 case KEYDB_SEARCH_MODE_WORDS:
917 need_uid = 1;
918 need_words = 1;
919 break;
920 case KEYDB_SEARCH_MODE_SHORT_KID:
921 case KEYDB_SEARCH_MODE_LONG_KID:
922 need_keyid = 1;
923 break;
924 case KEYDB_SEARCH_MODE_FPR16:
925 case KEYDB_SEARCH_MODE_FPR20:
926 case KEYDB_SEARCH_MODE_FPR:
927 need_fpr = 1;
928 break;
929 case KEYDB_SEARCH_MODE_FIRST:
930 /* always restart the search in this mode */
931 keyring_search_reset (hd);
932 break;
933 default: break;
935 if (desc[n].skipfnc)
937 any_skip = 1;
938 need_keyid = 1;
942 rc = prepare_search (hd);
943 if (rc)
944 return rc;
946 use_offtbl = !hd->secret && kr_offtbl;
947 if (!use_offtbl)
949 else if (!kr_offtbl_ready)
950 need_keyid = 1;
951 else if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID)
953 struct off_item *oi;
955 oi = lookup_offset_hash_table (kr_offtbl, desc[0].u.kid);
956 if (!oi)
957 { /* We know that we don't have this key */
958 hd->found.kr = NULL;
959 hd->current.eof = 1;
960 return -1;
962 /* We could now create a positive search status and return.
963 * However the problem is that another instance of gpg may
964 * have changed the keyring so that the offsets are not valid
965 * anymore - therefore we don't do it
969 if (need_words)
971 const char *name = NULL;
973 log_debug ("word search mode does not yet work\n");
974 /* FIXME: here is a long standing bug in our function and in addition we
975 just use the first search description */
976 for (n=0; n < ndesc && !name; n++)
978 if (desc[n].mode == KEYDB_SEARCH_MODE_WORDS)
979 name = desc[n].u.name;
981 assert (name);
982 if ( !hd->word_match.name || strcmp (hd->word_match.name, name) )
984 /* name changed */
985 xfree (hd->word_match.name);
986 xfree (hd->word_match.pattern);
987 hd->word_match.name = xstrdup (name);
988 hd->word_match.pattern = prepare_word_match (name);
990 name = hd->word_match.pattern;
993 init_packet(&pkt);
994 save_mode = set_packet_list_mode(0);
996 hd->found.kr = NULL;
997 main_offset = 0;
998 pk_no = uid_no = 0;
999 initial_skip = 1; /* skip until we see the start of a keyblock */
1000 while (!(rc=search_packet (hd->current.iobuf, &pkt, &offset, need_uid)))
1002 byte afp[MAX_FINGERPRINT_LEN];
1003 size_t an;
1005 if (pkt.pkttype == PKT_PUBLIC_KEY || pkt.pkttype == PKT_SECRET_KEY)
1007 main_offset = offset;
1008 pk_no = uid_no = 0;
1009 initial_skip = 0;
1011 if (initial_skip)
1013 free_packet (&pkt);
1014 continue;
1017 pk = NULL;
1018 sk = NULL;
1019 uid = NULL;
1020 if ( pkt.pkttype == PKT_PUBLIC_KEY
1021 || pkt.pkttype == PKT_PUBLIC_SUBKEY)
1023 pk = pkt.pkt.public_key;
1024 ++pk_no;
1026 if (need_fpr) {
1027 fingerprint_from_pk (pk, afp, &an);
1028 while (an < 20) /* fill up to 20 bytes */
1029 afp[an++] = 0;
1031 if (need_keyid)
1032 keyid_from_pk (pk, aki);
1034 if (use_offtbl && !kr_offtbl_ready)
1035 update_offset_hash_table (kr_offtbl, aki, main_offset);
1037 else if (pkt.pkttype == PKT_USER_ID)
1039 uid = pkt.pkt.user_id;
1040 ++uid_no;
1042 else if ( pkt.pkttype == PKT_SECRET_KEY
1043 || pkt.pkttype == PKT_SECRET_SUBKEY)
1045 sk = pkt.pkt.secret_key;
1046 ++pk_no;
1048 if (need_fpr) {
1049 fingerprint_from_sk (sk, afp, &an);
1050 while (an < 20) /* fill up to 20 bytes */
1051 afp[an++] = 0;
1053 if (need_keyid)
1054 keyid_from_sk (sk, aki);
1058 for (n=0; n < ndesc; n++)
1060 switch (desc[n].mode) {
1061 case KEYDB_SEARCH_MODE_NONE:
1062 BUG ();
1063 break;
1064 case KEYDB_SEARCH_MODE_EXACT:
1065 case KEYDB_SEARCH_MODE_SUBSTR:
1066 case KEYDB_SEARCH_MODE_MAIL:
1067 case KEYDB_SEARCH_MODE_MAILSUB:
1068 case KEYDB_SEARCH_MODE_MAILEND:
1069 case KEYDB_SEARCH_MODE_WORDS:
1070 if ( uid && !compare_name (desc[n].mode,
1071 desc[n].u.name,
1072 uid->name, uid->len))
1073 goto found;
1074 break;
1076 case KEYDB_SEARCH_MODE_SHORT_KID:
1077 if ((pk||sk) && desc[n].u.kid[1] == aki[1])
1078 goto found;
1079 break;
1080 case KEYDB_SEARCH_MODE_LONG_KID:
1081 if ((pk||sk) && desc[n].u.kid[0] == aki[0]
1082 && desc[n].u.kid[1] == aki[1])
1083 goto found;
1084 break;
1085 case KEYDB_SEARCH_MODE_FPR16:
1086 if ((pk||sk) && !memcmp (desc[n].u.fpr, afp, 16))
1087 goto found;
1088 break;
1089 case KEYDB_SEARCH_MODE_FPR20:
1090 case KEYDB_SEARCH_MODE_FPR:
1091 if ((pk||sk) && !memcmp (desc[n].u.fpr, afp, 20))
1092 goto found;
1093 break;
1094 case KEYDB_SEARCH_MODE_FIRST:
1095 if (pk||sk)
1096 goto found;
1097 break;
1098 case KEYDB_SEARCH_MODE_NEXT:
1099 if (pk||sk)
1100 goto found;
1101 break;
1102 default:
1103 rc = G10ERR_INV_ARG;
1104 goto found;
1107 free_packet (&pkt);
1108 continue;
1109 found:
1110 /* Record which desc we matched on. Note this value is only
1111 meaningful if this function returns with no errors. */
1112 if(descindex)
1113 *descindex=n;
1114 for (n=any_skip?0:ndesc; n < ndesc; n++)
1116 if (desc[n].skipfnc
1117 && desc[n].skipfnc (desc[n].skipfncvalue, aki, uid))
1118 break;
1120 if (n == ndesc)
1121 goto real_found;
1122 free_packet (&pkt);
1124 real_found:
1125 if (!rc)
1127 hd->found.offset = main_offset;
1128 hd->found.kr = hd->current.kr;
1129 hd->found.pk_no = (pk||sk)? pk_no : 0;
1130 hd->found.uid_no = uid? uid_no : 0;
1132 else if (rc == -1)
1134 hd->current.eof = 1;
1135 /* if we scanned all keyrings, we are sure that
1136 * all known key IDs are in our offtbl, mark that. */
1137 if (use_offtbl && !kr_offtbl_ready)
1139 KR_NAME kr;
1141 /* First set the did_full_scan flag for this keyring (ignore
1142 secret keyrings) */
1143 for (kr=kr_names; kr; kr = kr->next)
1145 if (!kr->secret && hd->resource == kr)
1147 kr->did_full_scan = 1;
1148 break;
1151 /* Then check whether all flags are set and if so, mark the
1152 offtbl ready */
1153 for (kr=kr_names; kr; kr = kr->next)
1155 if (!kr->secret && !kr->did_full_scan)
1156 break;
1158 if (!kr)
1159 kr_offtbl_ready = 1;
1162 else
1163 hd->current.error = rc;
1165 free_packet(&pkt);
1166 set_packet_list_mode(save_mode);
1167 return rc;
1171 static int
1172 create_tmp_file (const char *template,
1173 char **r_bakfname, char **r_tmpfname, IOBUF *r_fp)
1175 char *bakfname, *tmpfname;
1176 mode_t oldmask;
1178 *r_bakfname = NULL;
1179 *r_tmpfname = NULL;
1181 # ifdef USE_ONLY_8DOT3
1182 /* Here is another Windoze bug?:
1183 * you cant rename("pubring.gpg.tmp", "pubring.gpg");
1184 * but rename("pubring.gpg.tmp", "pubring.aaa");
1185 * works. So we replace .gpg by .bak or .tmp
1187 if (strlen (template) > 4
1188 && !strcmp (template+strlen(template)-4, EXTSEP_S "gpg") )
1190 bakfname = xmalloc (strlen (template) + 1);
1191 strcpy (bakfname, template);
1192 strcpy (bakfname+strlen(template)-4, EXTSEP_S "bak");
1194 tmpfname = xmalloc (strlen( template ) + 1 );
1195 strcpy (tmpfname,template);
1196 strcpy (tmpfname+strlen(template)-4, EXTSEP_S "tmp");
1198 else
1199 { /* file does not end with gpg; hmmm */
1200 bakfname = xmalloc (strlen( template ) + 5);
1201 strcpy (stpcpy(bakfname, template), EXTSEP_S "bak");
1203 tmpfname = xmalloc (strlen( template ) + 5);
1204 strcpy (stpcpy(tmpfname, template), EXTSEP_S "tmp");
1206 # else /* Posix file names */
1207 bakfname = xmalloc (strlen( template ) + 2);
1208 strcpy (stpcpy (bakfname,template),"~");
1210 tmpfname = xmalloc (strlen( template ) + 5);
1211 strcpy (stpcpy(tmpfname,template), EXTSEP_S "tmp");
1212 # endif /* Posix filename */
1214 /* Create the temp file with limited access */
1215 oldmask=umask(077);
1216 if (is_secured_filename (tmpfname))
1218 *r_fp = NULL;
1219 errno = EPERM;
1221 else
1222 *r_fp = iobuf_create (tmpfname);
1223 umask(oldmask);
1224 if (!*r_fp)
1226 int rc = gpg_error_from_syserror ();
1227 log_error(_("can't create `%s': %s\n"), tmpfname, strerror(errno) );
1228 xfree (tmpfname);
1229 xfree (bakfname);
1230 return rc;
1233 *r_bakfname = bakfname;
1234 *r_tmpfname = tmpfname;
1235 return 0;
1239 static int
1240 rename_tmp_file (const char *bakfname, const char *tmpfname,
1241 const char *fname, int secret )
1243 int rc = 0;
1245 /* It's a secret keyring, so let's force a fsync just to be safe on
1246 filesystems that may not sync data and metadata together
1247 (e.g. ext4). */
1248 if (secret && iobuf_ioctl (NULL, 4, 0, (char*)tmpfname))
1250 rc = gpg_error_from_syserror ();
1251 goto fail;
1254 /* Invalidate close caches. */
1255 if (iobuf_ioctl (NULL, 2, 0, (char*)tmpfname ))
1257 rc = gpg_error_from_syserror ();
1258 goto fail;
1260 iobuf_ioctl (NULL, 2, 0, (char*)bakfname );
1261 iobuf_ioctl (NULL, 2, 0, (char*)fname );
1263 /* first make a backup file except for secret keyrings */
1264 if (!secret)
1266 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
1267 remove (bakfname);
1268 #endif
1269 if (rename (fname, bakfname) )
1271 rc = gpg_error_from_syserror ();
1272 log_error ("renaming `%s' to `%s' failed: %s\n",
1273 fname, bakfname, strerror(errno) );
1274 return rc;
1278 /* then rename the file */
1279 #if defined(HAVE_DOSISH_SYSTEM) || defined(__riscos__)
1280 remove( fname );
1281 #endif
1282 if (secret)
1283 unregister_secured_file (fname);
1284 if (rename (tmpfname, fname) )
1286 rc = gpg_error_from_syserror ();
1287 log_error (_("renaming `%s' to `%s' failed: %s\n"),
1288 tmpfname, fname, strerror(errno) );
1289 register_secured_file (fname);
1290 goto fail;
1293 /* Now make sure the file has the same permissions as the original */
1295 #ifndef HAVE_DOSISH_SYSTEM
1297 struct stat statbuf;
1299 statbuf.st_mode=S_IRUSR | S_IWUSR;
1301 if (((secret && !opt.preserve_permissions)
1302 || !stat (bakfname,&statbuf))
1303 && !chmod (fname,statbuf.st_mode))
1305 else
1306 log_error ("WARNING: unable to restore permissions to `%s': %s",
1307 fname, strerror(errno));
1309 #endif
1311 return 0;
1313 fail:
1314 if (secret)
1316 log_info(_("WARNING: 2 files with confidential information exists.\n"));
1317 log_info(_("%s is the unchanged one\n"), fname );
1318 log_info(_("%s is the new one\n"), tmpfname );
1319 log_info(_("Please fix this possible security flaw\n"));
1321 return rc;
1325 static int
1326 write_keyblock (IOBUF fp, KBNODE keyblock)
1328 KBNODE kbctx = NULL, node;
1329 int rc;
1331 while ( (node = walk_kbnode (keyblock, &kbctx, 0)) )
1333 if (node->pkt->pkttype == PKT_RING_TRUST)
1334 continue; /* we write it later on our own */
1336 if ( (rc = build_packet (fp, node->pkt) ))
1338 log_error ("build_packet(%d) failed: %s\n",
1339 node->pkt->pkttype, g10_errstr(rc) );
1340 return rc;
1342 if (node->pkt->pkttype == PKT_SIGNATURE)
1343 { /* always write a signature cache packet */
1344 PKT_signature *sig = node->pkt->pkt.signature;
1345 unsigned int cacheval = 0;
1347 if (sig->flags.checked)
1349 cacheval |= 1;
1350 if (sig->flags.valid)
1351 cacheval |= 2;
1353 iobuf_put (fp, 0xb0); /* old style packet 12, 1 byte len*/
1354 iobuf_put (fp, 2); /* 2 bytes */
1355 iobuf_put (fp, 0); /* unused */
1356 if (iobuf_put (fp, cacheval))
1358 rc = gpg_error_from_syserror ();
1359 log_error ("writing sigcache packet failed\n");
1360 return rc;
1364 return 0;
1368 * Walk over all public keyrings, check the signatures and replace the
1369 * keyring with a new one where the signature cache is then updated.
1370 * This is only done for the public keyrings.
1373 keyring_rebuild_cache (void *token,int noisy)
1375 KEYRING_HANDLE hd;
1376 KEYDB_SEARCH_DESC desc;
1377 KBNODE keyblock = NULL, node;
1378 const char *lastresname = NULL, *resname;
1379 IOBUF tmpfp = NULL;
1380 char *tmpfilename = NULL;
1381 char *bakfilename = NULL;
1382 int rc;
1383 ulong count = 0, sigcount = 0;
1385 hd = keyring_new (token, 0);
1386 memset (&desc, 0, sizeof desc);
1387 desc.mode = KEYDB_SEARCH_MODE_FIRST;
1389 rc=keyring_lock (hd, 1);
1390 if(rc)
1391 goto leave;
1393 while ( !(rc = keyring_search (hd, &desc, 1, NULL)) )
1395 desc.mode = KEYDB_SEARCH_MODE_NEXT;
1396 resname = keyring_get_resource_name (hd);
1397 if (lastresname != resname )
1398 { /* we have switched to a new keyring - commit changes */
1399 if (tmpfp)
1401 if (iobuf_close (tmpfp))
1403 rc = gpg_error_from_syserror ();
1404 log_error ("error closing `%s': %s\n",
1405 tmpfilename, strerror (errno));
1406 goto leave;
1408 /* because we have switched resources, we can be sure that
1409 * the original file is closed */
1410 tmpfp = NULL;
1412 rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1413 lastresname, 0) : 0;
1414 xfree (tmpfilename); tmpfilename = NULL;
1415 xfree (bakfilename); bakfilename = NULL;
1416 if (rc)
1417 goto leave;
1418 lastresname = resname;
1419 if (noisy && !opt.quiet)
1420 log_info (_("caching keyring `%s'\n"), resname);
1421 rc = create_tmp_file (resname, &bakfilename, &tmpfilename, &tmpfp);
1422 if (rc)
1423 goto leave;
1426 release_kbnode (keyblock);
1427 rc = keyring_get_keyblock (hd, &keyblock);
1428 if (rc)
1430 log_error ("keyring_get_keyblock failed: %s\n", g10_errstr(rc));
1431 goto leave;
1433 assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
1435 /* check all signature to set the signature's cache flags */
1436 for (node=keyblock; node; node=node->next)
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. */
1445 if (node->pkt->pkttype == PKT_SIGNATURE)
1447 PKT_signature *sig=node->pkt->pkt.signature;
1449 if(!opt.no_sig_cache && sig->flags.checked && sig->flags.valid
1450 && (openpgp_md_test_algo(sig->digest_algo)
1451 || openpgp_pk_test_algo(sig->pubkey_algo)))
1452 sig->flags.checked=sig->flags.valid=0;
1453 else
1454 check_key_signature (keyblock, node, NULL);
1456 sigcount++;
1460 /* write the keyblock to the temporary file */
1461 rc = write_keyblock (tmpfp, keyblock);
1462 if (rc)
1463 goto leave;
1465 if ( !(++count % 50) && noisy && !opt.quiet)
1466 log_info(_("%lu keys cached so far (%lu signatures)\n"),
1467 count, sigcount );
1469 } /* end main loop */
1470 if (rc == -1)
1471 rc = 0;
1472 if (rc)
1474 log_error ("keyring_search failed: %s\n", g10_errstr(rc));
1475 goto leave;
1477 if(noisy || opt.verbose)
1478 log_info(_("%lu keys cached (%lu signatures)\n"), count, sigcount );
1479 if (tmpfp)
1481 if (iobuf_close (tmpfp))
1483 rc = gpg_error_from_syserror ();
1484 log_error ("error closing `%s': %s\n",
1485 tmpfilename, strerror (errno));
1486 goto leave;
1488 /* because we have switched resources, we can be sure that
1489 * the original file is closed */
1490 tmpfp = NULL;
1492 rc = lastresname? rename_tmp_file (bakfilename, tmpfilename,
1493 lastresname, 0) : 0;
1494 xfree (tmpfilename); tmpfilename = NULL;
1495 xfree (bakfilename); bakfilename = NULL;
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;
1509 /****************
1510 * Perform insert/delete/update operation.
1511 * mode 1 = insert
1512 * 2 = delete
1513 * 3 = update
1515 static int
1516 do_copy (int mode, const char *fname, KBNODE root, int secret,
1517 off_t start_offset, unsigned int n_packets )
1519 IOBUF fp, newfp;
1520 int rc=0;
1521 char *bakfname = NULL;
1522 char *tmpfname = NULL;
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 gpg_error_from_syserror ();
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;
1535 oldmask=umask(077);
1536 if (!secret && is_secured_filename (fname)) {
1537 newfp = NULL;
1538 errno = EPERM;
1540 else
1541 newfp = iobuf_create (fname);
1542 umask(oldmask);
1543 if( !newfp )
1545 rc = gpg_error_from_syserror ();
1546 log_error (_("can't create `%s': %s\n"), fname, strerror(errno));
1547 return rc;
1549 if( !opt.quiet )
1550 log_info(_("%s: keyring created\n"), fname );
1552 kbctx=NULL;
1553 while ( (node = walk_kbnode( root, &kbctx, 0 )) ) {
1554 if( (rc = build_packet( newfp, node->pkt )) ) {
1555 log_error("build_packet(%d) failed: %s\n",
1556 node->pkt->pkttype, g10_errstr(rc) );
1557 iobuf_cancel(newfp);
1558 return rc;
1561 if( iobuf_close(newfp) ) {
1562 rc = gpg_error_from_syserror ();
1563 log_error ("%s: close failed: %s\n", fname, strerror(errno));
1564 return rc;
1566 return 0; /* ready */
1569 if( !fp )
1571 rc = gpg_error_from_syserror ();
1572 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
1573 goto leave;
1576 /* Create the new file. */
1577 rc = create_tmp_file (fname, &bakfname, &tmpfname, &newfp);
1578 if (rc) {
1579 iobuf_close(fp);
1580 goto leave;
1582 if (secret)
1583 register_secured_file (tmpfname);
1585 if( mode == 1 ) { /* insert */
1586 /* copy everything to the new file */
1587 rc = copy_all_packets (fp, newfp);
1588 if( rc != -1 ) {
1589 log_error("%s: copy to `%s' failed: %s\n",
1590 fname, tmpfname, g10_errstr(rc) );
1591 iobuf_close(fp);
1592 if (secret)
1593 unregister_secured_file (tmpfname);
1594 iobuf_cancel(newfp);
1595 goto leave;
1597 rc = 0;
1600 if( mode == 2 || mode == 3 ) { /* delete or update */
1601 /* copy first part to the new file */
1602 rc = copy_some_packets( fp, newfp, start_offset );
1603 if( rc ) { /* should never get EOF here */
1604 log_error ("%s: copy to `%s' failed: %s\n",
1605 fname, tmpfname, g10_errstr(rc) );
1606 iobuf_close(fp);
1607 if (secret)
1608 unregister_secured_file (tmpfname);
1609 iobuf_cancel(newfp);
1610 goto leave;
1612 /* skip this keyblock */
1613 assert( n_packets );
1614 rc = skip_some_packets( fp, n_packets );
1615 if( rc ) {
1616 log_error("%s: skipping %u packets failed: %s\n",
1617 fname, n_packets, g10_errstr(rc));
1618 iobuf_close(fp);
1619 if (secret)
1620 unregister_secured_file (tmpfname);
1621 iobuf_cancel(newfp);
1622 goto leave;
1626 if( mode == 1 || mode == 3 ) { /* insert or update */
1627 rc = write_keyblock (newfp, root);
1628 if (rc) {
1629 iobuf_close(fp);
1630 if (secret)
1631 unregister_secured_file (tmpfname);
1632 iobuf_cancel(newfp);
1633 goto leave;
1637 if( mode == 2 || mode == 3 ) { /* delete or update */
1638 /* copy the rest */
1639 rc = copy_all_packets( fp, newfp );
1640 if( rc != -1 ) {
1641 log_error("%s: copy to `%s' failed: %s\n",
1642 fname, tmpfname, g10_errstr(rc) );
1643 iobuf_close(fp);
1644 if (secret)
1645 unregister_secured_file (tmpfname);
1646 iobuf_cancel(newfp);
1647 goto leave;
1649 rc = 0;
1652 /* close both files */
1653 if( iobuf_close(fp) ) {
1654 rc = gpg_error_from_syserror ();
1655 log_error("%s: close failed: %s\n", fname, strerror(errno) );
1656 goto leave;
1658 if( iobuf_close(newfp) ) {
1659 rc = gpg_error_from_syserror ();
1660 log_error("%s: close failed: %s\n", tmpfname, strerror(errno) );
1661 goto leave;
1664 rc = rename_tmp_file (bakfname, tmpfname, fname, secret);
1666 leave:
1667 xfree(bakfname);
1668 xfree(tmpfname);
1669 return rc;