1 /* keydb.c - key database dispatcher
2 * Copyright (C) 2001-2013 Free Software Foundation, Inc.
3 * Coyrright (C) 2001-2015 Werner Koch
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
26 #include <sys/types.h>
33 #include "main.h" /*try_make_homedir ()*/
36 #include "../kbx/keybox.h"
40 static int active_handles;
44 KEYDB_RESOURCE_TYPE_NONE = 0,
45 KEYDB_RESOURCE_TYPE_KEYRING,
46 KEYDB_RESOURCE_TYPE_KEYBOX
48 #define MAX_KEYDB_RESOURCES 40
52 KeydbResourceType type;
60 static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
61 static int used_resources;
63 /* A pointer used to check for the primary key database by comparing
64 to the struct resource_item's TOKEN. */
65 static void *primary_keydb;
68 /* This is a simple cache used to return the last result of a
69 successful fingerprint search. This works only for keybox resources
70 because (due to lack of a copy_keyblock function) we need to store
71 an image of the keyblock which is fortunately instantly available
73 enum keyblock_cache_states {
75 KEYBLOCK_CACHE_PREPARED,
79 struct keyblock_cache {
80 enum keyblock_cache_states state;
81 byte fpr[MAX_FINGERPRINT_LEN];
82 iobuf_t iobuf; /* Image of the keyblock. */
86 /* Offset of the record in the keybox. */
94 /* When we locked all of the resources in ACTIVE (using keyring_lock
95 / keybox_lock, as appropriate). */
98 /* The index into ACTIVE of the resources in which the last search
99 result was found. Initially -1. */
102 /* Initially -1 (invalid). This is used to save a search result and
103 later restore it as the selected result. */
106 /* The number of skipped long blobs since the last search
107 (keydb_search_reset). */
108 unsigned long skipped_long_blobs;
110 /* If set, this disables the use of the keyblock cache. */
113 /* Whether the next search will be from the beginning of the
114 database (and thus consider all records). */
117 /* The "file position." In our case, this is index of the current
118 resource in ACTIVE. */
121 /* The number of resources in ACTIVE. */
124 /* Cache of the last found and parsed key block (only used for
125 keyboxes, not keyrings). */
126 struct keyblock_cache keyblock_cache;
128 /* Copy of ALL_RESOURCES when keydb_new is called. */
129 struct resource_item active[MAX_KEYDB_RESOURCES];
132 /* Looking up keys is expensive. To hide the cost, we cache whether
133 keys exist in the key database. Then, if we know a key does not
134 exist, we don't have to spend time looking it up. This
135 particularly helps the --list-sigs and --check-sigs commands.
137 The cache stores the results in a hash using separate chaining.
138 Concretely: we use the LSB of the keyid to index the hash table and
139 each bucket consists of a linked list of entries. An entry
140 consists of the 64-bit key id. If a key id is not in the cache,
141 then we don't know whether it is in the DB or not.
143 To simplify the cache consistency protocol, we simply flush the
144 whole cache whenever a key is inserted or updated. */
146 #define KID_NOT_FOUND_CACHE_BUCKETS 256
147 static struct kid_not_found_cache_bucket *
148 kid_not_found_cache[KID_NOT_FOUND_CACHE_BUCKETS];
150 /* The total number of entries in the hash table. */
151 static unsigned int kid_not_found_cache_count;
153 struct kid_not_found_cache_bucket
155 struct kid_not_found_cache_bucket *next;
160 static int lock_all (KEYDB_HANDLE hd);
161 static void unlock_all (KEYDB_HANDLE hd);
164 /* Check whether the keyid KID is in key id is definitely not in the
169 0 - Indeterminate: the key id is not in the cache; we don't know
170 whether the key is in the database or not. If you want a
171 definitive answer, you'll need to perform a lookup.
173 1 - There is definitely no key with this key id in the database.
174 We searched for a key with this key id previously, but we
175 didn't find it in the database. */
177 kid_not_found_p (u32 *kid)
179 struct kid_not_found_cache_bucket *k;
181 for (k = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS]; k; k = k->next)
182 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
185 log_debug ("keydb: kid_not_found_p (%08lx%08lx) => not in DB\n",
186 (ulong)kid[0], (ulong)kid[1]);
191 log_debug ("keydb: kid_not_found_p (%08lx%08lx) => indeterminate\n",
192 (ulong)kid[0], (ulong)kid[1]);
197 /* Insert the keyid KID into the kid_not_found_cache. FOUND is whether
198 the key is in the key database or not.
200 Note this function does not check whether the key id is already in
201 the cache. As such, kid_not_found_p() should be called first. */
203 kid_not_found_insert (u32 *kid)
205 struct kid_not_found_cache_bucket *k;
208 log_debug ("keydb: kid_not_found_insert (%08lx%08lx)\n",
209 (ulong)kid[0], (ulong)kid[1]);
210 k = xmalloc (sizeof *k);
213 k->next = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS];
214 kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS] = k;
215 kid_not_found_cache_count++;
219 /* Flush the kid not found cache. */
221 kid_not_found_flush (void)
223 struct kid_not_found_cache_bucket *k, *knext;
227 log_debug ("keydb: kid_not_found_flush\n");
229 if (!kid_not_found_cache_count)
232 for (i=0; i < DIM(kid_not_found_cache); i++)
234 for (k = kid_not_found_cache[i]; k; k = knext)
239 kid_not_found_cache[i] = NULL;
241 kid_not_found_cache_count = 0;
246 keyblock_cache_clear (struct keydb_handle *hd)
248 hd->keyblock_cache.state = KEYBLOCK_CACHE_EMPTY;
249 xfree (hd->keyblock_cache.sigstatus);
250 hd->keyblock_cache.sigstatus = NULL;
251 iobuf_close (hd->keyblock_cache.iobuf);
252 hd->keyblock_cache.iobuf = NULL;
253 hd->keyblock_cache.resource = -1;
254 hd->keyblock_cache.offset = -1;
258 /* Handle the creation of a keyring or a keybox if it does not yet
259 exist. Take into account that other processes might have the
260 keyring/keybox already locked. This lock check does not work if
261 the directory itself is not yet available. If IS_BOX is true the
262 filename is expected to refer to a keybox. If FORCE_CREATE is true
263 the keyring or keybox will be created.
265 Return 0 if it is okay to access the specified file. */
267 maybe_create_keyring_or_box (char *filename, int is_box, int force_create)
269 dotlock_t lockhd = NULL;
273 char *last_slash_in_filename;
274 char *bak_fname = NULL;
275 char *tmp_fname = NULL;
278 /* A quick test whether the filename already exists. */
279 if (!access (filename, F_OK))
282 /* If we don't want to create a new file at all, there is no need to
283 go any further - bail out right here. */
285 return gpg_error (GPG_ERR_ENOENT);
287 /* First of all we try to create the home directory. Note, that we
288 don't do any locking here because any sane application of gpg
289 would create the home directory by itself and not rely on gpg's
290 tricky auto-creation which is anyway only done for certain home
291 directory name pattern. */
292 last_slash_in_filename = strrchr (filename, DIRSEP_C);
295 /* Windows may either have a slash or a backslash. Take care of it. */
296 char *p = strrchr (filename, '/');
297 if (!last_slash_in_filename || p > last_slash_in_filename)
298 last_slash_in_filename = p;
300 #endif /*HAVE_W32_SYSTEM*/
301 if (!last_slash_in_filename)
302 return gpg_error (GPG_ERR_ENOENT); /* No slash at all - should
303 not happen though. */
304 save_slash = *last_slash_in_filename;
305 *last_slash_in_filename = 0;
306 if (access(filename, F_OK))
313 try_make_homedir (filename);
315 if (access (filename, F_OK))
317 rc = gpg_error_from_syserror ();
318 *last_slash_in_filename = save_slash;
322 *last_slash_in_filename = save_slash;
324 /* To avoid races with other instances of gpg trying to create or
325 update the keyring (it is removed during an update for a short
326 time), we do the next stuff in a locked state. */
327 lockhd = dotlock_create (filename, 0);
330 rc = gpg_error_from_syserror ();
331 /* A reason for this to fail is that the directory is not
332 writable. However, this whole locking stuff does not make
333 sense if this is the case. An empty non-writable directory
334 with no keyring is not really useful at all. */
336 log_info ("can't allocate lock for '%s': %s\n",
337 filename, gpg_strerror (rc));
340 return gpg_error (GPG_ERR_ENOENT); /* Won't happen. */
345 if ( dotlock_take (lockhd, -1) )
347 rc = gpg_error_from_syserror ();
348 /* This is something bad. Probably a stale lockfile. */
349 log_info ("can't lock '%s': %s\n", filename, gpg_strerror (rc));
353 /* Now the real test while we are locked. */
355 /* Gpg either uses pubring.gpg or pubring.kbx and thus different
356 * lock files. Now, when one gpg process is updating a pubring.gpg
357 * and thus holding the corresponding lock, a second gpg process may
358 * get to here at the time between the two rename operation used by
359 * the first process to update pubring.gpg. The lock taken above
360 * may not protect the second process if it tries to create a
361 * pubring.kbx file which would be protected by a different lock
364 * We can detect this case by checking that the two temporary files
365 * used by the update code exist at the same time. In that case we
366 * do not create a new file but act as if FORCE_CREATE has not been
367 * given. Obviously there is a race between our two checks but the
368 * worst thing is that we won't create a new file, which is better
369 * than to accidentally creating one. */
370 rc = keybox_tmp_names (filename, is_box, &bak_fname, &tmp_fname);
374 if (!access (filename, F_OK))
376 rc = 0; /* Okay, we may access the file now. */
379 if (!access (bak_fname, F_OK) && !access (tmp_fname, F_OK))
381 /* Very likely another process is updating a pubring.gpg and we
382 should not create a pubring.kbx. */
383 rc = gpg_error (GPG_ERR_ENOENT);
388 /* The file does not yet exist, create it now. */
389 oldmask = umask (077);
390 if (is_secured_filename (filename))
393 gpg_err_set_errno (EPERM);
396 iobuf = iobuf_create (filename, 0);
400 rc = gpg_error_from_syserror ();
402 log_error (_("error creating keybox '%s': %s\n"),
403 filename, gpg_strerror (rc));
405 log_error (_("error creating keyring '%s': %s\n"),
406 filename, gpg_strerror (rc));
411 /* Must invalidate that ugly cache */
412 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, filename);
414 /* Make sure that at least one record is in a new keybox file, so
415 that the detection magic will work the next time it is used. */
418 FILE *fp = fopen (filename, "wb");
420 rc = gpg_error_from_syserror ();
423 rc = _keybox_write_header_blob (fp, 1);
429 log_error (_("error creating keybox '%s': %s\n"),
430 filename, gpg_strerror (rc));
432 log_error (_("error creating keyring '%s': %s\n"),
433 filename, gpg_strerror (rc));
441 log_info (_("keybox '%s' created\n"), filename);
443 log_info (_("keyring '%s' created\n"), filename);
451 dotlock_release (lockhd);
452 dotlock_destroy (lockhd);
460 /* Helper for keydb_add_resource. Opens FILENAME to figure out the
463 Returns the specified file's likely type. If the file does not
464 exist, returns KEYDB_RESOURCE_TYPE_NONE and sets *R_FOUND to 0.
465 Otherwise, tries to figure out the file's type. This is either
466 KEYDB_RESOURCE_TYPE_KEYBOX, KEYDB_RESOURCE_TYPE_KEYRING or
467 KEYDB_RESOURCE_TYPE_KEYNONE. If the file is a keybox and it has
468 the OpenPGP flag set, then R_OPENPGP is also set. */
469 static KeydbResourceType
470 rt_from_file (const char *filename, int *r_found, int *r_openpgp)
473 unsigned char verbuf[4];
475 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
477 *r_found = *r_openpgp = 0;
478 fp = fopen (filename, "rb");
483 if (fread (&magic, 4, 1, fp) == 1 )
485 if (magic == 0x13579ace || magic == 0xce9a5713)
486 ; /* GDBM magic - not anymore supported. */
487 else if (fread (&verbuf, 4, 1, fp) == 1
489 && fread (&magic, 4, 1, fp) == 1
490 && !memcmp (&magic, "KBXf", 4))
492 if ((verbuf[3] & 0x02))
494 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
497 rt = KEYDB_RESOURCE_TYPE_KEYRING;
499 else /* Maybe empty: assume keyring. */
500 rt = KEYDB_RESOURCE_TYPE_KEYRING;
509 keydb_search_desc_dump (struct keydb_search_desc *desc)
511 char b[MAX_FORMATTED_FINGERPRINT_LEN + 1];
512 char fpr[2 * MAX_FINGERPRINT_LEN + 1];
516 case KEYDB_SEARCH_MODE_EXACT:
517 return xasprintf ("EXACT: '%s'", desc->u.name);
518 case KEYDB_SEARCH_MODE_SUBSTR:
519 return xasprintf ("SUBSTR: '%s'", desc->u.name);
520 case KEYDB_SEARCH_MODE_MAIL:
521 return xasprintf ("MAIL: '%s'", desc->u.name);
522 case KEYDB_SEARCH_MODE_MAILSUB:
523 return xasprintf ("MAILSUB: '%s'", desc->u.name);
524 case KEYDB_SEARCH_MODE_MAILEND:
525 return xasprintf ("MAILEND: '%s'", desc->u.name);
526 case KEYDB_SEARCH_MODE_WORDS:
527 return xasprintf ("WORDS: '%s'", desc->u.name);
528 case KEYDB_SEARCH_MODE_SHORT_KID:
529 return xasprintf ("SHORT_KID: '%s'",
530 format_keyid (desc->u.kid, KF_SHORT, b, sizeof (b)));
531 case KEYDB_SEARCH_MODE_LONG_KID:
532 return xasprintf ("LONG_KID: '%s'",
533 format_keyid (desc->u.kid, KF_LONG, b, sizeof (b)));
534 case KEYDB_SEARCH_MODE_FPR16:
535 bin2hex (desc->u.fpr, 16, fpr);
536 return xasprintf ("FPR16: '%s'",
537 format_hexfingerprint (fpr, b, sizeof (b)));
538 case KEYDB_SEARCH_MODE_FPR20:
539 bin2hex (desc->u.fpr, 20, fpr);
540 return xasprintf ("FPR20: '%s'",
541 format_hexfingerprint (fpr, b, sizeof (b)));
542 case KEYDB_SEARCH_MODE_FPR:
543 bin2hex (desc->u.fpr, 20, fpr);
544 return xasprintf ("FPR: '%s'",
545 format_hexfingerprint (fpr, b, sizeof (b)));
546 case KEYDB_SEARCH_MODE_ISSUER:
547 return xasprintf ("ISSUER: '%s'", desc->u.name);
548 case KEYDB_SEARCH_MODE_ISSUER_SN:
549 return xasprintf ("ISSUER_SN: '%*s'",
550 (int) (desc->snlen == -1
551 ? strlen (desc->sn) : desc->snlen),
553 case KEYDB_SEARCH_MODE_SN:
554 return xasprintf ("SN: '%*s'",
555 (int) (desc->snlen == -1
556 ? strlen (desc->sn) : desc->snlen),
558 case KEYDB_SEARCH_MODE_SUBJECT:
559 return xasprintf ("SUBJECT: '%s'", desc->u.name);
560 case KEYDB_SEARCH_MODE_KEYGRIP:
561 return xasprintf ("KEYGRIP: %s", desc->u.grip);
562 case KEYDB_SEARCH_MODE_FIRST:
563 return xasprintf ("FIRST");
564 case KEYDB_SEARCH_MODE_NEXT:
565 return xasprintf ("NEXT");
567 return xasprintf ("Bad search mode (%d)", desc->mode);
573 /* Register a resource (keyring or keybox). The first keyring or
574 * keybox that is added using this function is created if it does not
575 * already exist and the KEYDB_RESOURCE_FLAG_READONLY is not set.
577 * FLAGS are a combination of the KEYDB_RESOURCE_FLAG_* constants.
579 * URL must have the following form:
581 * gnupg-ring:filename = plain keyring
582 * gnupg-kbx:filename = keybox file
583 * filename = check file's type (create as a plain keyring)
585 * Note: on systems with drive letters (Windows) invalid URLs (i.e.,
586 * those with an unrecognized part before the ':' such as "c:\...")
587 * will silently be treated as bare filenames. On other systems, such
588 * URLs will cause this function to return GPG_ERR_GENERAL.
590 * If KEYDB_RESOURCE_FLAG_DEFAULT is set, the resource is a keyring
591 * and the file ends in ".gpg", then this function also checks if a
592 * file with the same name, but the extension ".kbx" exists, is a
593 * keybox and the OpenPGP flag is set. If so, this function opens
594 * that resource instead.
596 * If the file is not found, KEYDB_RESOURCE_FLAG_GPGVDEF is set and
597 * the URL ends in ".kbx", then this function will try opening the
598 * same URL, but with the extension ".gpg". If that file is a keybox
599 * with the OpenPGP flag set or it is a keyring, then we use that
602 * If the file is not found, KEYDB_RESOURCE_FLAG_DEFAULT is set, the
603 * file should be created and the file's extension is ".gpg" then we
604 * replace the extension with ".kbx".
606 * If the KEYDB_RESOURCE_FLAG_PRIMARY is set and the resource is a
607 * keyring (not a keybox), then this resource is considered the
608 * primary resource. This is used by keydb_locate_writable(). If
609 * another primary keyring is set, then that keyring is considered the
612 * If KEYDB_RESOURCE_FLAG_READONLY is set and the resource is a
613 * keyring (not a keybox), then the keyring is marked as read only and
614 * operations just as keyring_insert_keyblock will return
617 keydb_add_resource (const char *url, unsigned int flags)
619 /* Whether we have successfully registered a resource. */
620 static int any_registered;
621 /* The file named by the URL (i.e., without the prototype). */
622 const char *resname = url;
624 char *filename = NULL;
626 int read_only = !!(flags&KEYDB_RESOURCE_FLAG_READONLY);
627 int is_default = !!(flags&KEYDB_RESOURCE_FLAG_DEFAULT);
628 int is_gpgvdef = !!(flags&KEYDB_RESOURCE_FLAG_GPGVDEF);
630 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
633 /* Create the resource if it is the first registered one. */
634 create = (!read_only && !any_registered);
636 if (strlen (resname) > 11 && !strncmp( resname, "gnupg-ring:", 11) )
638 rt = KEYDB_RESOURCE_TYPE_KEYRING;
641 else if (strlen (resname) > 10 && !strncmp (resname, "gnupg-kbx:", 10) )
643 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
646 #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
647 else if (strchr (resname, ':'))
649 log_error ("invalid key resource URL '%s'\n", url );
650 err = gpg_error (GPG_ERR_GENERAL);
653 #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
655 if (*resname != DIRSEP_C
656 #ifdef HAVE_W32_SYSTEM
657 && *resname != '/' /* Fixme: does not handle drive letters. */
661 /* Do tilde expansion etc. */
662 if (strchr (resname, DIRSEP_C)
663 #ifdef HAVE_W32_SYSTEM
664 || strchr (resname, '/') /* Windows also accepts this. */
667 filename = make_filename (resname, NULL);
669 filename = make_filename (gnupg_homedir (), resname, NULL);
672 filename = xstrdup (resname);
674 /* See whether we can determine the filetype. */
675 if (rt == KEYDB_RESOURCE_TYPE_NONE)
677 int found, openpgp_flag;
682 filenamelen = strlen (filename);
683 rt = rt_from_file (filename, &found, &openpgp_flag);
686 /* The file exists and we have the resource type in RT.
688 Now let us check whether in addition to the "pubring.gpg"
689 a "pubring.kbx with openpgp keys exists. This is so that
690 GPG 2.1 will use an existing "pubring.kbx" by default iff
691 that file has been created or used by 2.1. This check is
692 needed because after creation or use of the kbx file with
693 2.1 an older version of gpg may have created a new
694 pubring.gpg for its own use. */
695 if (!pass && is_default && rt == KEYDB_RESOURCE_TYPE_KEYRING
696 && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg"))
698 strcpy (filename+filenamelen-4, ".kbx");
699 if ((rt_from_file (filename, &found, &openpgp_flag)
700 == KEYDB_RESOURCE_TYPE_KEYBOX) && found && openpgp_flag)
701 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
702 else /* Restore filename */
703 strcpy (filename+filenamelen-4, ".gpg");
706 else if (!pass && is_gpgvdef
707 && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".kbx"))
709 /* Not found but gpgv's default "trustedkeys.kbx" file has
710 been requested. We did not found it so now check whether
711 a "trustedkeys.gpg" file exists and use that instead. */
712 KeydbResourceType rttmp;
714 strcpy (filename+filenamelen-4, ".gpg");
715 rttmp = rt_from_file (filename, &found, &openpgp_flag);
717 && ((rttmp == KEYDB_RESOURCE_TYPE_KEYBOX && openpgp_flag)
718 || (rttmp == KEYDB_RESOURCE_TYPE_KEYRING)))
720 else /* Restore filename */
721 strcpy (filename+filenamelen-4, ".kbx");
724 && is_default && create
725 && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg"))
727 /* The file does not exist, the default resource has been
728 requested, the file shall be created, and the file has a
729 ".gpg" suffix. Change the suffix to ".kbx" and try once
730 more. This way we achieve that we open an existing
731 ".gpg" keyring, but create a new keybox file with an
733 strcpy (filename+filenamelen-4, ".kbx");
737 else /* No file yet: create keybox. */
738 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
743 case KEYDB_RESOURCE_TYPE_NONE:
744 log_error ("unknown type of key resource '%s'\n", url );
745 err = gpg_error (GPG_ERR_GENERAL);
748 case KEYDB_RESOURCE_TYPE_KEYRING:
749 err = maybe_create_keyring_or_box (filename, 0, create);
753 if (keyring_register_filename (filename, read_only, &token))
755 if (used_resources >= MAX_KEYDB_RESOURCES)
756 err = gpg_error (GPG_ERR_RESOURCE_LIMIT);
759 if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
760 primary_keydb = token;
761 all_resources[used_resources].type = rt;
762 all_resources[used_resources].u.kr = NULL; /* Not used here */
763 all_resources[used_resources].token = token;
769 /* This keyring was already registered, so ignore it.
770 However, we can still mark it as primary even if it was
771 already registered. */
772 if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
773 primary_keydb = token;
777 case KEYDB_RESOURCE_TYPE_KEYBOX:
779 err = maybe_create_keyring_or_box (filename, 1, create);
783 err = keybox_register_file (filename, 0, &token);
786 if (used_resources >= MAX_KEYDB_RESOURCES)
787 err = gpg_error (GPG_ERR_RESOURCE_LIMIT);
790 if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
791 primary_keydb = token;
792 all_resources[used_resources].type = rt;
793 all_resources[used_resources].u.kb = NULL; /* Not used here */
794 all_resources[used_resources].token = token;
796 /* FIXME: Do a compress run if needed and no other
797 user is currently using the keybox. */
802 else if (gpg_err_code (err) == GPG_ERR_EEXIST)
804 /* Already registered. We will mark it as the primary key
806 if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
807 primary_keydb = token;
813 log_error ("resource type of '%s' not supported\n", url);
814 err = gpg_error (GPG_ERR_GENERAL);
818 /* fixme: check directory permissions and print a warning */
822 log_error (_("keyblock resource '%s': %s\n"), filename, gpg_strerror (err));
831 keydb_dump_stats (void)
833 if (kid_not_found_cache_count)
834 log_info ("keydb: kid_not_found_cache: total: %u\n",
835 kid_not_found_cache_count);
839 /* Create a new database handle. A database handle is similar to a
840 file handle: it contains a local file position. This is used when
841 searching: subsequent searches resume where the previous search
842 left off. To rewind the position, use keydb_search_reset(). This
843 function returns NULL on error, sets ERRNO, and prints an error
854 log_clock ("keydb_new");
856 hd = xtrycalloc (1, sizeof *hd);
860 hd->saved_found = -1;
863 log_assert (used_resources <= MAX_KEYDB_RESOURCES);
864 for (i=j=0; ! die && i < used_resources; i++)
866 switch (all_resources[i].type)
868 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
870 case KEYDB_RESOURCE_TYPE_KEYRING:
871 hd->active[j].type = all_resources[i].type;
872 hd->active[j].token = all_resources[i].token;
873 hd->active[j].u.kr = keyring_new (all_resources[i].token);
874 if (!hd->active[j].u.kr)
881 case KEYDB_RESOURCE_TYPE_KEYBOX:
882 hd->active[j].type = all_resources[i].type;
883 hd->active[j].token = all_resources[i].token;
884 hd->active[j].u.kb = keybox_new_openpgp (all_resources[i].token, 0);
885 if (!hd->active[j].u.kb)
901 gpg_err_set_errno (reterrno);
907 log_error (_("error opening key DB: %s\n"),
908 gpg_strerror (gpg_error_from_syserror()));
915 keydb_release (KEYDB_HANDLE hd)
921 log_assert (active_handles > 0);
925 for (i=0; i < hd->used; i++)
927 switch (hd->active[i].type)
929 case KEYDB_RESOURCE_TYPE_NONE:
931 case KEYDB_RESOURCE_TYPE_KEYRING:
932 keyring_release (hd->active[i].u.kr);
934 case KEYDB_RESOURCE_TYPE_KEYBOX:
935 keybox_release (hd->active[i].u.kb);
940 keyblock_cache_clear (hd);
945 /* Set a flag on the handle to suppress use of cached results. This
946 * is required for updating a keyring and for key listings. Fixme:
947 * Using a new parameter for keydb_new might be a better solution. */
949 keydb_disable_caching (KEYDB_HANDLE hd)
956 /* Return the file name of the resource in which the current search
957 * result was found or, if there is no search result, the filename of
958 * the current resource (i.e., the resource that the file position
959 * points to). Note: the filename is not necessarily the URL used to
962 * This function only returns NULL if no handle is specified, in all
963 * other error cases an empty string is returned. */
965 keydb_get_resource_name (KEYDB_HANDLE hd)
968 const char *s = NULL;
973 if ( hd->found >= 0 && hd->found < hd->used)
975 else if ( hd->current >= 0 && hd->current < hd->used)
980 switch (hd->active[idx].type)
982 case KEYDB_RESOURCE_TYPE_NONE:
985 case KEYDB_RESOURCE_TYPE_KEYRING:
986 s = keyring_get_resource_name (hd->active[idx].u.kr);
988 case KEYDB_RESOURCE_TYPE_KEYBOX:
989 s = keybox_get_resource_name (hd->active[idx].u.kb);
999 lock_all (KEYDB_HANDLE hd)
1003 /* Fixme: This locking scheme may lead to a deadlock if the resources
1004 are not added in the same order by all processes. We are
1005 currently only allowing one resource so it is not a problem.
1006 [Oops: Who claimed the latter]
1008 To fix this we need to use a lock file to protect lock_all. */
1010 for (i=0; !rc && i < hd->used; i++)
1012 switch (hd->active[i].type)
1014 case KEYDB_RESOURCE_TYPE_NONE:
1016 case KEYDB_RESOURCE_TYPE_KEYRING:
1017 rc = keyring_lock (hd->active[i].u.kr, 1);
1019 case KEYDB_RESOURCE_TYPE_KEYBOX:
1020 rc = keybox_lock (hd->active[i].u.kb, 1);
1027 /* Revert the already taken locks. */
1028 for (i--; i >= 0; i--)
1030 switch (hd->active[i].type)
1032 case KEYDB_RESOURCE_TYPE_NONE:
1034 case KEYDB_RESOURCE_TYPE_KEYRING:
1035 keyring_lock (hd->active[i].u.kr, 0);
1037 case KEYDB_RESOURCE_TYPE_KEYBOX:
1038 keybox_lock (hd->active[i].u.kb, 0);
1051 unlock_all (KEYDB_HANDLE hd)
1058 for (i=hd->used-1; i >= 0; i--)
1060 switch (hd->active[i].type)
1062 case KEYDB_RESOURCE_TYPE_NONE:
1064 case KEYDB_RESOURCE_TYPE_KEYRING:
1065 keyring_lock (hd->active[i].u.kr, 0);
1067 case KEYDB_RESOURCE_TYPE_KEYBOX:
1068 keybox_lock (hd->active[i].u.kb, 0);
1077 /* Save the last found state and invalidate the current selection
1078 * (i.e., the entry selected by keydb_search() is invalidated and
1079 * something like keydb_get_keyblock() will return an error). This
1080 * does not change the file position. This makes it possible to do
1083 * keydb_search (hd, ...); // Result 1.
1084 * keydb_push_found_state (hd);
1085 * keydb_search_reset (hd);
1086 * keydb_search (hd, ...); // Result 2.
1087 * keydb_pop_found_state (hd);
1088 * keydb_get_keyblock (hd, ...); // -> Result 1.
1090 * Note: it is only possible to save a single save state at a time.
1091 * In other words, the the save stack only has room for a single
1092 * instance of the state. */
1094 keydb_push_found_state (KEYDB_HANDLE hd)
1099 if (hd->found < 0 || hd->found >= hd->used)
1101 hd->saved_found = -1;
1105 switch (hd->active[hd->found].type)
1107 case KEYDB_RESOURCE_TYPE_NONE:
1109 case KEYDB_RESOURCE_TYPE_KEYRING:
1110 keyring_push_found_state (hd->active[hd->found].u.kr);
1112 case KEYDB_RESOURCE_TYPE_KEYBOX:
1113 keybox_push_found_state (hd->active[hd->found].u.kb);
1117 hd->saved_found = hd->found;
1122 /* Restore the previous save state. If the saved state is NULL or
1123 invalid, this is a NOP. */
1125 keydb_pop_found_state (KEYDB_HANDLE hd)
1130 hd->found = hd->saved_found;
1131 hd->saved_found = -1;
1132 if (hd->found < 0 || hd->found >= hd->used)
1135 switch (hd->active[hd->found].type)
1137 case KEYDB_RESOURCE_TYPE_NONE:
1139 case KEYDB_RESOURCE_TYPE_KEYRING:
1140 keyring_pop_found_state (hd->active[hd->found].u.kr);
1142 case KEYDB_RESOURCE_TYPE_KEYBOX:
1143 keybox_pop_found_state (hd->active[hd->found].u.kb);
1151 parse_keyblock_image (iobuf_t iobuf, int pk_no, int uid_no,
1152 const u32 *sigstatus, kbnode_t *r_keyblock)
1156 kbnode_t keyblock = NULL;
1157 kbnode_t node, *tail;
1158 int in_cert, save_mode;
1160 int pk_count, uid_count;
1164 pkt = xtrymalloc (sizeof *pkt);
1166 return gpg_error_from_syserror ();
1168 save_mode = set_packet_list_mode (0);
1172 pk_count = uid_count = 0;
1173 while ((err = parse_packet (iobuf, pkt)) != -1)
1175 if (gpg_err_code (err) == GPG_ERR_UNKNOWN_PACKET)
1183 log_error ("parse_keyblock_image: read error: %s\n",
1184 gpg_strerror (err));
1185 err = gpg_error (GPG_ERR_INV_KEYRING);
1189 /* Filter allowed packets. */
1190 switch (pkt->pkttype)
1192 case PKT_PUBLIC_KEY:
1193 case PKT_PUBLIC_SUBKEY:
1194 case PKT_SECRET_KEY:
1195 case PKT_SECRET_SUBKEY:
1199 break; /* Allowed per RFC. */
1202 /* Note that can't allow ring trust packets here and some of
1203 the other GPG specific packets don't make sense either. */
1204 log_error ("skipped packet of type %d in keybox\n",
1211 /* Other sanity checks. */
1212 if (!in_cert && pkt->pkttype != PKT_PUBLIC_KEY)
1214 log_error ("parse_keyblock_image: first packet in a keybox blob "
1215 "is not a public key packet\n");
1216 err = gpg_error (GPG_ERR_INV_KEYRING);
1219 if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
1220 || pkt->pkttype == PKT_SECRET_KEY))
1222 log_error ("parse_keyblock_image: "
1223 "multiple keyblocks in a keybox blob\n");
1224 err = gpg_error (GPG_ERR_INV_KEYRING);
1229 if (pkt->pkttype == PKT_SIGNATURE && sigstatus)
1231 PKT_signature *sig = pkt->pkt.signature;
1234 if (n_sigs > sigstatus[0])
1236 log_error ("parse_keyblock_image: "
1237 "more signatures than found in the meta data\n");
1238 err = gpg_error (GPG_ERR_INV_KEYRING);
1242 if (sigstatus[n_sigs])
1244 sig->flags.checked = 1;
1245 if (sigstatus[n_sigs] == 1 )
1247 else if (sigstatus[n_sigs] == 2 )
1248 ; /* bad signature */
1249 else if (sigstatus[n_sigs] < 0x10000000)
1253 sig->flags.valid = 1;
1254 /* Fixme: Shall we set the expired flag here? */
1259 node = new_kbnode (pkt);
1261 switch (pkt->pkttype)
1263 case PKT_PUBLIC_KEY:
1264 case PKT_PUBLIC_SUBKEY:
1265 case PKT_SECRET_KEY:
1266 case PKT_SECRET_SUBKEY:
1267 if (++pk_count == pk_no)
1272 if (++uid_count == uid_no)
1285 pkt = xtrymalloc (sizeof *pkt);
1288 err = gpg_error_from_syserror ();
1293 set_packet_list_mode (save_mode);
1295 if (err == -1 && keyblock)
1296 err = 0; /* Got the entire keyblock. */
1298 if (!err && sigstatus && n_sigs != sigstatus[0])
1300 log_error ("parse_keyblock_image: signature count does not match\n");
1301 err = gpg_error (GPG_ERR_INV_KEYRING);
1305 release_kbnode (keyblock);
1307 *r_keyblock = keyblock;
1314 /* Return the keyblock last found by keydb_search() in *RET_KB.
1316 * On success, the function returns 0 and the caller must free *RET_KB
1317 * using release_kbnode(). Otherwise, the function returns an error
1320 * The returned keyblock has the kbnode flag bit 0 set for the node
1321 * with the public key used to locate the keyblock or flag bit 1 set
1322 * for the user ID node. */
1324 keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
1326 gpg_error_t err = 0;
1331 return gpg_error (GPG_ERR_INV_ARG);
1334 log_clock ("keydb_get_keybock enter");
1336 if (hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED)
1338 err = iobuf_seek (hd->keyblock_cache.iobuf, 0);
1341 log_error ("keydb_get_keyblock: failed to rewind iobuf for cache\n");
1342 keyblock_cache_clear (hd);
1346 err = parse_keyblock_image (hd->keyblock_cache.iobuf,
1347 hd->keyblock_cache.pk_no,
1348 hd->keyblock_cache.uid_no,
1349 hd->keyblock_cache.sigstatus,
1352 keyblock_cache_clear (hd);
1354 log_clock (err? "keydb_get_keyblock leave (cached, failed)"
1355 : "keydb_get_keyblock leave (cached)");
1360 if (hd->found < 0 || hd->found >= hd->used)
1361 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1363 switch (hd->active[hd->found].type)
1365 case KEYDB_RESOURCE_TYPE_NONE:
1366 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1368 case KEYDB_RESOURCE_TYPE_KEYRING:
1369 err = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
1371 case KEYDB_RESOURCE_TYPE_KEYBOX:
1377 err = keybox_get_keyblock (hd->active[hd->found].u.kb,
1378 &iobuf, &pk_no, &uid_no, &sigstatus);
1381 err = parse_keyblock_image (iobuf, pk_no, uid_no, sigstatus,
1383 if (!err && hd->keyblock_cache.state == KEYBLOCK_CACHE_PREPARED)
1385 hd->keyblock_cache.state = KEYBLOCK_CACHE_FILLED;
1386 hd->keyblock_cache.sigstatus = sigstatus;
1387 hd->keyblock_cache.iobuf = iobuf;
1388 hd->keyblock_cache.pk_no = pk_no;
1389 hd->keyblock_cache.uid_no = uid_no;
1394 iobuf_close (iobuf);
1401 if (hd->keyblock_cache.state != KEYBLOCK_CACHE_FILLED)
1402 keyblock_cache_clear (hd);
1405 log_clock (err? "keydb_get_keyblock leave (failed)"
1406 : "keydb_get_keyblock leave");
1411 /* Build a keyblock image from KEYBLOCK. Returns 0 on success and
1412 only then stores a new iobuf object at R_IOBUF and a signature
1413 status vecotor at R_SIGSTATUS. */
1415 build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf, u32 **r_sigstatus)
1419 kbnode_t kbctx, node;
1425 *r_sigstatus = NULL;
1427 /* Allocate a vector for the signature cache. This is an array of
1428 u32 values with the first value giving the number of elements to
1429 follow and each element descriping the cache status of the
1433 for (kbctx=NULL, n_sigs=0; (node = walk_kbnode (keyblock, &kbctx, 0));)
1434 if (node->pkt->pkttype == PKT_SIGNATURE)
1436 sigstatus = xtrycalloc (1+n_sigs, sizeof *sigstatus);
1438 return gpg_error_from_syserror ();
1443 iobuf = iobuf_temp ();
1444 for (kbctx = NULL, n_sigs = 0; (node = walk_kbnode (keyblock, &kbctx, 0));)
1446 /* Make sure to use only packets valid on a keyblock. */
1447 switch (node->pkt->pkttype)
1449 case PKT_PUBLIC_KEY:
1450 case PKT_PUBLIC_SUBKEY:
1454 /* Note that we don't want the ring trust packets. They are
1461 err = build_packet (iobuf, node->pkt);
1464 iobuf_close (iobuf);
1468 /* Build signature status vector. */
1469 if (node->pkt->pkttype == PKT_SIGNATURE)
1471 PKT_signature *sig = node->pkt->pkt.signature;
1474 /* Fixme: Detect the "missing key" status. */
1475 if (sig->flags.checked && sigstatus)
1477 if (sig->flags.valid)
1479 if (!sig->expiredate)
1480 sigstatus[n_sigs] = 0xffffffff;
1481 else if (sig->expiredate < 0x1000000)
1482 sigstatus[n_sigs] = 0x10000000;
1484 sigstatus[n_sigs] = sig->expiredate;
1487 sigstatus[n_sigs] = 0x00000002; /* Bad signature. */
1492 sigstatus[0] = n_sigs;
1496 *r_sigstatus = sigstatus;
1501 /* Update the keyblock KB (i.e., extract the fingerprint and find the
1502 * corresponding keyblock in the keyring).
1504 * This doesn't do anything if --dry-run was specified.
1506 * Returns 0 on success. Otherwise, it returns an error code. Note:
1507 * if there isn't a keyblock in the keyring corresponding to KB, then
1508 * this function returns GPG_ERR_VALUE_NOT_FOUND.
1510 * This function selects the matching record and modifies the current
1511 * file position to point to the record just after the selected entry.
1512 * Thus, if you do a subsequent search using HD, you should first do a
1513 * keydb_search_reset. Further, if the selected record is important,
1514 * you should use keydb_push_found_state and keydb_pop_found_state to
1515 * save and restore it. */
1517 keydb_update_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
1521 KEYDB_SEARCH_DESC desc;
1525 log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
1526 pk = kb->pkt->pkt.public_key;
1529 return gpg_error (GPG_ERR_INV_ARG);
1531 kid_not_found_flush ();
1532 keyblock_cache_clear (hd);
1537 err = lock_all (hd);
1541 memset (&desc, 0, sizeof (desc));
1542 fingerprint_from_pk (pk, desc.u.fpr, &len);
1544 desc.mode = KEYDB_SEARCH_MODE_FPR20;
1546 log_bug ("%s: Unsupported key length: %zu\n", __func__, len);
1548 keydb_search_reset (hd);
1549 err = keydb_search (hd, &desc, 1, NULL);
1551 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1552 log_assert (hd->found >= 0 && hd->found < hd->used);
1554 switch (hd->active[hd->found].type)
1556 case KEYDB_RESOURCE_TYPE_NONE:
1557 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1559 case KEYDB_RESOURCE_TYPE_KEYRING:
1560 err = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
1562 case KEYDB_RESOURCE_TYPE_KEYBOX:
1566 err = build_keyblock_image (kb, &iobuf, NULL);
1569 err = keybox_update_keyblock (hd->active[hd->found].u.kb,
1570 iobuf_get_temp_buffer (iobuf),
1571 iobuf_get_temp_length (iobuf));
1572 iobuf_close (iobuf);
1583 /* Insert a keyblock into one of the underlying keyrings or keyboxes.
1585 * Be default, the keyring / keybox from which the last search result
1586 * came is used. If there was no previous search result (or
1587 * keydb_search_reset was called), then the keyring / keybox where the
1588 * next search would start is used (i.e., the current file position).
1590 * Note: this doesn't do anything if --dry-run was specified.
1592 * Returns 0 on success. Otherwise, it returns an error code. */
1594 keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
1600 return gpg_error (GPG_ERR_INV_ARG);
1602 kid_not_found_flush ();
1603 keyblock_cache_clear (hd);
1608 if (hd->found >= 0 && hd->found < hd->used)
1610 else if (hd->current >= 0 && hd->current < hd->used)
1613 return gpg_error (GPG_ERR_GENERAL);
1615 err = lock_all (hd);
1619 switch (hd->active[idx].type)
1621 case KEYDB_RESOURCE_TYPE_NONE:
1622 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1624 case KEYDB_RESOURCE_TYPE_KEYRING:
1625 err = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
1627 case KEYDB_RESOURCE_TYPE_KEYBOX:
1628 { /* We need to turn our kbnode_t list of packets into a proper
1629 keyblock first. This is required by the OpenPGP key parser
1630 included in the keybox code. Eventually we can change this
1631 kludge to have the caller pass the image. */
1635 err = build_keyblock_image (kb, &iobuf, &sigstatus);
1638 err = keybox_insert_keyblock (hd->active[idx].u.kb,
1639 iobuf_get_temp_buffer (iobuf),
1640 iobuf_get_temp_length (iobuf),
1643 iobuf_close (iobuf);
1654 /* Delete the currently selected keyblock. If you haven't done a
1655 * search yet on this database handle (or called keydb_search_reset),
1656 * then this will return an error.
1658 * Returns 0 on success or an error code, if an error occurs. */
1660 keydb_delete_keyblock (KEYDB_HANDLE hd)
1665 return gpg_error (GPG_ERR_INV_ARG);
1667 kid_not_found_flush ();
1668 keyblock_cache_clear (hd);
1670 if (hd->found < 0 || hd->found >= hd->used)
1671 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1680 switch (hd->active[hd->found].type)
1682 case KEYDB_RESOURCE_TYPE_NONE:
1683 rc = gpg_error (GPG_ERR_GENERAL);
1685 case KEYDB_RESOURCE_TYPE_KEYRING:
1686 rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
1688 case KEYDB_RESOURCE_TYPE_KEYBOX:
1689 rc = keybox_delete (hd->active[hd->found].u.kb);
1699 /* A database may consists of multiple keyrings / key boxes. This
1700 * sets the "file position" to the start of the first keyring / key
1701 * box that is writable (i.e., doesn't have the read-only flag set).
1703 * This first tries the primary keyring (the last keyring (not
1704 * keybox!) added using keydb_add_resource() and with
1705 * KEYDB_RESOURCE_FLAG_PRIMARY set). If that is not writable, then it
1706 * tries the keyrings / keyboxes in the order in which they were
1709 keydb_locate_writable (KEYDB_HANDLE hd)
1714 return GPG_ERR_INV_ARG;
1716 rc = keydb_search_reset (hd); /* this does reset hd->current */
1720 /* If we have a primary set, try that one first */
1723 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
1725 if(hd->active[hd->current].token == primary_keydb)
1727 if(keyring_is_writable (hd->active[hd->current].token))
1734 rc = keydb_search_reset (hd); /* this does reset hd->current */
1739 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
1741 switch (hd->active[hd->current].type)
1743 case KEYDB_RESOURCE_TYPE_NONE:
1746 case KEYDB_RESOURCE_TYPE_KEYRING:
1747 if (keyring_is_writable (hd->active[hd->current].token))
1748 return 0; /* found (hd->current is set to it) */
1750 case KEYDB_RESOURCE_TYPE_KEYBOX:
1751 if (keybox_is_writable (hd->active[hd->current].token))
1752 return 0; /* found (hd->current is set to it) */
1757 return gpg_error (GPG_ERR_NOT_FOUND);
1761 /* Rebuild the on-disk caches of all key resources. */
1763 keydb_rebuild_caches (int noisy)
1767 for (i=0; i < used_resources; i++)
1769 if (!keyring_is_writable (all_resources[i].token))
1771 switch (all_resources[i].type)
1773 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
1775 case KEYDB_RESOURCE_TYPE_KEYRING:
1776 rc = keyring_rebuild_cache (all_resources[i].token,noisy);
1778 log_error (_("failed to rebuild keyring cache: %s\n"),
1781 case KEYDB_RESOURCE_TYPE_KEYBOX:
1789 /* Return the number of skipped blocks (because they were to large to
1790 read from a keybox) since the last search reset. */
1792 keydb_get_skipped_counter (KEYDB_HANDLE hd)
1794 return hd ? hd->skipped_long_blobs : 0;
1798 /* Clears the current search result and resets the handle's position
1799 * so that the next search starts at the beginning of the database
1800 * (the start of the first resource).
1802 * Returns 0 on success and an error code if an error occurred.
1803 * (Currently, this function always returns 0 if HD is valid.) */
1805 keydb_search_reset (KEYDB_HANDLE hd)
1811 return gpg_error (GPG_ERR_INV_ARG);
1813 keyblock_cache_clear (hd);
1816 log_clock ("keydb_search_reset");
1819 log_debug ("keydb_search: reset (hd=%p)", hd);
1821 hd->skipped_long_blobs = 0;
1824 /* Now reset all resources. */
1825 for (i=0; !rc && i < hd->used; i++)
1827 switch (hd->active[i].type)
1829 case KEYDB_RESOURCE_TYPE_NONE:
1831 case KEYDB_RESOURCE_TYPE_KEYRING:
1832 rc = keyring_search_reset (hd->active[i].u.kr);
1834 case KEYDB_RESOURCE_TYPE_KEYBOX:
1835 rc = keybox_search_reset (hd->active[i].u.kb);
1844 /* Search the database for keys matching the search description. If
1845 * the DB contains any legacy keys, these are silently ignored.
1847 * DESC is an array of search terms with NDESC entries. The search
1848 * terms are or'd together. That is, the next entry in the DB that
1849 * matches any of the descriptions will be returned.
1851 * Note: this function resumes searching where the last search left
1852 * off (i.e., at the current file position). If you want to search
1853 * from the start of the database, then you need to first call
1854 * keydb_search_reset().
1856 * If no key matches the search description, returns
1857 * GPG_ERR_NOT_FOUND. If there was a match, returns 0. If an error
1858 * occurred, returns an error code.
1860 * The returned key is considered to be selected and the raw data can,
1861 * for instance, be returned by calling keydb_get_keyblock(). */
1863 keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
1864 size_t ndesc, size_t *descindex)
1868 int was_reset = hd->is_reset;
1869 /* If an entry is already in the cache, then don't add it again. */
1870 int already_in_cache = 0;
1873 *descindex = 0; /* Make sure it is always set on return. */
1876 return gpg_error (GPG_ERR_INV_ARG);
1879 log_clock ("keydb_search enter");
1883 log_debug ("%s: %zd search descriptions:\n", __func__, ndesc);
1884 for (i = 0; i < ndesc; i ++)
1886 char *t = keydb_search_desc_dump (&desc[i]);
1887 log_debug ("%s %d: %s\n", __func__, i, t);
1893 if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID
1894 && (already_in_cache = kid_not_found_p (desc[0].u.kid)) == 1 )
1897 log_clock ("keydb_search leave (not found, cached)");
1898 return gpg_error (GPG_ERR_NOT_FOUND);
1901 /* NB: If one of the exact search modes below is used in a loop to
1902 walk over all keys (with the same fingerprint) the caching must
1903 have been disabled for the handle. */
1906 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
1907 || desc[0].mode == KEYDB_SEARCH_MODE_FPR)
1908 && hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED
1909 && !memcmp (hd->keyblock_cache.fpr, desc[0].u.fpr, 20)
1910 /* Make sure the current file position occurs before the cached
1911 result to avoid an infinite loop. */
1912 && (hd->current < hd->keyblock_cache.resource
1913 || (hd->current == hd->keyblock_cache.resource
1914 && (keybox_offset (hd->active[hd->current].u.kb)
1915 <= hd->keyblock_cache.offset))))
1917 /* (DESCINDEX is already set). */
1919 log_clock ("keydb_search leave (cached)");
1921 hd->current = hd->keyblock_cache.resource;
1922 /* HD->KEYBLOCK_CACHE.OFFSET is the last byte in the record.
1923 Seek just beyond that. */
1924 keybox_seek (hd->active[hd->current].u.kb,
1925 hd->keyblock_cache.offset + 1);
1930 while ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1931 && hd->current >= 0 && hd->current < hd->used)
1934 log_debug ("%s: searching %s (resource %d of %d)\n",
1936 hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING
1938 : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX
1939 ? "keybox" : "unknown type"),
1940 hd->current, hd->used);
1942 switch (hd->active[hd->current].type)
1944 case KEYDB_RESOURCE_TYPE_NONE:
1945 BUG(); /* we should never see it here */
1947 case KEYDB_RESOURCE_TYPE_KEYRING:
1948 rc = keyring_search (hd->active[hd->current].u.kr, desc,
1949 ndesc, descindex, 1);
1951 case KEYDB_RESOURCE_TYPE_KEYBOX:
1953 rc = keybox_search (hd->active[hd->current].u.kb, desc,
1954 ndesc, KEYBOX_BLOBTYPE_PGP,
1955 descindex, &hd->skipped_long_blobs);
1956 while (rc == GPG_ERR_LEGACY_KEY);
1961 log_debug ("%s: searched %s (resource %d of %d) => %s\n",
1963 hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING
1965 : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX
1966 ? "keybox" : "unknown type"),
1967 hd->current, hd->used,
1968 rc == -1 ? "EOF" : gpg_strerror (rc));
1970 if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1972 /* EOF -> switch to next resource */
1976 hd->found = hd->current;
1980 rc = ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1981 ? gpg_error (GPG_ERR_NOT_FOUND)
1984 keyblock_cache_clear (hd);
1987 && ndesc == 1 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
1988 || desc[0].mode == KEYDB_SEARCH_MODE_FPR)
1989 && hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX)
1991 hd->keyblock_cache.state = KEYBLOCK_CACHE_PREPARED;
1992 hd->keyblock_cache.resource = hd->current;
1993 /* The current offset is at the start of the next record. Since
1994 a record is at least 1 byte, we just use offset - 1, which is
1995 within the record. */
1996 hd->keyblock_cache.offset
1997 = keybox_offset (hd->active[hd->current].u.kb) - 1;
1998 memcpy (hd->keyblock_cache.fpr, desc[0].u.fpr, 20);
2001 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND
2002 && ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID && was_reset
2003 && !already_in_cache)
2004 kid_not_found_insert (desc[0].u.kid);
2007 log_clock (rc? "keydb_search leave (not found)"
2008 : "keydb_search leave (found)");
2013 /* Return the first non-legacy key in the database.
2015 * If you want the very first key in the database, you can directly
2016 * call keydb_search with the search description
2017 * KEYDB_SEARCH_MODE_FIRST. */
2019 keydb_search_first (KEYDB_HANDLE hd)
2022 KEYDB_SEARCH_DESC desc;
2024 err = keydb_search_reset (hd);
2028 memset (&desc, 0, sizeof desc);
2029 desc.mode = KEYDB_SEARCH_MODE_FIRST;
2030 return keydb_search (hd, &desc, 1, NULL);
2034 /* Return the next key (not the next matching key!).
2036 * Unlike calling keydb_search with KEYDB_SEARCH_MODE_NEXT, this
2037 * function silently skips legacy keys. */
2039 keydb_search_next (KEYDB_HANDLE hd)
2041 KEYDB_SEARCH_DESC desc;
2043 memset (&desc, 0, sizeof desc);
2044 desc.mode = KEYDB_SEARCH_MODE_NEXT;
2045 return keydb_search (hd, &desc, 1, NULL);
2049 /* This is a convenience function for searching for keys with a long
2052 * Note: this function resumes searching where the last search left
2053 * off. If you want to search the whole database, then you need to
2054 * first call keydb_search_reset(). */
2056 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
2058 KEYDB_SEARCH_DESC desc;
2060 memset (&desc, 0, sizeof desc);
2061 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
2062 desc.u.kid[0] = kid[0];
2063 desc.u.kid[1] = kid[1];
2064 return keydb_search (hd, &desc, 1, NULL);
2068 /* This is a convenience function for searching for keys with a long
2069 * (20 byte) fingerprint.
2071 * Note: this function resumes searching where the last search left
2072 * off. If you want to search the whole database, then you need to
2073 * first call keydb_search_reset(). */
2075 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
2077 KEYDB_SEARCH_DESC desc;
2079 memset (&desc, 0, sizeof desc);
2080 desc.mode = KEYDB_SEARCH_MODE_FPR;
2081 memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
2082 return keydb_search (hd, &desc, 1, NULL);