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 <http://www.gnu.org/licenses/>.
27 #include <sys/types.h>
34 #include "main.h" /*try_make_homedir ()*/
37 #include "../kbx/keybox.h"
41 static int active_handles;
45 KEYDB_RESOURCE_TYPE_NONE = 0,
46 KEYDB_RESOURCE_TYPE_KEYRING,
47 KEYDB_RESOURCE_TYPE_KEYBOX
49 #define MAX_KEYDB_RESOURCES 40
53 KeydbResourceType type;
61 static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
62 static int used_resources;
63 static void *primary_keyring=NULL;
66 /* This is a simple cache used to return the last result of a
67 successful fingerprint search. This works only for keybox resources
68 because (due to lack of a copy_keyblock function) we need to store
69 an image of the keyblock which is fortunately instantly available
71 enum keyblock_cache_states {
73 KEYBLOCK_CACHE_PREPARED,
77 struct keyblock_cache {
78 enum keyblock_cache_states state;
79 byte fpr[MAX_FINGERPRINT_LEN];
80 iobuf_t iobuf; /* Image of the keyblock. */
89 /* When we locked all of the resources in ACTIVE (using keyring_lock
90 / keybox_lock, as appropriate). */
93 /* The index into ACTIVE of the resources in which the last search
94 result was found. Initially -1. */
97 /* Initially -1 (invalid). This is used to save a search result and
98 later restore it as the selected result. */
101 /* The number of skipped long blobs since the last search
102 (keydb_search_reset). */
103 unsigned long skipped_long_blobs;
105 /* If set, this disables the use of the keyblock cache. */
108 /* Whether the next search will be from the beginning of the
109 database (and thus consider all records). */
112 /* The "file position." In our case, this is index of the current
113 resource in ACTIVE. */
116 /* The number of resources in ACTIVE. */
119 /* Cache of the last found and parsed key block (only used for
120 keyboxes, not keyrings). */
121 struct keyblock_cache keyblock_cache;
123 /* Copy of ALL_RESOURCES when keydb_new is called. */
124 struct resource_item active[MAX_KEYDB_RESOURCES];
127 /* Looking up keys is expensive. To hide the cost, we cache whether
128 keys exist in the key database. Then, if we know a key does not
129 exist, we don't have to spend time looking it up. This
130 particularly helps the --list-sigs and --check-sigs commands.
132 The cache stores the results in a hash using separate chaining.
133 Concretely: we use the LSB of the keyid to index the hash table and
134 each bucket consists of a linked list of entries. An entry
135 consists of the 64-bit key id. If a key id is not in the cache,
136 then we don't know whether it is in the DB or not.
138 To simplify the cache consistency protocol, we simply flush the
139 whole cache whenever a key is inserted or updated. */
141 #define KID_NOT_FOUND_CACHE_BUCKETS 256
142 static struct kid_not_found_cache_bucket *
143 kid_not_found_cache[KID_NOT_FOUND_CACHE_BUCKETS];
145 /* The total number of entries in the hash table. */
146 static unsigned int kid_not_found_cache_count;
148 struct kid_not_found_cache_bucket
150 struct kid_not_found_cache_bucket *next;
155 static int lock_all (KEYDB_HANDLE hd);
156 static void unlock_all (KEYDB_HANDLE hd);
159 /* Check whether the keyid KID is in key id is definately not in the
164 0 - Indeterminate: the key id is not in the cache; we don't know
165 whether the key is in the database or not. If you want a
166 definitive answer, you'll need to perform a lookup.
168 1 - There is definitely no key with this key id in the database.
169 We searched for a key with this key id previously, but we
170 didn't find it in the database. */
172 kid_not_found_p (u32 *kid)
174 struct kid_not_found_cache_bucket *k;
176 for (k = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS]; k; k = k->next)
177 if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
180 log_debug ("keydb: kid_not_found_p (%08lx%08lx) => not in DB\n",
181 (ulong)kid[0], (ulong)kid[1]);
186 log_debug ("keydb: kid_not_found_p (%08lx%08lx) => indeterminate\n",
187 (ulong)kid[0], (ulong)kid[1]);
192 /* Insert the keyid KID into the kid_not_found_cache. FOUND is whether
193 the key is in the key database or not.
195 Note this function does not check whether the key id is already in
196 the cache. As such, kid_not_found_p() should be called first. */
198 kid_not_found_insert (u32 *kid)
200 struct kid_not_found_cache_bucket *k;
203 log_debug ("keydb: kid_not_found_insert (%08lx%08lx)\n",
204 (ulong)kid[0], (ulong)kid[1]);
205 k = xmalloc (sizeof *k);
208 k->next = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS];
209 kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS] = k;
210 kid_not_found_cache_count++;
214 /* Flush the kid not found cache. */
216 kid_not_found_flush (void)
218 struct kid_not_found_cache_bucket *k, *knext;
222 log_debug ("keydb: kid_not_found_flush\n");
224 if (!kid_not_found_cache_count)
227 for (i=0; i < DIM(kid_not_found_cache); i++)
229 for (k = kid_not_found_cache[i]; k; k = knext)
234 kid_not_found_cache[i] = NULL;
236 kid_not_found_cache_count = 0;
241 keyblock_cache_clear (struct keydb_handle *hd)
243 hd->keyblock_cache.state = KEYBLOCK_CACHE_EMPTY;
244 xfree (hd->keyblock_cache.sigstatus);
245 hd->keyblock_cache.sigstatus = NULL;
246 iobuf_close (hd->keyblock_cache.iobuf);
247 hd->keyblock_cache.iobuf = NULL;
251 /* Handle the creation of a keyring or a keybox if it does not yet
252 exist. Take into account that other processes might have the
253 keyring/keybox already locked. This lock check does not work if
254 the directory itself is not yet available. If IS_BOX is true the
255 filename is expected to refer to a keybox. If FORCE_CREATE is true
256 the keyring or keybox will be created.
258 Return 0 if it is okay to access the specified file. */
260 maybe_create_keyring_or_box (char *filename, int is_box, int force_create)
262 dotlock_t lockhd = NULL;
266 char *last_slash_in_filename;
269 /* A quick test whether the filename already exists. */
270 if (!access (filename, F_OK))
273 /* If we don't want to create a new file at all, there is no need to
274 go any further - bail out right here. */
276 return gpg_error (GPG_ERR_ENOENT);
278 /* First of all we try to create the home directory. Note, that we
279 don't do any locking here because any sane application of gpg
280 would create the home directory by itself and not rely on gpg's
281 tricky auto-creation which is anyway only done for certain home
282 directory name pattern. */
283 last_slash_in_filename = strrchr (filename, DIRSEP_C);
286 /* Windows may either have a slash or a backslash. Take care of it. */
287 char *p = strrchr (filename, '/');
288 if (!last_slash_in_filename || p > last_slash_in_filename)
289 last_slash_in_filename = p;
291 #endif /*HAVE_W32_SYSTEM*/
292 if (!last_slash_in_filename)
293 return gpg_error (GPG_ERR_ENOENT); /* No slash at all - should
294 not happen though. */
295 save_slash = *last_slash_in_filename;
296 *last_slash_in_filename = 0;
297 if (access(filename, F_OK))
304 try_make_homedir (filename);
306 if (access (filename, F_OK))
308 rc = gpg_error_from_syserror ();
309 *last_slash_in_filename = save_slash;
313 *last_slash_in_filename = save_slash;
315 /* To avoid races with other instances of gpg trying to create or
316 update the keyring (it is removed during an update for a short
317 time), we do the next stuff in a locked state. */
318 lockhd = dotlock_create (filename, 0);
321 rc = gpg_error_from_syserror ();
322 /* A reason for this to fail is that the directory is not
323 writable. However, this whole locking stuff does not make
324 sense if this is the case. An empty non-writable directory
325 with no keyring is not really useful at all. */
327 log_info ("can't allocate lock for '%s': %s\n",
328 filename, gpg_strerror (rc));
331 return gpg_error (GPG_ERR_ENOENT); /* Won't happen. */
336 if ( dotlock_take (lockhd, -1) )
338 rc = gpg_error_from_syserror ();
339 /* This is something bad. Probably a stale lockfile. */
340 log_info ("can't lock '%s': %s\n", filename, gpg_strerror (rc));
344 /* Now the real test while we are locked. */
345 if (!access (filename, F_OK))
347 rc = 0; /* Okay, we may access the file now. */
351 /* The file does not yet exist, create it now. */
352 oldmask = umask (077);
353 if (is_secured_filename (filename))
356 gpg_err_set_errno (EPERM);
359 iobuf = iobuf_create (filename, 0);
363 rc = gpg_error_from_syserror ();
365 log_error (_("error creating keybox '%s': %s\n"),
366 filename, gpg_strerror (rc));
368 log_error (_("error creating keyring '%s': %s\n"),
369 filename, gpg_strerror (rc));
374 /* Must invalidate that ugly cache */
375 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, filename);
377 /* Make sure that at least one record is in a new keybox file, so
378 that the detection magic will work the next time it is used. */
381 FILE *fp = fopen (filename, "w");
383 rc = gpg_error_from_syserror ();
386 rc = _keybox_write_header_blob (fp, 1);
392 log_error (_("error creating keybox '%s': %s\n"),
393 filename, gpg_strerror (rc));
395 log_error (_("error creating keyring '%s': %s\n"),
396 filename, gpg_strerror (rc));
404 log_info (_("keybox '%s' created\n"), filename);
406 log_info (_("keyring '%s' created\n"), filename);
414 dotlock_release (lockhd);
415 dotlock_destroy (lockhd);
421 /* Helper for keydb_add_resource. Opens FILENAME to figure out the
424 Returns the specified file's likely type. If the file does not
425 exist, returns KEYDB_RESOURCE_TYPE_NONE and sets *R_FOUND to 0.
426 Otherwise, tries to figure out the file's type. This is either
427 KEYDB_RESOURCE_TYPE_KEYBOX, KEYDB_RESOURCE_TYPE_KEYRING or
428 KEYDB_RESOURCE_TYPE_KEYNONE. If the file is a keybox and it has
429 the OpenPGP flag set, then R_OPENPGP is also set. */
430 static KeydbResourceType
431 rt_from_file (const char *filename, int *r_found, int *r_openpgp)
434 unsigned char verbuf[4];
436 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
438 *r_found = *r_openpgp = 0;
439 fp = fopen (filename, "rb");
444 if (fread (&magic, 4, 1, fp) == 1 )
446 if (magic == 0x13579ace || magic == 0xce9a5713)
447 ; /* GDBM magic - not anymore supported. */
448 else if (fread (&verbuf, 4, 1, fp) == 1
450 && fread (&magic, 4, 1, fp) == 1
451 && !memcmp (&magic, "KBXf", 4))
453 if ((verbuf[3] & 0x02))
455 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
458 rt = KEYDB_RESOURCE_TYPE_KEYRING;
460 else /* Maybe empty: assume keyring. */
461 rt = KEYDB_RESOURCE_TYPE_KEYRING;
471 keydb_add_resource (const char *url, unsigned int flags)
473 /* Whether we have successfully registered a resource. */
474 static int any_registered;
475 /* The file named by the URL (i.e., without the prototype). */
476 const char *resname = url;
478 char *filename = NULL;
480 int read_only = !!(flags&KEYDB_RESOURCE_FLAG_READONLY);
481 int is_default = !!(flags&KEYDB_RESOURCE_FLAG_DEFAULT);
482 int is_gpgvdef = !!(flags&KEYDB_RESOURCE_FLAG_GPGVDEF);
484 KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
487 /* Create the resource if it is the first registered one. */
488 create = (!read_only && !any_registered);
490 if (strlen (resname) > 11 && !strncmp( resname, "gnupg-ring:", 11) )
492 rt = KEYDB_RESOURCE_TYPE_KEYRING;
495 else if (strlen (resname) > 10 && !strncmp (resname, "gnupg-kbx:", 10) )
497 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
500 #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
501 else if (strchr (resname, ':'))
503 log_error ("invalid key resource URL '%s'\n", url );
504 rc = gpg_error (GPG_ERR_GENERAL);
507 #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
509 if (*resname != DIRSEP_C
510 #ifdef HAVE_W32_SYSTEM
511 && *resname != '/' /* Fixme: does not handle drive letters. */
515 /* Do tilde expansion etc. */
516 if (strchr (resname, DIRSEP_C)
517 #ifdef HAVE_W32_SYSTEM
518 || strchr (resname, '/') /* Windows also accepts this. */
521 filename = make_filename (resname, NULL);
523 filename = make_filename (opt.homedir, resname, NULL);
526 filename = xstrdup (resname);
528 /* See whether we can determine the filetype. */
529 if (rt == KEYDB_RESOURCE_TYPE_NONE)
531 int found, openpgp_flag;
536 filenamelen = strlen (filename);
537 rt = rt_from_file (filename, &found, &openpgp_flag);
540 /* The file exists and we have the resource type in RT.
542 Now let us check whether in addition to the "pubring.gpg"
543 a "pubring.kbx with openpgp keys exists. This is so that
544 GPG 2.1 will use an existing "pubring.kbx" by default iff
545 that file has been created or used by 2.1. This check is
546 needed because after creation or use of the kbx file with
547 2.1 an older version of gpg may have created a new
548 pubring.gpg for its own use. */
549 if (!pass && is_default && rt == KEYDB_RESOURCE_TYPE_KEYRING
550 && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg"))
552 strcpy (filename+filenamelen-4, ".kbx");
553 if ((rt_from_file (filename, &found, &openpgp_flag)
554 == KEYDB_RESOURCE_TYPE_KEYBOX) && found && openpgp_flag)
555 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
556 else /* Restore filename */
557 strcpy (filename+filenamelen-4, ".gpg");
560 else if (!pass && is_gpgvdef
561 && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".kbx"))
563 /* Not found but gpgv's default "trustedkeys.kbx" file has
564 been requested. We did not found it so now check whether
565 a "trustedkeys.gpg" file exists and use that instead. */
566 KeydbResourceType rttmp;
568 strcpy (filename+filenamelen-4, ".gpg");
569 rttmp = rt_from_file (filename, &found, &openpgp_flag);
571 && ((rttmp == KEYDB_RESOURCE_TYPE_KEYBOX && openpgp_flag)
572 || (rttmp == KEYDB_RESOURCE_TYPE_KEYRING)))
574 else /* Restore filename */
575 strcpy (filename+filenamelen-4, ".kbx");
578 && is_default && create
579 && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg"))
581 /* The file does not exist, the default resource has been
582 requested, the file shall be created, and the file has a
583 ".gpg" suffix. Change the suffix to ".kbx" and try once
584 more. This way we achieve that we open an existing
585 ".gpg" keyring, but create a new keybox file with an
587 strcpy (filename+filenamelen-4, ".kbx");
591 else /* No file yet: create keybox. */
592 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
597 case KEYDB_RESOURCE_TYPE_NONE:
598 log_error ("unknown type of key resource '%s'\n", url );
599 rc = gpg_error (GPG_ERR_GENERAL);
602 case KEYDB_RESOURCE_TYPE_KEYRING:
603 rc = maybe_create_keyring_or_box (filename, 0, create);
607 if (keyring_register_filename (filename, read_only, &token))
609 if (used_resources >= MAX_KEYDB_RESOURCES)
610 rc = gpg_error (GPG_ERR_RESOURCE_LIMIT);
613 if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
614 primary_keyring = token;
615 all_resources[used_resources].type = rt;
616 all_resources[used_resources].u.kr = NULL; /* Not used here */
617 all_resources[used_resources].token = token;
623 /* This keyring was already registered, so ignore it.
624 However, we can still mark it as primary even if it was
625 already registered. */
626 if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
627 primary_keyring = token;
631 case KEYDB_RESOURCE_TYPE_KEYBOX:
633 rc = maybe_create_keyring_or_box (filename, 1, create);
637 /* FIXME: How do we register a read-only keybox? */
638 token = keybox_register_file (filename, 0);
641 if (used_resources >= MAX_KEYDB_RESOURCES)
642 rc = gpg_error (GPG_ERR_RESOURCE_LIMIT);
645 /* if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) */
646 /* primary_keyring = token; */
647 all_resources[used_resources].type = rt;
648 all_resources[used_resources].u.kb = NULL; /* Not used here */
649 all_resources[used_resources].token = token;
651 /* FIXME: Do a compress run if needed and no other
652 user is currently using the keybox. */
659 /* Already registered. We will mark it as the primary key
661 /* FIXME: How to do that? Change the keybox interface? */
662 /* if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY)) */
663 /* primary_keyring = token; */
669 log_error ("resource type of '%s' not supported\n", url);
670 rc = gpg_error (GPG_ERR_GENERAL);
674 /* fixme: check directory permissions and print a warning */
678 log_error (_("keyblock resource '%s': %s\n"), filename, gpg_strerror (rc));
687 keydb_dump_stats (void)
689 if (kid_not_found_cache_count)
690 log_info ("keydb: kid_not_found_cache: total: %u\n",
691 kid_not_found_cache_count);
703 log_clock ("keydb_new");
705 hd = xmalloc_clear (sizeof *hd);
707 hd->saved_found = -1;
710 assert (used_resources <= MAX_KEYDB_RESOURCES);
711 for (i=j=0; ! die && i < used_resources; i++)
713 switch (all_resources[i].type)
715 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
717 case KEYDB_RESOURCE_TYPE_KEYRING:
718 hd->active[j].type = all_resources[i].type;
719 hd->active[j].token = all_resources[i].token;
720 hd->active[j].u.kr = keyring_new (all_resources[i].token);
721 if (!hd->active[j].u.kr)
725 case KEYDB_RESOURCE_TYPE_KEYBOX:
726 hd->active[j].type = all_resources[i].type;
727 hd->active[j].token = all_resources[i].token;
728 hd->active[j].u.kb = keybox_new_openpgp (all_resources[i].token, 0);
729 if (!hd->active[j].u.kb)
750 keydb_release (KEYDB_HANDLE hd)
756 assert (active_handles > 0);
760 for (i=0; i < hd->used; i++)
762 switch (hd->active[i].type)
764 case KEYDB_RESOURCE_TYPE_NONE:
766 case KEYDB_RESOURCE_TYPE_KEYRING:
767 keyring_release (hd->active[i].u.kr);
769 case KEYDB_RESOURCE_TYPE_KEYBOX:
770 keybox_release (hd->active[i].u.kb);
780 keydb_disable_caching (KEYDB_HANDLE hd)
788 keydb_get_resource_name (KEYDB_HANDLE hd)
791 const char *s = NULL;
796 if ( hd->found >= 0 && hd->found < hd->used)
798 else if ( hd->current >= 0 && hd->current < hd->used)
803 switch (hd->active[idx].type)
805 case KEYDB_RESOURCE_TYPE_NONE:
808 case KEYDB_RESOURCE_TYPE_KEYRING:
809 s = keyring_get_resource_name (hd->active[idx].u.kr);
811 case KEYDB_RESOURCE_TYPE_KEYBOX:
812 s = keybox_get_resource_name (hd->active[idx].u.kb);
822 lock_all (KEYDB_HANDLE hd)
826 /* Fixme: This locking scheme may lead to a deadlock if the resources
827 are not added in the same order by all processes. We are
828 currently only allowing one resource so it is not a problem.
829 [Oops: Who claimed the latter]
831 To fix this we need to use a lock file to protect lock_all. */
833 for (i=0; !rc && i < hd->used; i++)
835 switch (hd->active[i].type)
837 case KEYDB_RESOURCE_TYPE_NONE:
839 case KEYDB_RESOURCE_TYPE_KEYRING:
840 rc = keyring_lock (hd->active[i].u.kr, 1);
842 case KEYDB_RESOURCE_TYPE_KEYBOX:
843 rc = keybox_lock (hd->active[i].u.kb, 1);
850 /* Revert the already taken locks. */
851 for (i--; i >= 0; i--)
853 switch (hd->active[i].type)
855 case KEYDB_RESOURCE_TYPE_NONE:
857 case KEYDB_RESOURCE_TYPE_KEYRING:
858 keyring_lock (hd->active[i].u.kr, 0);
860 case KEYDB_RESOURCE_TYPE_KEYBOX:
861 rc = keybox_lock (hd->active[i].u.kb, 0);
874 unlock_all (KEYDB_HANDLE hd)
881 for (i=hd->used-1; i >= 0; i--)
883 switch (hd->active[i].type)
885 case KEYDB_RESOURCE_TYPE_NONE:
887 case KEYDB_RESOURCE_TYPE_KEYRING:
888 keyring_lock (hd->active[i].u.kr, 0);
890 case KEYDB_RESOURCE_TYPE_KEYBOX:
891 keybox_lock (hd->active[i].u.kb, 0);
901 keydb_push_found_state (KEYDB_HANDLE hd)
906 if (hd->found < 0 || hd->found >= hd->used)
908 hd->saved_found = -1;
912 switch (hd->active[hd->found].type)
914 case KEYDB_RESOURCE_TYPE_NONE:
916 case KEYDB_RESOURCE_TYPE_KEYRING:
917 keyring_push_found_state (hd->active[hd->found].u.kr);
919 case KEYDB_RESOURCE_TYPE_KEYBOX:
920 keybox_push_found_state (hd->active[hd->found].u.kb);
924 hd->saved_found = hd->found;
930 keydb_pop_found_state (KEYDB_HANDLE hd)
935 hd->found = hd->saved_found;
936 hd->saved_found = -1;
937 if (hd->found < 0 || hd->found >= hd->used)
940 switch (hd->active[hd->found].type)
942 case KEYDB_RESOURCE_TYPE_NONE:
944 case KEYDB_RESOURCE_TYPE_KEYRING:
945 keyring_pop_found_state (hd->active[hd->found].u.kr);
947 case KEYDB_RESOURCE_TYPE_KEYBOX:
948 keybox_pop_found_state (hd->active[hd->found].u.kb);
956 parse_keyblock_image (iobuf_t iobuf, int pk_no, int uid_no,
957 const u32 *sigstatus, kbnode_t *r_keyblock)
961 kbnode_t keyblock = NULL;
962 kbnode_t node, *tail;
963 int in_cert, save_mode;
965 int pk_count, uid_count;
969 pkt = xtrymalloc (sizeof *pkt);
971 return gpg_error_from_syserror ();
973 save_mode = set_packet_list_mode (0);
977 pk_count = uid_count = 0;
978 while ((err = parse_packet (iobuf, pkt)) != -1)
980 if (gpg_err_code (err) == GPG_ERR_UNKNOWN_PACKET)
988 log_error ("parse_keyblock_image: read error: %s\n",
990 err = gpg_error (GPG_ERR_INV_KEYRING);
994 /* Filter allowed packets. */
995 switch (pkt->pkttype)
998 case PKT_PUBLIC_SUBKEY:
1000 case PKT_SECRET_SUBKEY:
1004 break; /* Allowed per RFC. */
1007 /* Note that can't allow ring trust packets here and some of
1008 the other GPG specific packets don't make sense either. */
1009 log_error ("skipped packet of type %d in keybox\n",
1016 /* Other sanity checks. */
1017 if (!in_cert && pkt->pkttype != PKT_PUBLIC_KEY)
1019 log_error ("parse_keyblock_image: first packet in a keybox blob "
1020 "is not a public key packet\n");
1021 err = gpg_error (GPG_ERR_INV_KEYRING);
1024 if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
1025 || pkt->pkttype == PKT_SECRET_KEY))
1027 log_error ("parse_keyblock_image: "
1028 "multiple keyblocks in a keybox blob\n");
1029 err = gpg_error (GPG_ERR_INV_KEYRING);
1034 if (pkt->pkttype == PKT_SIGNATURE && sigstatus)
1036 PKT_signature *sig = pkt->pkt.signature;
1039 if (n_sigs > sigstatus[0])
1041 log_error ("parse_keyblock_image: "
1042 "more signatures than found in the meta data\n");
1043 err = gpg_error (GPG_ERR_INV_KEYRING);
1047 if (sigstatus[n_sigs])
1049 sig->flags.checked = 1;
1050 if (sigstatus[n_sigs] == 1 )
1052 else if (sigstatus[n_sigs] == 2 )
1053 ; /* bad signature */
1054 else if (sigstatus[n_sigs] < 0x10000000)
1058 sig->flags.valid = 1;
1059 /* Fixme: Shall we set the expired flag here? */
1064 node = new_kbnode (pkt);
1066 switch (pkt->pkttype)
1068 case PKT_PUBLIC_KEY:
1069 case PKT_PUBLIC_SUBKEY:
1070 case PKT_SECRET_KEY:
1071 case PKT_SECRET_SUBKEY:
1072 if (++pk_count == pk_no)
1077 if (++uid_count == uid_no)
1090 pkt = xtrymalloc (sizeof *pkt);
1093 err = gpg_error_from_syserror ();
1098 set_packet_list_mode (save_mode);
1100 if (err == -1 && keyblock)
1101 err = 0; /* Got the entire keyblock. */
1103 if (!err && sigstatus && n_sigs != sigstatus[0])
1105 log_error ("parse_keyblock_image: signature count does not match\n");
1106 err = gpg_error (GPG_ERR_INV_KEYRING);
1110 release_kbnode (keyblock);
1112 *r_keyblock = keyblock;
1120 keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
1122 gpg_error_t err = 0;
1127 return gpg_error (GPG_ERR_INV_ARG);
1130 log_clock ("keydb_get_keybock enter");
1132 if (hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED)
1134 err = iobuf_seek (hd->keyblock_cache.iobuf, 0);
1137 log_error ("keydb_get_keyblock: failed to rewind iobuf for cache\n");
1138 keyblock_cache_clear (hd);
1142 err = parse_keyblock_image (hd->keyblock_cache.iobuf,
1143 hd->keyblock_cache.pk_no,
1144 hd->keyblock_cache.uid_no,
1145 hd->keyblock_cache.sigstatus,
1148 keyblock_cache_clear (hd);
1150 log_clock (err? "keydb_get_keyblock leave (cached, failed)"
1151 : "keydb_get_keyblock leave (cached)");
1156 if (hd->found < 0 || hd->found >= hd->used)
1157 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1159 switch (hd->active[hd->found].type)
1161 case KEYDB_RESOURCE_TYPE_NONE:
1162 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1164 case KEYDB_RESOURCE_TYPE_KEYRING:
1165 err = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
1167 case KEYDB_RESOURCE_TYPE_KEYBOX:
1173 err = keybox_get_keyblock (hd->active[hd->found].u.kb,
1174 &iobuf, &pk_no, &uid_no, &sigstatus);
1177 err = parse_keyblock_image (iobuf, pk_no, uid_no, sigstatus,
1179 if (!err && hd->keyblock_cache.state == KEYBLOCK_CACHE_PREPARED)
1181 hd->keyblock_cache.state = KEYBLOCK_CACHE_FILLED;
1182 hd->keyblock_cache.sigstatus = sigstatus;
1183 hd->keyblock_cache.iobuf = iobuf;
1184 hd->keyblock_cache.pk_no = pk_no;
1185 hd->keyblock_cache.uid_no = uid_no;
1190 iobuf_close (iobuf);
1197 if (hd->keyblock_cache.state != KEYBLOCK_CACHE_FILLED)
1198 keyblock_cache_clear (hd);
1201 log_clock (err? "keydb_get_keyblock leave (failed)"
1202 : "keydb_get_keyblock leave");
1207 /* Build a keyblock image from KEYBLOCK. Returns 0 on success and
1208 only then stores a new iobuf object at R_IOBUF and a signature
1209 status vecotor at R_SIGSTATUS. */
1211 build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf, u32 **r_sigstatus)
1215 kbnode_t kbctx, node;
1221 *r_sigstatus = NULL;
1223 /* Allocate a vector for the signature cache. This is an array of
1224 u32 values with the first value giving the number of elements to
1225 follow and each element descriping the cache status of the
1229 for (kbctx=NULL, n_sigs=0; (node = walk_kbnode (keyblock, &kbctx, 0));)
1230 if (node->pkt->pkttype == PKT_SIGNATURE)
1232 sigstatus = xtrycalloc (1+n_sigs, sizeof *sigstatus);
1234 return gpg_error_from_syserror ();
1239 iobuf = iobuf_temp ();
1240 for (kbctx = NULL, n_sigs = 0; (node = walk_kbnode (keyblock, &kbctx, 0));)
1242 /* Make sure to use only packets valid on a keyblock. */
1243 switch (node->pkt->pkttype)
1245 case PKT_PUBLIC_KEY:
1246 case PKT_PUBLIC_SUBKEY:
1250 /* Note that we don't want the ring trust packets. They are
1257 err = build_packet (iobuf, node->pkt);
1260 iobuf_close (iobuf);
1264 /* Build signature status vector. */
1265 if (node->pkt->pkttype == PKT_SIGNATURE)
1267 PKT_signature *sig = node->pkt->pkt.signature;
1270 /* Fixme: Detect the "missing key" status. */
1271 if (sig->flags.checked && sigstatus)
1273 if (sig->flags.valid)
1275 if (!sig->expiredate)
1276 sigstatus[n_sigs] = 0xffffffff;
1277 else if (sig->expiredate < 0x1000000)
1278 sigstatus[n_sigs] = 0x10000000;
1280 sigstatus[n_sigs] = sig->expiredate;
1283 sigstatus[n_sigs] = 0x00000002; /* Bad signature. */
1288 sigstatus[0] = n_sigs;
1292 *r_sigstatus = sigstatus;
1298 keydb_update_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
1303 return gpg_error (GPG_ERR_INV_ARG);
1305 kid_not_found_flush ();
1306 keyblock_cache_clear (hd);
1308 if (hd->found < 0 || hd->found >= hd->used)
1309 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1314 err = lock_all (hd);
1318 switch (hd->active[hd->found].type)
1320 case KEYDB_RESOURCE_TYPE_NONE:
1321 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1323 case KEYDB_RESOURCE_TYPE_KEYRING:
1324 err = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
1326 case KEYDB_RESOURCE_TYPE_KEYBOX:
1330 err = build_keyblock_image (kb, &iobuf, NULL);
1333 err = keybox_update_keyblock (hd->active[hd->found].u.kb,
1334 iobuf_get_temp_buffer (iobuf),
1335 iobuf_get_temp_length (iobuf));
1336 iobuf_close (iobuf);
1348 keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
1354 return gpg_error (GPG_ERR_INV_ARG);
1356 kid_not_found_flush ();
1357 keyblock_cache_clear (hd);
1362 if (hd->found >= 0 && hd->found < hd->used)
1364 else if (hd->current >= 0 && hd->current < hd->used)
1367 return gpg_error (GPG_ERR_GENERAL);
1369 err = lock_all (hd);
1373 switch (hd->active[idx].type)
1375 case KEYDB_RESOURCE_TYPE_NONE:
1376 err = gpg_error (GPG_ERR_GENERAL); /* oops */
1378 case KEYDB_RESOURCE_TYPE_KEYRING:
1379 err = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
1381 case KEYDB_RESOURCE_TYPE_KEYBOX:
1382 { /* We need to turn our kbnode_t list of packets into a proper
1383 keyblock first. This is required by the OpenPGP key parser
1384 included in the keybox code. Eventually we can change this
1385 kludge to have the caller pass the image. */
1389 err = build_keyblock_image (kb, &iobuf, &sigstatus);
1392 err = keybox_insert_keyblock (hd->active[idx].u.kb,
1393 iobuf_get_temp_buffer (iobuf),
1394 iobuf_get_temp_length (iobuf),
1397 iobuf_close (iobuf);
1409 keydb_delete_keyblock (KEYDB_HANDLE hd)
1414 return gpg_error (GPG_ERR_INV_ARG);
1416 kid_not_found_flush ();
1417 keyblock_cache_clear (hd);
1419 if (hd->found < 0 || hd->found >= hd->used)
1420 return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
1429 switch (hd->active[hd->found].type)
1431 case KEYDB_RESOURCE_TYPE_NONE:
1432 rc = gpg_error (GPG_ERR_GENERAL);
1434 case KEYDB_RESOURCE_TYPE_KEYRING:
1435 rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
1437 case KEYDB_RESOURCE_TYPE_KEYBOX:
1438 rc = keybox_delete (hd->active[hd->found].u.kb);
1449 keydb_locate_writable (KEYDB_HANDLE hd)
1454 return GPG_ERR_INV_ARG;
1456 rc = keydb_search_reset (hd); /* this does reset hd->current */
1460 /* If we have a primary set, try that one first */
1461 if (primary_keyring)
1463 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
1465 if(hd->active[hd->current].token==primary_keyring)
1467 if(keyring_is_writable (hd->active[hd->current].token))
1474 rc = keydb_search_reset (hd); /* this does reset hd->current */
1479 for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
1481 switch (hd->active[hd->current].type)
1483 case KEYDB_RESOURCE_TYPE_NONE:
1486 case KEYDB_RESOURCE_TYPE_KEYRING:
1487 if (keyring_is_writable (hd->active[hd->current].token))
1488 return 0; /* found (hd->current is set to it) */
1490 case KEYDB_RESOURCE_TYPE_KEYBOX:
1491 if (keybox_is_writable (hd->active[hd->current].token))
1492 return 0; /* found (hd->current is set to it) */
1497 return gpg_error (GPG_ERR_NOT_FOUND);
1501 keydb_rebuild_caches (int noisy)
1505 for (i=0; i < used_resources; i++)
1507 if (!keyring_is_writable (all_resources[i].token))
1509 switch (all_resources[i].type)
1511 case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
1513 case KEYDB_RESOURCE_TYPE_KEYRING:
1514 rc = keyring_rebuild_cache (all_resources[i].token,noisy);
1516 log_error (_("failed to rebuild keyring cache: %s\n"),
1519 case KEYDB_RESOURCE_TYPE_KEYBOX:
1528 keydb_get_skipped_counter (KEYDB_HANDLE hd)
1530 return hd ? hd->skipped_long_blobs : 0;
1535 keydb_search_reset (KEYDB_HANDLE hd)
1541 return gpg_error (GPG_ERR_INV_ARG);
1543 keyblock_cache_clear (hd);
1546 log_clock ("keydb_search_reset");
1549 log_debug ("keydb_search: reset (hd=%p)", hd);
1551 hd->skipped_long_blobs = 0;
1554 /* Now reset all resources. */
1555 for (i=0; !rc && i < hd->used; i++)
1557 switch (hd->active[i].type)
1559 case KEYDB_RESOURCE_TYPE_NONE:
1561 case KEYDB_RESOURCE_TYPE_KEYRING:
1562 rc = keyring_search_reset (hd->active[i].u.kr);
1564 case KEYDB_RESOURCE_TYPE_KEYBOX:
1565 rc = keybox_search_reset (hd->active[i].u.kb);
1575 dump_search_desc (KEYDB_HANDLE hd, const char *text,
1576 KEYDB_SEARCH_DESC *desc, size_t ndesc)
1581 for (n=0; n < ndesc; n++)
1583 switch (desc[n].mode)
1585 case KEYDB_SEARCH_MODE_NONE: s = "none"; break;
1586 case KEYDB_SEARCH_MODE_EXACT: s = "exact"; break;
1587 case KEYDB_SEARCH_MODE_SUBSTR: s = "substr"; break;
1588 case KEYDB_SEARCH_MODE_MAIL: s = "mail"; break;
1589 case KEYDB_SEARCH_MODE_MAILSUB: s = "mailsub"; break;
1590 case KEYDB_SEARCH_MODE_MAILEND: s = "mailend"; break;
1591 case KEYDB_SEARCH_MODE_WORDS: s = "words"; break;
1592 case KEYDB_SEARCH_MODE_SHORT_KID: s = "short_kid"; break;
1593 case KEYDB_SEARCH_MODE_LONG_KID: s = "long_kid"; break;
1594 case KEYDB_SEARCH_MODE_FPR16: s = "fpr16"; break;
1595 case KEYDB_SEARCH_MODE_FPR20: s = "fpr20"; break;
1596 case KEYDB_SEARCH_MODE_FPR: s = "fpr"; break;
1597 case KEYDB_SEARCH_MODE_ISSUER: s = "issuer"; break;
1598 case KEYDB_SEARCH_MODE_ISSUER_SN: s = "issuer_sn"; break;
1599 case KEYDB_SEARCH_MODE_SN: s = "sn"; break;
1600 case KEYDB_SEARCH_MODE_SUBJECT: s = "subject"; break;
1601 case KEYDB_SEARCH_MODE_KEYGRIP: s = "keygrip"; break;
1602 case KEYDB_SEARCH_MODE_FIRST: s = "first"; break;
1603 case KEYDB_SEARCH_MODE_NEXT: s = "next"; break;
1604 default: s = "?"; break;
1607 log_debug ("%s: mode=%s (hd=%p)", text, s, hd);
1609 log_debug ("%*s mode=%s", (int)strlen (text), "", s);
1610 if (desc[n].mode == KEYDB_SEARCH_MODE_LONG_KID)
1611 log_printf (" %08lX%08lX", (unsigned long)desc[n].u.kid[0],
1612 (unsigned long)desc[n].u.kid[1]);
1613 else if (desc[n].mode == KEYDB_SEARCH_MODE_SHORT_KID)
1614 log_printf (" %08lX", (unsigned long)desc[n].u.kid[1]);
1615 else if (desc[n].mode == KEYDB_SEARCH_MODE_SUBSTR)
1616 log_printf (" '%s'", desc[n].u.name);
1622 keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
1623 size_t ndesc, size_t *descindex)
1626 int was_reset = hd->is_reset;
1627 /* If an entry is already in the cache, then don't add it again. */
1628 int already_in_cache = 0;
1631 *descindex = 0; /* Make sure it is always set on return. */
1634 return gpg_error (GPG_ERR_INV_ARG);
1637 log_clock ("keydb_search enter");
1640 dump_search_desc (hd, "keydb_search", desc, ndesc);
1643 if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID
1644 && (already_in_cache = kid_not_found_p (desc[0].u.kid)) == 1 )
1647 log_clock ("keydb_search leave (not found, cached)");
1648 return gpg_error (GPG_ERR_NOT_FOUND);
1651 /* NB: If one of the exact search modes below is used in a loop to
1652 walk over all keys (with the same fingerprint) the caching must
1653 have been disabled for the handle. */
1656 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
1657 || desc[0].mode == KEYDB_SEARCH_MODE_FPR)
1658 && hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED
1659 && !memcmp (hd->keyblock_cache.fpr, desc[0].u.fpr, 20))
1661 /* (DESCINDEX is already set). */
1663 log_clock ("keydb_search leave (cached)");
1668 while ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1669 && hd->current >= 0 && hd->current < hd->used)
1671 switch (hd->active[hd->current].type)
1673 case KEYDB_RESOURCE_TYPE_NONE:
1674 BUG(); /* we should never see it here */
1676 case KEYDB_RESOURCE_TYPE_KEYRING:
1677 rc = keyring_search (hd->active[hd->current].u.kr, desc,
1680 case KEYDB_RESOURCE_TYPE_KEYBOX:
1681 rc = keybox_search (hd->active[hd->current].u.kb, desc,
1682 ndesc, KEYBOX_BLOBTYPE_PGP,
1683 descindex, &hd->skipped_long_blobs);
1686 if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1688 /* EOF -> switch to next resource */
1692 hd->found = hd->current;
1696 rc = ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
1697 ? gpg_error (GPG_ERR_NOT_FOUND)
1700 keyblock_cache_clear (hd);
1703 && ndesc == 1 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
1704 || desc[0].mode == KEYDB_SEARCH_MODE_FPR))
1706 hd->keyblock_cache.state = KEYBLOCK_CACHE_PREPARED;
1707 memcpy (hd->keyblock_cache.fpr, desc[0].u.fpr, 20);
1710 if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND
1711 && ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID && was_reset
1712 && !already_in_cache)
1713 kid_not_found_insert (desc[0].u.kid);
1716 log_clock (rc? "keydb_search leave (not found)"
1717 : "keydb_search leave (found)");
1723 keydb_search_first (KEYDB_HANDLE hd)
1726 KEYDB_SEARCH_DESC desc;
1728 err = keydb_search_reset (hd);
1732 memset (&desc, 0, sizeof desc);
1733 desc.mode = KEYDB_SEARCH_MODE_FIRST;
1734 err = keydb_search (hd, &desc, 1, NULL);
1735 if (gpg_err_code (err) == GPG_ERR_LEGACY_KEY)
1736 err = keydb_search_next (hd);
1742 keydb_search_next (KEYDB_HANDLE hd)
1745 KEYDB_SEARCH_DESC desc;
1749 memset (&desc, 0, sizeof desc);
1750 desc.mode = KEYDB_SEARCH_MODE_NEXT;
1751 err = keydb_search (hd, &desc, 1, NULL);
1753 while (gpg_err_code (err) == GPG_ERR_LEGACY_KEY);
1759 keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
1761 KEYDB_SEARCH_DESC desc;
1763 memset (&desc, 0, sizeof desc);
1764 desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
1765 desc.u.kid[0] = kid[0];
1766 desc.u.kid[1] = kid[1];
1767 return keydb_search (hd, &desc, 1, NULL);
1771 keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
1774 KEYDB_SEARCH_DESC desc;
1776 memset (&desc, 0, sizeof desc);
1777 desc.mode = KEYDB_SEARCH_MODE_FPR;
1778 memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
1781 err = keydb_search (hd, &desc, 1, NULL);
1783 while (gpg_err_code (err) == GPG_ERR_LEGACY_KEY);