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;
67 /* Whether we have successfully registered any resource. */
68 static int any_registered;
70 /* This is a simple cache used to return the last result of a
71 successful fingerprint search. This works only for keybox resources
72 because (due to lack of a copy_keyblock function) we need to store
73 an image of the keyblock which is fortunately instantly available
75 enum keyblock_cache_states {
77 KEYBLOCK_CACHE_PREPARED,
81 struct keyblock_cache {
82 enum keyblock_cache_states state;
83 byte fpr[MAX_FINGERPRINT_LEN];
84 iobuf_t iobuf; /* Image of the keyblock. */
88 /* Offset of the record in the keybox. */
96 /* When we locked all of the resources in ACTIVE (using keyring_lock
97 / keybox_lock, as appropriate). */
100 /* The index into ACTIVE of the resources in which the last search
101 result was found. Initially -1. */
104 /* Initially -1 (invalid). This is used to save a search result and
105 later restore it as the selected result. */
108 /* The number of skipped long blobs since the last search
109 (keydb_search_reset). */
110 unsigned long skipped_long_blobs;
112 /* If set, this disables the use of the keyblock cache. */
115 /* Whether the next search will be from the beginning of the
116 database (and thus consider all records). */
119 /* The "file position." In our case, this is index of the current
120 resource in ACTIVE. */
123 /* The number of resources in ACTIVE. */
126 /* Cache of the last found and parsed key block (only used for
127 keyboxes, not keyrings). */
128 struct keyblock_cache keyblock_cache;
130 /* Copy of ALL_RESOURCES when keydb_new is called. */
131 struct resource_item active[MAX_KEYDB_RESOURCES];
134 /* Looking up keys is expensive. To hide the cost, we cache whether
135 keys exist in the key database. Then, if we know a key does not
136 exist, we don't have to spend time looking it up. This
137 particularly helps the --list-sigs and --check-sigs commands.
139 The cache stores the results in a hash using separate chaining.
140 Concretely: we use the LSB of the keyid to index the hash table and
141 each bucket consists of a linked list of entries. An entry
142 consists of the 64-bit key id. If a key id is not in the cache,
143 then we don't know whether it is in the DB or not.
145 To simplify the cache consistency protocol, we simply flush the
146 whole cache whenever a key is inserted or updated. */
148 #define KID_NOT_FOUND_CACHE_BUCKETS 256
149 static struct kid_not_found_cache_bucket *
150 kid_not_found_cache[KID_NOT_FOUND_CACHE_BUCKETS];
152 /* The total number of entries in the hash table. */
153 static unsigned int kid_not_found_cache_count;
155 struct kid_not_found_cache_bucket
157 struct kid_not_found_cache_bucket *next;
162 static int lock_all (KEYDB_HANDLE hd);
163 static void unlock_all (KEYDB_HANDLE hd);
166 /* Check whether the keyid KID is in key id is definitely not in the
171 0 - Indeterminate: the key id is not in the cache; we don't know
172 whether the key is in the database or not. If you want a
173 definitive answer, you'll need to perform a lookup.
175 1 - There is definitely no key with this key id in the database.
176 We searched for a key with this key id previously, but we
177 didn't find it in the database. */
179 kid_not_found_p (u32 *kid)
181 struct kid_not_found_cache_bucket *k;
183 for (k = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS]; k; k = k->next)
184 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
187 log_debug ("keydb: kid_not_found_p (%08lx%08lx) => not in DB\n",
188 (ulong)kid[0], (ulong)kid[1]);
193 log_debug ("keydb: kid_not_found_p (%08lx%08lx) => indeterminate\n",
194 (ulong)kid[0], (ulong)kid[1]);
199 /* Insert the keyid KID into the kid_not_found_cache. FOUND is whether
200 the key is in the key database or not.
202 Note this function does not check whether the key id is already in
203 the cache. As such, kid_not_found_p() should be called first. */
205 kid_not_found_insert (u32 *kid)
207 struct kid_not_found_cache_bucket *k;
210 log_debug ("keydb: kid_not_found_insert (%08lx%08lx)\n",
211 (ulong)kid[0], (ulong)kid[1]);
212 k = xmalloc (sizeof *k);
215 k->next = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS];
216 kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS] = k;
217 kid_not_found_cache_count++;
221 /* Flush the kid not found cache. */
223 kid_not_found_flush (void)
225 struct kid_not_found_cache_bucket *k, *knext;
229 log_debug ("keydb: kid_not_found_flush\n");
231 if (!kid_not_found_cache_count)
234 for (i=0; i < DIM(kid_not_found_cache); i++)
236 for (k = kid_not_found_cache[i]; k; k = knext)
241 kid_not_found_cache[i] = NULL;
243 kid_not_found_cache_count = 0;
248 keyblock_cache_clear (struct keydb_handle *hd)
250 hd->keyblock_cache.state = KEYBLOCK_CACHE_EMPTY;
251 xfree (hd->keyblock_cache.sigstatus);
252 hd->keyblock_cache.sigstatus = NULL;
253 iobuf_close (hd->keyblock_cache.iobuf);
254 hd->keyblock_cache.iobuf = NULL;
255 hd->keyblock_cache.resource = -1;
256 hd->keyblock_cache.offset = -1;
260 /* Handle the creation of a keyring or a keybox if it does not yet
261 exist. Take into account that other processes might have the
262 keyring/keybox already locked. This lock check does not work if
263 the directory itself is not yet available. If IS_BOX is true the
264 filename is expected to refer to a keybox. If FORCE_CREATE is true
265 the keyring or keybox will be created.
267 Return 0 if it is okay to access the specified file. */
269 maybe_create_keyring_or_box (char *filename, int is_box, int force_create)
271 dotlock_t lockhd = NULL;
275 char *last_slash_in_filename;
276 char *bak_fname = NULL;
277 char *tmp_fname = NULL;
280 /* A quick test whether the filename already exists. */
281 if (!access (filename, F_OK))
282 return !access (filename, R_OK)? 0 : gpg_error (GPG_ERR_EACCES);
284 /* If we don't want to create a new file at all, there is no need to
285 go any further - bail out right here. */
287 return gpg_error (GPG_ERR_ENOENT);
289 /* First of all we try to create the home directory. Note, that we
290 don't do any locking here because any sane application of gpg
291 would create the home directory by itself and not rely on gpg's
292 tricky auto-creation which is anyway only done for certain home
293 directory name pattern. */
294 last_slash_in_filename = strrchr (filename, DIRSEP_C);
297 /* Windows may either have a slash or a backslash. Take care of it. */
298 char *p = strrchr (filename, '/');
299 if (!last_slash_in_filename || p > last_slash_in_filename)
300 last_slash_in_filename = p;
302 #endif /*HAVE_W32_SYSTEM*/
303 if (!last_slash_in_filename)
304 return gpg_error (GPG_ERR_ENOENT); /* No slash at all - should
305 not happen though. */
306 save_slash = *last_slash_in_filename;
307 *last_slash_in_filename = 0;
308 if (access(filename, F_OK))
315 try_make_homedir (filename);
317 if (access (filename, F_OK))
319 rc = gpg_error_from_syserror ();
320 *last_slash_in_filename = save_slash;
324 *last_slash_in_filename = save_slash;
326 /* To avoid races with other instances of gpg trying to create or
327 update the keyring (it is removed during an update for a short
328 time), we do the next stuff in a locked state. */
329 lockhd = dotlock_create (filename, 0);
332 rc = gpg_error_from_syserror ();
333 /* A reason for this to fail is that the directory is not
334 writable. However, this whole locking stuff does not make
335 sense if this is the case. An empty non-writable directory
336 with no keyring is not really useful at all. */
338 log_info ("can't allocate lock for '%s': %s\n",
339 filename, gpg_strerror (rc));
342 return gpg_error (GPG_ERR_ENOENT); /* Won't happen. */
347 if ( dotlock_take (lockhd, -1) )
349 rc = gpg_error_from_syserror ();
350 /* This is something bad. Probably a stale lockfile. */
351 log_info ("can't lock '%s': %s\n", filename, gpg_strerror (rc));
355 /* Now the real test while we are locked. */
357 /* Gpg either uses pubring.gpg or pubring.kbx and thus different
358 * lock files. Now, when one gpg process is updating a pubring.gpg
359 * and thus holding the corresponding lock, a second gpg process may
360 * get to here at the time between the two rename operation used by
361 * the first process to update pubring.gpg. The lock taken above
362 * may not protect the second process if it tries to create a
363 * pubring.kbx file which would be protected by a different lock
366 * We can detect this case by checking that the two temporary files
367 * used by the update code exist at the same time. In that case we
368 * do not create a new file but act as if FORCE_CREATE has not been
369 * given. Obviously there is a race between our two checks but the
370 * worst thing is that we won't create a new file, which is better
371 * than to accidentally creating one. */
372 rc = keybox_tmp_names (filename, is_box, &bak_fname, &tmp_fname);
376 if (!access (filename, F_OK))
378 rc = 0; /* Okay, we may access the file now. */
381 if (!access (bak_fname, F_OK) && !access (tmp_fname, F_OK))
383 /* Very likely another process is updating a pubring.gpg and we
384 should not create a pubring.kbx. */
385 rc = gpg_error (GPG_ERR_ENOENT);
390 /* The file does not yet exist, create it now. */
391 oldmask = umask (077);
392 if (is_secured_filename (filename))
395 gpg_err_set_errno (EPERM);
398 iobuf = iobuf_create (filename, 0);
402 rc = gpg_error_from_syserror ();
404 log_error (_("error creating keybox '%s': %s\n"),
405 filename, gpg_strerror (rc));
407 log_error (_("error creating keyring '%s': %s\n"),
408 filename, gpg_strerror (rc));
413 /* Must invalidate that ugly cache */
414 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, filename);
416 /* Make sure that at least one record is in a new keybox file, so
417 that the detection magic will work the next time it is used. */
420 FILE *fp = fopen (filename, "wb");
422 rc = gpg_error_from_syserror ();
425 rc = _keybox_write_header_blob (fp, 1);
431 log_error (_("error creating keybox '%s': %s\n"),
432 filename, gpg_strerror (rc));
434 log_error (_("error creating keyring '%s': %s\n"),
435 filename, gpg_strerror (rc));
443 log_info (_("keybox '%s' created\n"), filename);
445 log_info (_("keyring '%s' created\n"), filename);
453 dotlock_release (lockhd);
454 dotlock_destroy (lockhd);
462 /* Helper for keydb_add_resource. Opens FILENAME to figure out the
465 Returns the specified file's likely type. If the file does not
466 exist, returns KEYDB_RESOURCE_TYPE_NONE and sets *R_FOUND to 0.
467 Otherwise, tries to figure out the file's type. This is either
468 KEYDB_RESOURCE_TYPE_KEYBOX, KEYDB_RESOURCE_TYPE_KEYRING or
469 KEYDB_RESOURCE_TYPE_KEYNONE. If the file is a keybox and it has
470 the OpenPGP flag set, then R_OPENPGP is also set. */
471 static KeydbResourceType
472 rt_from_file (const char *filename, int *r_found, int *r_openpgp)
475 unsigned char verbuf[4];
477 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
479 *r_found = *r_openpgp = 0;
480 fp = fopen (filename, "rb");
485 if (fread (&magic, 4, 1, fp) == 1 )
487 if (magic == 0x13579ace || magic == 0xce9a5713)
488 ; /* GDBM magic - not anymore supported. */
489 else if (fread (&verbuf, 4, 1, fp) == 1
491 && fread (&magic, 4, 1, fp) == 1
492 && !memcmp (&magic, "KBXf", 4))
494 if ((verbuf[3] & 0x02))
496 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
499 rt = KEYDB_RESOURCE_TYPE_KEYRING;
501 else /* Maybe empty: assume keyring. */
502 rt = KEYDB_RESOURCE_TYPE_KEYRING;
511 keydb_search_desc_dump (struct keydb_search_desc *desc)
513 char b[MAX_FORMATTED_FINGERPRINT_LEN + 1];
514 char fpr[2 * MAX_FINGERPRINT_LEN + 1];
518 case KEYDB_SEARCH_MODE_EXACT:
519 return xasprintf ("EXACT: '%s'", desc->u.name);
520 case KEYDB_SEARCH_MODE_SUBSTR:
521 return xasprintf ("SUBSTR: '%s'", desc->u.name);
522 case KEYDB_SEARCH_MODE_MAIL:
523 return xasprintf ("MAIL: '%s'", desc->u.name);
524 case KEYDB_SEARCH_MODE_MAILSUB:
525 return xasprintf ("MAILSUB: '%s'", desc->u.name);
526 case KEYDB_SEARCH_MODE_MAILEND:
527 return xasprintf ("MAILEND: '%s'", desc->u.name);
528 case KEYDB_SEARCH_MODE_WORDS:
529 return xasprintf ("WORDS: '%s'", desc->u.name);
530 case KEYDB_SEARCH_MODE_SHORT_KID:
531 return xasprintf ("SHORT_KID: '%s'",
532 format_keyid (desc->u.kid, KF_SHORT, b, sizeof (b)));
533 case KEYDB_SEARCH_MODE_LONG_KID:
534 return xasprintf ("LONG_KID: '%s'",
535 format_keyid (desc->u.kid, KF_LONG, b, sizeof (b)));
536 case KEYDB_SEARCH_MODE_FPR16:
537 bin2hex (desc->u.fpr, 16, fpr);
538 return xasprintf ("FPR16: '%s'",
539 format_hexfingerprint (fpr, b, sizeof (b)));
540 case KEYDB_SEARCH_MODE_FPR20:
541 bin2hex (desc->u.fpr, 20, fpr);
542 return xasprintf ("FPR20: '%s'",
543 format_hexfingerprint (fpr, b, sizeof (b)));
544 case KEYDB_SEARCH_MODE_FPR:
545 bin2hex (desc->u.fpr, 20, fpr);
546 return xasprintf ("FPR: '%s'",
547 format_hexfingerprint (fpr, b, sizeof (b)));
548 case KEYDB_SEARCH_MODE_ISSUER:
549 return xasprintf ("ISSUER: '%s'", desc->u.name);
550 case KEYDB_SEARCH_MODE_ISSUER_SN:
551 return xasprintf ("ISSUER_SN: '%*s'",
552 (int) (desc->snlen == -1
553 ? strlen (desc->sn) : desc->snlen),
555 case KEYDB_SEARCH_MODE_SN:
556 return xasprintf ("SN: '%*s'",
557 (int) (desc->snlen == -1
558 ? strlen (desc->sn) : desc->snlen),
560 case KEYDB_SEARCH_MODE_SUBJECT:
561 return xasprintf ("SUBJECT: '%s'", desc->u.name);
562 case KEYDB_SEARCH_MODE_KEYGRIP:
563 return xasprintf ("KEYGRIP: %s", desc->u.grip);
564 case KEYDB_SEARCH_MODE_FIRST:
565 return xasprintf ("FIRST");
566 case KEYDB_SEARCH_MODE_NEXT:
567 return xasprintf ("NEXT");
569 return xasprintf ("Bad search mode (%d)", desc->mode);
575 /* Register a resource (keyring or keybox). The first keyring or
576 * keybox that is added using this function is created if it does not
577 * already exist and the KEYDB_RESOURCE_FLAG_READONLY is not set.
579 * FLAGS are a combination of the KEYDB_RESOURCE_FLAG_* constants.
581 * URL must have the following form:
583 * gnupg-ring:filename = plain keyring
584 * gnupg-kbx:filename = keybox file
585 * filename = check file's type (create as a plain keyring)
587 * Note: on systems with drive letters (Windows) invalid URLs (i.e.,
588 * those with an unrecognized part before the ':' such as "c:\...")
589 * will silently be treated as bare filenames. On other systems, such
590 * URLs will cause this function to return GPG_ERR_GENERAL.
592 * If KEYDB_RESOURCE_FLAG_DEFAULT is set, the resource is a keyring
593 * and the file ends in ".gpg", then this function also checks if a
594 * file with the same name, but the extension ".kbx" exists, is a
595 * keybox and the OpenPGP flag is set. If so, this function opens
596 * that resource instead.
598 * If the file is not found, KEYDB_RESOURCE_FLAG_GPGVDEF is set and
599 * the URL ends in ".kbx", then this function will try opening the
600 * same URL, but with the extension ".gpg". If that file is a keybox
601 * with the OpenPGP flag set or it is a keyring, then we use that
604 * If the file is not found, KEYDB_RESOURCE_FLAG_DEFAULT is set, the
605 * file should be created and the file's extension is ".gpg" then we
606 * replace the extension with ".kbx".
608 * If the KEYDB_RESOURCE_FLAG_PRIMARY is set and the resource is a
609 * keyring (not a keybox), then this resource is considered the
610 * primary resource. This is used by keydb_locate_writable(). If
611 * another primary keyring is set, then that keyring is considered the
614 * If KEYDB_RESOURCE_FLAG_READONLY is set and the resource is a
615 * keyring (not a keybox), then the keyring is marked as read only and
616 * operations just as keyring_insert_keyblock will return
619 keydb_add_resource (const char *url, unsigned int flags)
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 */
823 log_error (_("keyblock resource '%s': %s\n"),
824 filename, gpg_strerror (err));
825 write_status_error ("add_keyblock_resource", err);
835 keydb_dump_stats (void)
837 if (kid_not_found_cache_count)
838 log_info ("keydb: kid_not_found_cache: total: %u\n",
839 kid_not_found_cache_count);
843 /* Create a new database handle. A database handle is similar to a
844 file handle: it contains a local file position. This is used when
845 searching: subsequent searches resume where the previous search
846 left off. To rewind the position, use keydb_search_reset(). This
847 function returns NULL on error, sets ERRNO, and prints an error
858 log_clock ("keydb_new");
860 hd = xtrycalloc (1, sizeof *hd);
864 hd->saved_found = -1;
867 log_assert (used_resources <= MAX_KEYDB_RESOURCES);
868 for (i=j=0; ! die && i < used_resources; i++)
870 switch (all_resources[i].type)
872 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
874 case KEYDB_RESOURCE_TYPE_KEYRING:
875 hd->active[j].type = all_resources[i].type;
876 hd->active[j].token = all_resources[i].token;
877 hd->active[j].u.kr = keyring_new (all_resources[i].token);
878 if (!hd->active[j].u.kr)
885 case KEYDB_RESOURCE_TYPE_KEYBOX:
886 hd->active[j].type = all_resources[i].type;
887 hd->active[j].token = all_resources[i].token;
888 hd->active[j].u.kb = keybox_new_openpgp (all_resources[i].token, 0);
889 if (!hd->active[j].u.kb)
905 gpg_err_set_errno (reterrno);
911 log_error (_("error opening key DB: %s\n"),
912 gpg_strerror (gpg_error_from_syserror()));
919 keydb_release (KEYDB_HANDLE hd)
925 log_assert (active_handles > 0);
929 for (i=0; i < hd->used; i++)
931 switch (hd->active[i].type)
933 case KEYDB_RESOURCE_TYPE_NONE:
935 case KEYDB_RESOURCE_TYPE_KEYRING:
936 keyring_release (hd->active[i].u.kr);
938 case KEYDB_RESOURCE_TYPE_KEYBOX:
939 keybox_release (hd->active[i].u.kb);
944 keyblock_cache_clear (hd);
949 /* Set a flag on the handle to suppress use of cached results. This
950 * is required for updating a keyring and for key listings. Fixme:
951 * Using a new parameter for keydb_new might be a better solution. */
953 keydb_disable_caching (KEYDB_HANDLE hd)
960 /* Return the file name of the resource in which the current search
961 * result was found or, if there is no search result, the filename of
962 * the current resource (i.e., the resource that the file position
963 * points to). Note: the filename is not necessarily the URL used to
966 * This function only returns NULL if no handle is specified, in all
967 * other error cases an empty string is returned. */
969 keydb_get_resource_name (KEYDB_HANDLE hd)
972 const char *s = NULL;
977 if ( hd->found >= 0 && hd->found < hd->used)
979 else if ( hd->current >= 0 && hd->current < hd->used)
984 switch (hd->active[idx].type)
986 case KEYDB_RESOURCE_TYPE_NONE:
989 case KEYDB_RESOURCE_TYPE_KEYRING:
990 s = keyring_get_resource_name (hd->active[idx].u.kr);
992 case KEYDB_RESOURCE_TYPE_KEYBOX:
993 s = keybox_get_resource_name (hd->active[idx].u.kb);
1003 lock_all (KEYDB_HANDLE hd)
1007 /* Fixme: This locking scheme may lead to a deadlock if the resources
1008 are not added in the same order by all processes. We are
1009 currently only allowing one resource so it is not a problem.
1010 [Oops: Who claimed the latter]
1012 To fix this we need to use a lock file to protect lock_all. */
1014 for (i=0; !rc && i < hd->used; i++)
1016 switch (hd->active[i].type)
1018 case KEYDB_RESOURCE_TYPE_NONE:
1020 case KEYDB_RESOURCE_TYPE_KEYRING:
1021 rc = keyring_lock (hd->active[i].u.kr, 1);
1023 case KEYDB_RESOURCE_TYPE_KEYBOX:
1024 rc = keybox_lock (hd->active[i].u.kb, 1);
1031 /* Revert the already taken locks. */
1032 for (i--; i >= 0; i--)
1034 switch (hd->active[i].type)
1036 case KEYDB_RESOURCE_TYPE_NONE:
1038 case KEYDB_RESOURCE_TYPE_KEYRING:
1039 keyring_lock (hd->active[i].u.kr, 0);
1041 case KEYDB_RESOURCE_TYPE_KEYBOX:
1042 keybox_lock (hd->active[i].u.kb, 0);
1055 unlock_all (KEYDB_HANDLE hd)
1062 for (i=hd->used-1; i >= 0; i--)
1064 switch (hd->active[i].type)
1066 case KEYDB_RESOURCE_TYPE_NONE:
1068 case KEYDB_RESOURCE_TYPE_KEYRING:
1069 keyring_lock (hd->active[i].u.kr, 0);
1071 case KEYDB_RESOURCE_TYPE_KEYBOX:
1072 keybox_lock (hd->active[i].u.kb, 0);
1081 /* Save the last found state and invalidate the current selection
1082 * (i.e., the entry selected by keydb_search() is invalidated and
1083 * something like keydb_get_keyblock() will return an error). This
1084 * does not change the file position. This makes it possible to do
1087 * keydb_search (hd, ...); // Result 1.
1088 * keydb_push_found_state (hd);
1089 * keydb_search_reset (hd);
1090 * keydb_search (hd, ...); // Result 2.
1091 * keydb_pop_found_state (hd);
1092 * keydb_get_keyblock (hd, ...); // -> Result 1.
1094 * Note: it is only possible to save a single save state at a time.
1095 * In other words, the the save stack only has room for a single
1096 * instance of the state. */
1098 keydb_push_found_state (KEYDB_HANDLE hd)
1103 if (hd->found < 0 || hd->found >= hd->used)
1105 hd->saved_found = -1;
1109 switch (hd->active[hd->found].type)
1111 case KEYDB_RESOURCE_TYPE_NONE:
1113 case KEYDB_RESOURCE_TYPE_KEYRING:
1114 keyring_push_found_state (hd->active[hd->found].u.kr);
1116 case KEYDB_RESOURCE_TYPE_KEYBOX:
1117 keybox_push_found_state (hd->active[hd->found].u.kb);
1121 hd->saved_found = hd->found;
1126 /* Restore the previous save state. If the saved state is NULL or
1127 invalid, this is a NOP. */
1129 keydb_pop_found_state (KEYDB_HANDLE hd)
1134 hd->found = hd->saved_found;
1135 hd->saved_found = -1;
1136 if (hd->found < 0 || hd->found >= hd->used)
1139 switch (hd->active[hd->found].type)
1141 case KEYDB_RESOURCE_TYPE_NONE:
1143 case KEYDB_RESOURCE_TYPE_KEYRING:
1144 keyring_pop_found_state (hd->active[hd->found].u.kr);
1146 case KEYDB_RESOURCE_TYPE_KEYBOX:
1147 keybox_pop_found_state (hd->active[hd->found].u.kb);
1155 parse_keyblock_image (iobuf_t iobuf, int pk_no, int uid_no,
1156 const u32 *sigstatus, kbnode_t *r_keyblock)
1160 kbnode_t keyblock = NULL;
1161 kbnode_t node, *tail;
1162 int in_cert, save_mode;
1164 int pk_count, uid_count;
1168 pkt = xtrymalloc (sizeof *pkt);
1170 return gpg_error_from_syserror ();
1172 save_mode = set_packet_list_mode (0);
1176 pk_count = uid_count = 0;
1177 while ((err = parse_packet (iobuf, pkt)) != -1)
1179 if (gpg_err_code (err) == GPG_ERR_UNKNOWN_PACKET)
1187 log_error ("parse_keyblock_image: read error: %s\n",
1188 gpg_strerror (err));
1189 err = gpg_error (GPG_ERR_INV_KEYRING);
1193 /* Filter allowed packets. */
1194 switch (pkt->pkttype)
1196 case PKT_PUBLIC_KEY:
1197 case PKT_PUBLIC_SUBKEY:
1198 case PKT_SECRET_KEY:
1199 case PKT_SECRET_SUBKEY:
1203 break; /* Allowed per RFC. */
1206 /* Note that can't allow ring trust packets here and some of
1207 the other GPG specific packets don't make sense either. */
1208 if (pkt->pkttype != PKT_RING_TRUST)
1209 log_error ("skipped packet of type %d in keybox\n",
1216 /* Other sanity checks. */
1217 if (!in_cert && pkt->pkttype != PKT_PUBLIC_KEY)
1219 log_error ("parse_keyblock_image: first packet in a keybox blob "
1220 "is not a public key packet\n");
1221 err = gpg_error (GPG_ERR_INV_KEYRING);
1224 if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
1225 || pkt->pkttype == PKT_SECRET_KEY))
1227 log_error ("parse_keyblock_image: "
1228 "multiple keyblocks in a keybox blob\n");
1229 err = gpg_error (GPG_ERR_INV_KEYRING);
1234 if (pkt->pkttype == PKT_SIGNATURE && sigstatus)
1236 PKT_signature *sig = pkt->pkt.signature;
1239 if (n_sigs > sigstatus[0])
1241 log_error ("parse_keyblock_image: "
1242 "more signatures than found in the meta data\n");
1243 err = gpg_error (GPG_ERR_INV_KEYRING);
1247 if (sigstatus[n_sigs])
1249 sig->flags.checked = 1;
1250 if (sigstatus[n_sigs] == 1 )
1252 else if (sigstatus[n_sigs] == 2 )
1253 ; /* bad signature */
1254 else if (sigstatus[n_sigs] < 0x10000000)
1258 sig->flags.valid = 1;
1259 /* Fixme: Shall we set the expired flag here? */
1264 node = new_kbnode (pkt);
1266 switch (pkt->pkttype)
1268 case PKT_PUBLIC_KEY:
1269 case PKT_PUBLIC_SUBKEY:
1270 case PKT_SECRET_KEY:
1271 case PKT_SECRET_SUBKEY:
1272 if (++pk_count == pk_no)
1277 if (++uid_count == uid_no)
1290 pkt = xtrymalloc (sizeof *pkt);
1293 err = gpg_error_from_syserror ();
1298 set_packet_list_mode (save_mode);
1300 if (err == -1 && keyblock)
1301 err = 0; /* Got the entire keyblock. */
1303 if (!err && sigstatus && n_sigs != sigstatus[0])
1305 log_error ("parse_keyblock_image: signature count does not match\n");
1306 err = gpg_error (GPG_ERR_INV_KEYRING);
1310 release_kbnode (keyblock);
1312 *r_keyblock = keyblock;
1319 /* Return the keyblock last found by keydb_search() in *RET_KB.
1321 * On success, the function returns 0 and the caller must free *RET_KB
1322 * using release_kbnode(). Otherwise, the function returns an error
1325 * The returned keyblock has the kbnode flag bit 0 set for the node
1326 * with the public key used to locate the keyblock or flag bit 1 set
1327 * for the user ID node. */
1329 keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
1331 gpg_error_t err = 0;
1336 return gpg_error (GPG_ERR_INV_ARG);
1339 log_clock ("keydb_get_keybock enter");
1341 if (hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED)
1343 err = iobuf_seek (hd->keyblock_cache.iobuf, 0);
1346 log_error ("keydb_get_keyblock: failed to rewind iobuf for cache\n");
1347 keyblock_cache_clear (hd);
1351 err = parse_keyblock_image (hd->keyblock_cache.iobuf,
1352 hd->keyblock_cache.pk_no,
1353 hd->keyblock_cache.uid_no,
1354 hd->keyblock_cache.sigstatus,
1357 keyblock_cache_clear (hd);
1359 log_clock (err? "keydb_get_keyblock leave (cached, failed)"
1360 : "keydb_get_keyblock leave (cached)");
1365 if (hd->found < 0 || hd->found >= hd->used)
1366 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1368 switch (hd->active[hd->found].type)
1370 case KEYDB_RESOURCE_TYPE_NONE:
1371 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1373 case KEYDB_RESOURCE_TYPE_KEYRING:
1374 err = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
1376 case KEYDB_RESOURCE_TYPE_KEYBOX:
1382 err = keybox_get_keyblock (hd->active[hd->found].u.kb,
1383 &iobuf, &pk_no, &uid_no, &sigstatus);
1386 err = parse_keyblock_image (iobuf, pk_no, uid_no, sigstatus,
1388 if (!err && hd->keyblock_cache.state == KEYBLOCK_CACHE_PREPARED)
1390 hd->keyblock_cache.state = KEYBLOCK_CACHE_FILLED;
1391 hd->keyblock_cache.sigstatus = sigstatus;
1392 hd->keyblock_cache.iobuf = iobuf;
1393 hd->keyblock_cache.pk_no = pk_no;
1394 hd->keyblock_cache.uid_no = uid_no;
1399 iobuf_close (iobuf);
1406 if (hd->keyblock_cache.state != KEYBLOCK_CACHE_FILLED)
1407 keyblock_cache_clear (hd);
1410 log_clock (err? "keydb_get_keyblock leave (failed)"
1411 : "keydb_get_keyblock leave");
1416 /* Build a keyblock image from KEYBLOCK. Returns 0 on success and
1417 only then stores a new iobuf object at R_IOBUF and a signature
1418 status vecotor at R_SIGSTATUS. */
1420 build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf, u32 **r_sigstatus)
1424 kbnode_t kbctx, node;
1430 *r_sigstatus = NULL;
1432 /* Allocate a vector for the signature cache. This is an array of
1433 u32 values with the first value giving the number of elements to
1434 follow and each element descriping the cache status of the
1438 for (kbctx=NULL, n_sigs=0; (node = walk_kbnode (keyblock, &kbctx, 0));)
1439 if (node->pkt->pkttype == PKT_SIGNATURE)
1441 sigstatus = xtrycalloc (1+n_sigs, sizeof *sigstatus);
1443 return gpg_error_from_syserror ();
1448 iobuf = iobuf_temp ();
1449 for (kbctx = NULL, n_sigs = 0; (node = walk_kbnode (keyblock, &kbctx, 0));)
1451 /* Make sure to use only packets valid on a keyblock. */
1452 switch (node->pkt->pkttype)
1454 case PKT_PUBLIC_KEY:
1455 case PKT_PUBLIC_SUBKEY:
1459 /* Note that we don't want the ring trust packets. They are
1466 err = build_packet (iobuf, node->pkt);
1469 iobuf_close (iobuf);
1473 /* Build signature status vector. */
1474 if (node->pkt->pkttype == PKT_SIGNATURE)
1476 PKT_signature *sig = node->pkt->pkt.signature;
1479 /* Fixme: Detect the "missing key" status. */
1480 if (sig->flags.checked && sigstatus)
1482 if (sig->flags.valid)
1484 if (!sig->expiredate)
1485 sigstatus[n_sigs] = 0xffffffff;
1486 else if (sig->expiredate < 0x1000000)
1487 sigstatus[n_sigs] = 0x10000000;
1489 sigstatus[n_sigs] = sig->expiredate;
1492 sigstatus[n_sigs] = 0x00000002; /* Bad signature. */
1497 sigstatus[0] = n_sigs;
1501 *r_sigstatus = sigstatus;
1506 /* Update the keyblock KB (i.e., extract the fingerprint and find the
1507 * corresponding keyblock in the keyring).
1509 * This doesn't do anything if --dry-run was specified.
1511 * Returns 0 on success. Otherwise, it returns an error code. Note:
1512 * if there isn't a keyblock in the keyring corresponding to KB, then
1513 * this function returns GPG_ERR_VALUE_NOT_FOUND.
1515 * This function selects the matching record and modifies the current
1516 * file position to point to the record just after the selected entry.
1517 * Thus, if you do a subsequent search using HD, you should first do a
1518 * keydb_search_reset. Further, if the selected record is important,
1519 * you should use keydb_push_found_state and keydb_pop_found_state to
1520 * save and restore it. */
1522 keydb_update_keyblock (ctrl_t ctrl, KEYDB_HANDLE hd, kbnode_t kb)
1526 KEYDB_SEARCH_DESC desc;
1530 log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
1531 pk = kb->pkt->pkt.public_key;
1534 return gpg_error (GPG_ERR_INV_ARG);
1536 kid_not_found_flush ();
1537 keyblock_cache_clear (hd);
1542 err = lock_all (hd);
1547 tofu_notice_key_changed (ctrl, kb);
1550 memset (&desc, 0, sizeof (desc));
1551 fingerprint_from_pk (pk, desc.u.fpr, &len);
1553 desc.mode = KEYDB_SEARCH_MODE_FPR20;
1555 log_bug ("%s: Unsupported key length: %zu\n", __func__, len);
1557 keydb_search_reset (hd);
1558 err = keydb_search (hd, &desc, 1, NULL);
1560 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1561 log_assert (hd->found >= 0 && hd->found < hd->used);
1563 switch (hd->active[hd->found].type)
1565 case KEYDB_RESOURCE_TYPE_NONE:
1566 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1568 case KEYDB_RESOURCE_TYPE_KEYRING:
1569 err = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
1571 case KEYDB_RESOURCE_TYPE_KEYBOX:
1575 err = build_keyblock_image (kb, &iobuf, NULL);
1578 err = keybox_update_keyblock (hd->active[hd->found].u.kb,
1579 iobuf_get_temp_buffer (iobuf),
1580 iobuf_get_temp_length (iobuf));
1581 iobuf_close (iobuf);
1592 /* Insert a keyblock into one of the underlying keyrings or keyboxes.
1594 * Be default, the keyring / keybox from which the last search result
1595 * came is used. If there was no previous search result (or
1596 * keydb_search_reset was called), then the keyring / keybox where the
1597 * next search would start is used (i.e., the current file position).
1599 * Note: this doesn't do anything if --dry-run was specified.
1601 * Returns 0 on success. Otherwise, it returns an error code. */
1603 keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
1609 return gpg_error (GPG_ERR_INV_ARG);
1611 kid_not_found_flush ();
1612 keyblock_cache_clear (hd);
1617 if (hd->found >= 0 && hd->found < hd->used)
1619 else if (hd->current >= 0 && hd->current < hd->used)
1622 return gpg_error (GPG_ERR_GENERAL);
1624 err = lock_all (hd);
1628 switch (hd->active[idx].type)
1630 case KEYDB_RESOURCE_TYPE_NONE:
1631 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1633 case KEYDB_RESOURCE_TYPE_KEYRING:
1634 err = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
1636 case KEYDB_RESOURCE_TYPE_KEYBOX:
1637 { /* We need to turn our kbnode_t list of packets into a proper
1638 keyblock first. This is required by the OpenPGP key parser
1639 included in the keybox code. Eventually we can change this
1640 kludge to have the caller pass the image. */
1644 err = build_keyblock_image (kb, &iobuf, &sigstatus);
1647 err = keybox_insert_keyblock (hd->active[idx].u.kb,
1648 iobuf_get_temp_buffer (iobuf),
1649 iobuf_get_temp_length (iobuf),
1652 iobuf_close (iobuf);
1663 /* Delete the currently selected keyblock. If you haven't done a
1664 * search yet on this database handle (or called keydb_search_reset),
1665 * then this will return an error.
1667 * Returns 0 on success or an error code, if an error occurs. */
1669 keydb_delete_keyblock (KEYDB_HANDLE hd)
1674 return gpg_error (GPG_ERR_INV_ARG);
1676 kid_not_found_flush ();
1677 keyblock_cache_clear (hd);
1679 if (hd->found < 0 || hd->found >= hd->used)
1680 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1689 switch (hd->active[hd->found].type)
1691 case KEYDB_RESOURCE_TYPE_NONE:
1692 rc = gpg_error (GPG_ERR_GENERAL);
1694 case KEYDB_RESOURCE_TYPE_KEYRING:
1695 rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
1697 case KEYDB_RESOURCE_TYPE_KEYBOX:
1698 rc = keybox_delete (hd->active[hd->found].u.kb);
1708 /* A database may consists of multiple keyrings / key boxes. This
1709 * sets the "file position" to the start of the first keyring / key
1710 * box that is writable (i.e., doesn't have the read-only flag set).
1712 * This first tries the primary keyring (the last keyring (not
1713 * keybox!) added using keydb_add_resource() and with
1714 * KEYDB_RESOURCE_FLAG_PRIMARY set). If that is not writable, then it
1715 * tries the keyrings / keyboxes in the order in which they were
1718 keydb_locate_writable (KEYDB_HANDLE hd)
1723 return GPG_ERR_INV_ARG;
1725 rc = keydb_search_reset (hd); /* this does reset hd->current */
1729 /* If we have a primary set, try that one first */
1732 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
1734 if(hd->active[hd->current].token == primary_keydb)
1736 if(keyring_is_writable (hd->active[hd->current].token))
1743 rc = keydb_search_reset (hd); /* this does reset hd->current */
1748 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
1750 switch (hd->active[hd->current].type)
1752 case KEYDB_RESOURCE_TYPE_NONE:
1755 case KEYDB_RESOURCE_TYPE_KEYRING:
1756 if (keyring_is_writable (hd->active[hd->current].token))
1757 return 0; /* found (hd->current is set to it) */
1759 case KEYDB_RESOURCE_TYPE_KEYBOX:
1760 if (keybox_is_writable (hd->active[hd->current].token))
1761 return 0; /* found (hd->current is set to it) */
1766 return gpg_error (GPG_ERR_NOT_FOUND);
1770 /* Rebuild the on-disk caches of all key resources. */
1772 keydb_rebuild_caches (int noisy)
1776 for (i=0; i < used_resources; i++)
1778 if (!keyring_is_writable (all_resources[i].token))
1780 switch (all_resources[i].type)
1782 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
1784 case KEYDB_RESOURCE_TYPE_KEYRING:
1785 rc = keyring_rebuild_cache (all_resources[i].token,noisy);
1787 log_error (_("failed to rebuild keyring cache: %s\n"),
1790 case KEYDB_RESOURCE_TYPE_KEYBOX:
1798 /* Return the number of skipped blocks (because they were to large to
1799 read from a keybox) since the last search reset. */
1801 keydb_get_skipped_counter (KEYDB_HANDLE hd)
1803 return hd ? hd->skipped_long_blobs : 0;
1807 /* Clears the current search result and resets the handle's position
1808 * so that the next search starts at the beginning of the database
1809 * (the start of the first resource).
1811 * Returns 0 on success and an error code if an error occurred.
1812 * (Currently, this function always returns 0 if HD is valid.) */
1814 keydb_search_reset (KEYDB_HANDLE hd)
1820 return gpg_error (GPG_ERR_INV_ARG);
1822 keyblock_cache_clear (hd);
1825 log_clock ("keydb_search_reset");
1828 log_debug ("keydb_search: reset (hd=%p)", hd);
1830 hd->skipped_long_blobs = 0;
1833 /* Now reset all resources. */
1834 for (i=0; !rc && i < hd->used; i++)
1836 switch (hd->active[i].type)
1838 case KEYDB_RESOURCE_TYPE_NONE:
1840 case KEYDB_RESOURCE_TYPE_KEYRING:
1841 rc = keyring_search_reset (hd->active[i].u.kr);
1843 case KEYDB_RESOURCE_TYPE_KEYBOX:
1844 rc = keybox_search_reset (hd->active[i].u.kb);
1853 /* Search the database for keys matching the search description. If
1854 * the DB contains any legacy keys, these are silently ignored.
1856 * DESC is an array of search terms with NDESC entries. The search
1857 * terms are or'd together. That is, the next entry in the DB that
1858 * matches any of the descriptions will be returned.
1860 * Note: this function resumes searching where the last search left
1861 * off (i.e., at the current file position). If you want to search
1862 * from the start of the database, then you need to first call
1863 * keydb_search_reset().
1865 * If no key matches the search description, returns
1866 * GPG_ERR_NOT_FOUND. If there was a match, returns 0. If an error
1867 * occurred, returns an error code.
1869 * The returned key is considered to be selected and the raw data can,
1870 * for instance, be returned by calling keydb_get_keyblock(). */
1872 keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
1873 size_t ndesc, size_t *descindex)
1877 int was_reset = hd->is_reset;
1878 /* If an entry is already in the cache, then don't add it again. */
1879 int already_in_cache = 0;
1882 *descindex = 0; /* Make sure it is always set on return. */
1885 return gpg_error (GPG_ERR_INV_ARG);
1887 if (!any_registered)
1889 write_status_error ("keydb_search", gpg_error (GPG_ERR_KEYRING_OPEN));
1890 return gpg_error (GPG_ERR_NOT_FOUND);
1894 log_clock ("keydb_search enter");
1898 log_debug ("%s: %zd search descriptions:\n", __func__, ndesc);
1899 for (i = 0; i < ndesc; i ++)
1901 char *t = keydb_search_desc_dump (&desc[i]);
1902 log_debug ("%s %d: %s\n", __func__, i, t);
1908 if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID
1909 && (already_in_cache = kid_not_found_p (desc[0].u.kid)) == 1 )
1912 log_clock ("keydb_search leave (not found, cached)");
1913 return gpg_error (GPG_ERR_NOT_FOUND);
1916 /* NB: If one of the exact search modes below is used in a loop to
1917 walk over all keys (with the same fingerprint) the caching must
1918 have been disabled for the handle. */
1921 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
1922 || desc[0].mode == KEYDB_SEARCH_MODE_FPR)
1923 && hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED
1924 && !memcmp (hd->keyblock_cache.fpr, desc[0].u.fpr, 20)
1925 /* Make sure the current file position occurs before the cached
1926 result to avoid an infinite loop. */
1927 && (hd->current < hd->keyblock_cache.resource
1928 || (hd->current == hd->keyblock_cache.resource
1929 && (keybox_offset (hd->active[hd->current].u.kb)
1930 <= hd->keyblock_cache.offset))))
1932 /* (DESCINDEX is already set). */
1934 log_clock ("keydb_search leave (cached)");
1936 hd->current = hd->keyblock_cache.resource;
1937 /* HD->KEYBLOCK_CACHE.OFFSET is the last byte in the record.
1938 Seek just beyond that. */
1939 keybox_seek (hd->active[hd->current].u.kb,
1940 hd->keyblock_cache.offset + 1);
1945 while ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1946 && hd->current >= 0 && hd->current < hd->used)
1949 log_debug ("%s: searching %s (resource %d of %d)\n",
1951 hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING
1953 : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX
1954 ? "keybox" : "unknown type"),
1955 hd->current, hd->used);
1957 switch (hd->active[hd->current].type)
1959 case KEYDB_RESOURCE_TYPE_NONE:
1960 BUG(); /* we should never see it here */
1962 case KEYDB_RESOURCE_TYPE_KEYRING:
1963 rc = keyring_search (hd->active[hd->current].u.kr, desc,
1964 ndesc, descindex, 1);
1966 case KEYDB_RESOURCE_TYPE_KEYBOX:
1968 rc = keybox_search (hd->active[hd->current].u.kb, desc,
1969 ndesc, KEYBOX_BLOBTYPE_PGP,
1970 descindex, &hd->skipped_long_blobs);
1971 while (rc == GPG_ERR_LEGACY_KEY);
1976 log_debug ("%s: searched %s (resource %d of %d) => %s\n",
1978 hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING
1980 : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX
1981 ? "keybox" : "unknown type"),
1982 hd->current, hd->used,
1983 rc == -1 ? "EOF" : gpg_strerror (rc));
1985 if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1987 /* EOF -> switch to next resource */
1991 hd->found = hd->current;
1995 rc = ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1996 ? gpg_error (GPG_ERR_NOT_FOUND)
1999 keyblock_cache_clear (hd);
2002 && ndesc == 1 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
2003 || desc[0].mode == KEYDB_SEARCH_MODE_FPR)
2004 && hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX)
2006 hd->keyblock_cache.state = KEYBLOCK_CACHE_PREPARED;
2007 hd->keyblock_cache.resource = hd->current;
2008 /* The current offset is at the start of the next record. Since
2009 a record is at least 1 byte, we just use offset - 1, which is
2010 within the record. */
2011 hd->keyblock_cache.offset
2012 = keybox_offset (hd->active[hd->current].u.kb) - 1;
2013 memcpy (hd->keyblock_cache.fpr, desc[0].u.fpr, 20);
2016 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND
2017 && ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID && was_reset
2018 && !already_in_cache)
2019 kid_not_found_insert (desc[0].u.kid);
2022 log_clock (rc? "keydb_search leave (not found)"
2023 : "keydb_search leave (found)");
2028 /* Return the first non-legacy key in the database.
2030 * If you want the very first key in the database, you can directly
2031 * call keydb_search with the search description
2032 * KEYDB_SEARCH_MODE_FIRST. */
2034 keydb_search_first (KEYDB_HANDLE hd)
2037 KEYDB_SEARCH_DESC desc;
2039 err = keydb_search_reset (hd);
2043 memset (&desc, 0, sizeof desc);
2044 desc.mode = KEYDB_SEARCH_MODE_FIRST;
2045 return keydb_search (hd, &desc, 1, NULL);
2049 /* Return the next key (not the next matching key!).
2051 * Unlike calling keydb_search with KEYDB_SEARCH_MODE_NEXT, this
2052 * function silently skips legacy keys. */
2054 keydb_search_next (KEYDB_HANDLE hd)
2056 KEYDB_SEARCH_DESC desc;
2058 memset (&desc, 0, sizeof desc);
2059 desc.mode = KEYDB_SEARCH_MODE_NEXT;
2060 return keydb_search (hd, &desc, 1, NULL);
2064 /* This is a convenience function for searching for keys with a long
2067 * Note: this function resumes searching where the last search left
2068 * off. If you want to search the whole database, then you need to
2069 * first call keydb_search_reset(). */
2071 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
2073 KEYDB_SEARCH_DESC desc;
2075 memset (&desc, 0, sizeof desc);
2076 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
2077 desc.u.kid[0] = kid[0];
2078 desc.u.kid[1] = kid[1];
2079 return keydb_search (hd, &desc, 1, NULL);
2083 /* This is a convenience function for searching for keys with a long
2084 * (20 byte) fingerprint.
2086 * Note: this function resumes searching where the last search left
2087 * off. If you want to search the whole database, then you need to
2088 * first call keydb_search_reset(). */
2090 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
2092 KEYDB_SEARCH_DESC desc;
2094 memset (&desc, 0, sizeof desc);
2095 desc.mode = KEYDB_SEARCH_MODE_FPR;
2096 memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
2097 return keydb_search (hd, &desc, 1, NULL);