chiark / gitweb /
gpg: Fix attempt to double free an UID structure.
[gnupg2.git] / g10 / getkey.c
1 /* getkey.c -  Get a key from the database
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2007, 2008, 2010  Free Software Foundation, Inc.
4  * Copyright (C) 2015, 2016 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27
28 #include "gpg.h"
29 #include "util.h"
30 #include "packet.h"
31 #include "iobuf.h"
32 #include "keydb.h"
33 #include "options.h"
34 #include "main.h"
35 #include "trustdb.h"
36 #include "i18n.h"
37 #include "keyserver-internal.h"
38 #include "call-agent.h"
39 #include "host2net.h"
40 #include "mbox-util.h"
41 #include "status.h"
42
43 #define MAX_PK_CACHE_ENTRIES   PK_UID_CACHE_SIZE
44 #define MAX_UID_CACHE_ENTRIES  PK_UID_CACHE_SIZE
45
46 #if MAX_PK_CACHE_ENTRIES < 2
47 #error We need the cache for key creation
48 #endif
49
50 /* Flags values returned by the lookup code.  Note that the values are
51  * directly used by the KEY_CONSIDERED status line.  */
52 #define LOOKUP_NOT_SELECTED        (1<<0)
53 #define LOOKUP_ALL_SUBKEYS_EXPIRED (1<<1)  /* or revoked */
54
55
56 /* A context object used by the lookup functions.  */
57 struct getkey_ctx_s
58 {
59   /* Part of the search criteria: whether the search is an exact
60      search or not.  A search that is exact requires that a key or
61      subkey meet all of the specified criteria.  A search that is not
62      exact allows selecting a different key or subkey from the
63      keyblock that matched the critera.  Further, an exact search
64      returns the key or subkey that matched whereas a non-exact search
65      typically returns the primary key.  See finish_lookup for
66      details.  */
67   int exact;
68
69   /* Part of the search criteria: Whether the caller only wants keys
70      with an available secret key.  This is used by getkey_next to get
71      the next result with the same initial criteria.  */
72   int want_secret;
73
74   /* Part of the search criteria: The type of the requested key.  A
75      mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.
76      If non-zero, then for a key to match, it must implement one of
77      the required uses.  */
78   int req_usage;
79
80   /* The database handle.  */
81   KEYDB_HANDLE kr_handle;
82
83   /* Whether we should call xfree() on the context when the context is
84      released using getkey_end()).  */
85   int not_allocated;
86
87   /* This variable is used as backing store for strings which have
88      their address used in ITEMS.  */
89   strlist_t extra_list;
90
91   /* Part of the search criteria: The low-level search specification
92      as passed to keydb_search.  */
93   int nitems;
94   /* This must be the last element in the structure.  When we allocate
95      the structure, we allocate it so that ITEMS can hold NITEMS.  */
96   KEYDB_SEARCH_DESC items[1];
97 };
98
99 #if 0
100 static struct
101 {
102   int any;
103   int okay_count;
104   int nokey_count;
105   int error_count;
106 } lkup_stats[21];
107 #endif
108
109 typedef struct keyid_list
110 {
111   struct keyid_list *next;
112   char fpr[MAX_FINGERPRINT_LEN];
113   u32 keyid[2];
114 } *keyid_list_t;
115
116
117 #if MAX_PK_CACHE_ENTRIES
118 typedef struct pk_cache_entry
119 {
120   struct pk_cache_entry *next;
121   u32 keyid[2];
122   PKT_public_key *pk;
123 } *pk_cache_entry_t;
124 static pk_cache_entry_t pk_cache;
125 static int pk_cache_entries;    /* Number of entries in pk cache.  */
126 static int pk_cache_disabled;
127 #endif
128
129 #if MAX_UID_CACHE_ENTRIES < 5
130 #error we really need the userid cache
131 #endif
132 typedef struct user_id_db
133 {
134   struct user_id_db *next;
135   keyid_list_t keyids;
136   int len;
137   char name[1];
138 } *user_id_db_t;
139 static user_id_db_t user_id_db;
140 static int uid_cache_entries;   /* Number of entries in uid cache. */
141
142 static void merge_selfsigs (kbnode_t keyblock);
143 static int lookup (getkey_ctx_t ctx,
144                    kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
145                    int want_secret);
146 static kbnode_t finish_lookup (kbnode_t keyblock,
147                                unsigned int req_usage, int want_exact,
148                                unsigned int *r_flags);
149 static void print_status_key_considered (kbnode_t keyblock, unsigned int flags);
150
151
152 #if 0
153 static void
154 print_stats ()
155 {
156   int i;
157   for (i = 0; i < DIM (lkup_stats); i++)
158     {
159       if (lkup_stats[i].any)
160         es_fprintf (es_stderr,
161                  "lookup stats: mode=%-2d  ok=%-6d  nokey=%-6d  err=%-6d\n",
162                  i,
163                  lkup_stats[i].okay_count,
164                  lkup_stats[i].nokey_count, lkup_stats[i].error_count);
165     }
166 }
167 #endif
168
169
170 /* Cache a copy of a public key in the public key cache.  PK is not
171  * cached if caching is disabled (via getkey_disable_caches), if
172  * PK->FLAGS.DONT_CACHE is set, we don't know how to derive a key id
173  * from the public key (e.g., unsupported algorithm), or a key with
174  * the key id is already in the cache.
175  *
176  * The public key packet is copied into the cache using
177  * copy_public_key.  Thus, any secret parts are not copied, for
178  * instance.
179  *
180  * This cache is filled by get_pubkey and is read by get_pubkey and
181  * get_pubkey_fast.  */
182 void
183 cache_public_key (PKT_public_key * pk)
184 {
185 #if MAX_PK_CACHE_ENTRIES
186   pk_cache_entry_t ce, ce2;
187   u32 keyid[2];
188
189   if (pk_cache_disabled)
190     return;
191
192   if (pk->flags.dont_cache)
193     return;
194
195   if (is_ELGAMAL (pk->pubkey_algo)
196       || pk->pubkey_algo == PUBKEY_ALGO_DSA
197       || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
198       || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
199       || pk->pubkey_algo == PUBKEY_ALGO_ECDH
200       || is_RSA (pk->pubkey_algo))
201     {
202       keyid_from_pk (pk, keyid);
203     }
204   else
205     return; /* Don't know how to get the keyid.  */
206
207   for (ce = pk_cache; ce; ce = ce->next)
208     if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
209       {
210         if (DBG_CACHE)
211           log_debug ("cache_public_key: already in cache\n");
212         return;
213       }
214
215   if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
216     {
217       int n;
218
219       /* Remove the last 50% of the entries.  */
220       for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
221         ce = ce->next;
222       if (ce && ce != pk_cache && ce->next)
223         {
224           ce2 = ce->next;
225           ce->next = NULL;
226           ce = ce2;
227           for (; ce; ce = ce2)
228             {
229               ce2 = ce->next;
230               free_public_key (ce->pk);
231               xfree (ce);
232               pk_cache_entries--;
233             }
234         }
235       log_assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
236     }
237   pk_cache_entries++;
238   ce = xmalloc (sizeof *ce);
239   ce->next = pk_cache;
240   pk_cache = ce;
241   ce->pk = copy_public_key (NULL, pk);
242   ce->keyid[0] = keyid[0];
243   ce->keyid[1] = keyid[1];
244 #endif
245 }
246
247
248 /* Return a const utf-8 string with the text "[User ID not found]".
249    This function is required so that we don't need to switch gettext's
250    encoding temporary.  */
251 static const char *
252 user_id_not_found_utf8 (void)
253 {
254   static char *text;
255
256   if (!text)
257     text = native_to_utf8 (_("[User ID not found]"));
258   return text;
259 }
260
261
262
263 /* Return the user ID from the given keyblock.
264  * We use the primary uid flag which has been set by the merge_selfsigs
265  * function.  The returned value is only valid as long as the given
266  * keyblock is not changed.  */
267 static const char *
268 get_primary_uid (KBNODE keyblock, size_t * uidlen)
269 {
270   KBNODE k;
271   const char *s;
272
273   for (k = keyblock; k; k = k->next)
274     {
275       if (k->pkt->pkttype == PKT_USER_ID
276           && !k->pkt->pkt.user_id->attrib_data
277           && k->pkt->pkt.user_id->is_primary)
278         {
279           *uidlen = k->pkt->pkt.user_id->len;
280           return k->pkt->pkt.user_id->name;
281         }
282     }
283   s = user_id_not_found_utf8 ();
284   *uidlen = strlen (s);
285   return s;
286 }
287
288
289 static void
290 release_keyid_list (keyid_list_t k)
291 {
292   while (k)
293     {
294       keyid_list_t k2 = k->next;
295       xfree (k);
296       k = k2;
297     }
298 }
299
300 /****************
301  * Store the association of keyid and userid
302  * Feed only public keys to this function.
303  */
304 static void
305 cache_user_id (KBNODE keyblock)
306 {
307   user_id_db_t r;
308   const char *uid;
309   size_t uidlen;
310   keyid_list_t keyids = NULL;
311   KBNODE k;
312
313   for (k = keyblock; k; k = k->next)
314     {
315       if (k->pkt->pkttype == PKT_PUBLIC_KEY
316           || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
317         {
318           keyid_list_t a = xmalloc_clear (sizeof *a);
319           /* Hmmm: For a long list of keyids it might be an advantage
320            * to append the keys.  */
321           fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
322           keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
323           /* First check for duplicates.  */
324           for (r = user_id_db; r; r = r->next)
325             {
326               keyid_list_t b;
327
328               for (b = r->keyids; b; b = b->next)
329                 {
330                   if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
331                     {
332                       if (DBG_CACHE)
333                         log_debug ("cache_user_id: already in cache\n");
334                       release_keyid_list (keyids);
335                       xfree (a);
336                       return;
337                     }
338                 }
339             }
340           /* Now put it into the cache.  */
341           a->next = keyids;
342           keyids = a;
343         }
344     }
345   if (!keyids)
346     BUG (); /* No key no fun.  */
347
348
349   uid = get_primary_uid (keyblock, &uidlen);
350
351   if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
352     {
353       /* fixme: use another algorithm to free some cache slots */
354       r = user_id_db;
355       user_id_db = r->next;
356       release_keyid_list (r->keyids);
357       xfree (r);
358       uid_cache_entries--;
359     }
360   r = xmalloc (sizeof *r + uidlen - 1);
361   r->keyids = keyids;
362   r->len = uidlen;
363   memcpy (r->name, uid, r->len);
364   r->next = user_id_db;
365   user_id_db = r;
366   uid_cache_entries++;
367 }
368
369
370 /* Disable and drop the public key cache (which is filled by
371    cache_public_key and get_pubkey).  Note: there is currently no way
372    to reenable this cache.  */
373 void
374 getkey_disable_caches ()
375 {
376 #if MAX_PK_CACHE_ENTRIES
377   {
378     pk_cache_entry_t ce, ce2;
379
380     for (ce = pk_cache; ce; ce = ce2)
381       {
382         ce2 = ce->next;
383         free_public_key (ce->pk);
384         xfree (ce);
385       }
386     pk_cache_disabled = 1;
387     pk_cache_entries = 0;
388     pk_cache = NULL;
389   }
390 #endif
391   /* fixme: disable user id cache ? */
392 }
393
394
395 void
396 pubkey_free (pubkey_t key)
397 {
398   if (key)
399     {
400       xfree (key->pk);
401       release_kbnode (key->keyblock);
402       xfree (key);
403     }
404 }
405
406 void
407 pubkeys_free (pubkey_t keys)
408 {
409   while (keys)
410     {
411       pubkey_t next = keys->next;
412       pubkey_free (keys);
413       keys = next;
414     }
415 }
416
417 /* Returns all keys that match the search specfication SEARCH_TERMS.
418
419    This function also checks for and warns about duplicate entries in
420    the keydb, which can occur if the user has configured multiple
421    keyrings or keyboxes or if a keyring or keybox was corrupted.
422
423    Note: SEARCH_TERMS will not be expanded (i.e., it may not be a
424    group).
425
426    USE is the operation for which the key is required.  It must be
427    either PUBKEY_USAGE_ENC, PUBKEY_USAGE_SIG, PUBKEY_USAGE_CERT or
428    PUBKEY_USAGE_AUTH.
429
430    XXX: Currently, only PUBKEY_USAGE_ENC and PUBKEY_USAGE_SIG are
431    implemented.
432
433    INCLUDE_UNUSABLE indicates whether disabled keys are allowed.
434    (Recipients specified with --encrypt-to and --hidden-encrypt-to may
435    be disabled.  It is possible to edit disabled keys.)
436
437    SOURCE is the context in which SEARCH_TERMS was specified, e.g.,
438    "--encrypt-to", etc.  If this function is called interactively,
439    then this should be NULL.
440
441    If WARN_POSSIBLY_AMBIGUOUS is set, then emits a warning if the user
442    does not specify a long key id or a fingerprint.
443
444    The results are placed in *KEYS.  *KEYS must be NULL!  */
445 gpg_error_t
446 get_pubkeys (ctrl_t ctrl,
447              char *search_terms, int use, int include_unusable, char *source,
448              int warn_possibly_ambiguous,
449              pubkey_t *r_keys)
450 {
451   /* We show a warning when a key appears multiple times in the DB.
452      This can happen for two reasons:
453
454        - The user has configured multiple keyrings or keyboxes.
455
456        - The keyring or keybox has been corrupted in some way, e.g., a
457          bug or a random process changing them.
458
459      For each duplicate, we only want to show the key once.  Hence,
460      this list.  */
461   static strlist_t key_dups;
462
463   /* USE transformed to a string.  */
464   char *use_str;
465
466   gpg_error_t err;
467
468   KEYDB_SEARCH_DESC desc;
469
470   GETKEY_CTX ctx;
471   pubkey_t results = NULL;
472   pubkey_t r;
473
474   int count;
475
476   char fingerprint[2 * MAX_FINGERPRINT_LEN + 1];
477
478   if (DBG_LOOKUP)
479     {
480       log_debug ("\n");
481       log_debug ("%s: Checking %s=%s\n",
482                  __func__, source ? source : "user input", search_terms);
483     }
484
485   if (*r_keys)
486     log_bug ("%s: KEYS should be NULL!\n", __func__);
487
488   switch (use)
489     {
490     case PUBKEY_USAGE_ENC: use_str = "encrypt"; break;
491     case PUBKEY_USAGE_SIG: use_str = "sign"; break;
492     case PUBKEY_USAGE_CERT: use_str = "cetify"; break;
493     case PUBKEY_USAGE_AUTH: use_str = "authentication"; break;
494     default: log_bug ("%s: Bad value for USE (%d)\n", __func__, use);
495     }
496
497   if (use == PUBKEY_USAGE_CERT || use == PUBKEY_USAGE_AUTH)
498     log_bug ("%s: use=%s is unimplemented.\n", __func__, use_str);
499
500   err = classify_user_id (search_terms, &desc, 1);
501   if (err)
502     {
503       log_info (_("key \"%s\" not found: %s\n"),
504                 search_terms, gpg_strerror (err));
505       if (!opt.quiet && source)
506         log_info (_("(check argument of option '%s')\n"), source);
507       goto out;
508     }
509
510   if (warn_possibly_ambiguous
511       && ! (desc.mode == KEYDB_SEARCH_MODE_LONG_KID
512             || desc.mode == KEYDB_SEARCH_MODE_FPR16
513             || desc.mode == KEYDB_SEARCH_MODE_FPR20
514             || desc.mode == KEYDB_SEARCH_MODE_FPR))
515     {
516       log_info (_("Warning: '%s' should be a long key ID or a fingerprint\n"),
517                 search_terms);
518       if (!opt.quiet && source)
519         log_info (_("(check argument of option '%s')\n"), source);
520     }
521
522   /* Gather all of the results.  */
523   ctx = NULL;
524   count = 0;
525   do
526     {
527       PKT_public_key *pk = xmalloc_clear (sizeof *pk);
528       KBNODE kb;
529       pk->req_usage = use;
530
531       if (! ctx)
532         err = get_pubkey_byname (ctrl, &ctx, pk, search_terms, &kb, NULL,
533                                  include_unusable, 1);
534       else
535         err = getkey_next (ctx, pk, &kb);
536
537       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
538         /* No more results.   */
539         {
540           xfree (pk);
541           break;
542         }
543       else if (err)
544         /* An error (other than "not found").  */
545         {
546           log_error (_("error looking up: %s\n"),
547                      gpg_strerror (err));
548           xfree (pk);
549           break;
550         }
551
552       /* Another result!  */
553       count ++;
554
555       r = xmalloc_clear (sizeof (*r));
556       r->pk = pk;
557       r->keyblock = kb;
558       r->next = results;
559       results = r;
560     }
561   while (ctx);
562   getkey_end (ctx);
563
564   if (DBG_LOOKUP)
565     {
566       log_debug ("%s resulted in %d matches.\n", search_terms, count);
567       for (r = results; r; r = r->next)
568         log_debug ("  %s\n",
569                    hexfingerprint (r->keyblock->pkt->pkt.public_key,
570                                    fingerprint, sizeof (fingerprint)));
571     }
572
573   if (! results && gpg_err_code (err) == GPG_ERR_NOT_FOUND)
574     /* No match.  */
575     {
576       if (DBG_LOOKUP)
577         log_debug ("%s: '%s' not found.\n", __func__, search_terms);
578
579       log_info (_("key \"%s\" not found\n"), search_terms);
580       if (!opt.quiet && source)
581         log_info (_("(check argument of option '%s')\n"), source);
582
583       goto out;
584     }
585   else if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
586     /* No more matches.  */
587     ;
588   else if (err)
589     /* Some other error.  An error message was already printed
590        out.  Free RESULTS and continue.  */
591     goto out;
592
593   /* Check for duplicates.  */
594   if (DBG_LOOKUP)
595     log_debug ("%s: Checking results of %s='%s' for dups\n",
596                __func__, source ? source : "user input", search_terms);
597   count = 0;
598   for (r = results; r; r = r->next)
599     {
600       pubkey_t *prevp;
601       pubkey_t next;
602       pubkey_t r2;
603       int dups = 0;
604
605       prevp = &r->next;
606       next = r->next;
607       while ((r2 = next))
608         {
609           if (cmp_public_keys (r->keyblock->pkt->pkt.public_key,
610                                r2->keyblock->pkt->pkt.public_key) != 0)
611             /* Not a dup.  */
612             {
613               prevp = &r2->next;
614               next = r2->next;
615               continue;
616             }
617
618           dups ++;
619           count ++;
620
621           /* Remove R2 from the list.  */
622           *prevp = r2->next;
623           release_kbnode (r2->keyblock);
624           next = r2->next;
625           xfree (r2);
626         }
627
628       if (dups)
629         {
630           hexfingerprint (r->keyblock->pkt->pkt.public_key,
631                           fingerprint, sizeof fingerprint);
632           if (! strlist_find (key_dups, fingerprint))
633             {
634               char fingerprint_formatted[MAX_FORMATTED_FINGERPRINT_LEN + 1];
635
636               log_info (_("Warning: %s appears in the keyring %d times\n"),
637                         format_hexfingerprint (fingerprint,
638                                                fingerprint_formatted,
639                                                sizeof fingerprint_formatted),
640                         1 + dups);
641               add_to_strlist (&key_dups, fingerprint);
642             }
643         }
644     }
645
646   if (DBG_LOOKUP && count)
647     {
648       log_debug ("After removing %d dups:\n", count);
649       for (r = results, count = 0; r; r = r->next)
650         log_debug ("  %d: %s\n",
651                    count,
652                    hexfingerprint (r->keyblock->pkt->pkt.public_key,
653                                    fingerprint, sizeof fingerprint));
654     }
655
656  out:
657   if (err)
658     pubkeys_free (results);
659   else
660     *r_keys = results;
661
662   return err;
663 }
664
665
666 static void
667 pk_from_block (PKT_public_key *pk, kbnode_t keyblock, kbnode_t found_key)
668 {
669   kbnode_t a = found_key ? found_key : keyblock;
670
671   log_assert (a->pkt->pkttype == PKT_PUBLIC_KEY
672               || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
673
674   copy_public_key (pk, a->pkt->pkt.public_key);
675 }
676
677
678 /* Return the public key with the key id KEYID and store it at PK.
679  * The resources in *PK should be released using
680  * release_public_key_parts().  This function also stores a copy of
681  * the public key in the user id cache (see cache_public_key).
682  *
683  * If PK is NULL, this function just stores the public key in the
684  * cache and returns the usual return code.
685  *
686  * PK->REQ_USAGE (which is a mask of PUBKEY_USAGE_SIG,
687  * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT) is passed through to the
688  * lookup function.  If this is non-zero, only keys with the specified
689  * usage will be returned.  As such, it is essential that
690  * PK->REQ_USAGE be correctly initialized!
691  *
692  * Returns 0 on success, GPG_ERR_NO_PUBKEY if there is no public key
693  * with the specified key id, or another error code if an error
694  * occurs.
695  *
696  * If the data was not read from the cache, then the self-signed data
697  * has definitely been merged into the public key using
698  * merge_selfsigs.  */
699 int
700 get_pubkey (PKT_public_key * pk, u32 * keyid)
701 {
702   int internal = 0;
703   int rc = 0;
704
705 #if MAX_PK_CACHE_ENTRIES
706   if (pk)
707     {
708       /* Try to get it from the cache.  We don't do this when pk is
709          NULL as it does not guarantee that the user IDs are
710          cached. */
711       pk_cache_entry_t ce;
712       for (ce = pk_cache; ce; ce = ce->next)
713         {
714           if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
715             /* XXX: We don't check PK->REQ_USAGE here, but if we don't
716                read from the cache, we do check it!  */
717             {
718               copy_public_key (pk, ce->pk);
719               return 0;
720             }
721         }
722     }
723 #endif
724   /* More init stuff.  */
725   if (!pk)
726     {
727       pk = xmalloc_clear (sizeof *pk);
728       internal++;
729     }
730
731
732   /* Do a lookup.  */
733   {
734     struct getkey_ctx_s ctx;
735     KBNODE kb = NULL;
736     KBNODE found_key = NULL;
737     memset (&ctx, 0, sizeof ctx);
738     ctx.exact = 1; /* Use the key ID exactly as given.  */
739     ctx.not_allocated = 1;
740     ctx.kr_handle = keydb_new ();
741     if (!ctx.kr_handle)
742       {
743         rc = gpg_error_from_syserror ();
744         goto leave;
745       }
746     ctx.nitems = 1;
747     ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
748     ctx.items[0].u.kid[0] = keyid[0];
749     ctx.items[0].u.kid[1] = keyid[1];
750     ctx.req_usage = pk->req_usage;
751     rc = lookup (&ctx, &kb, &found_key, 0);
752     if (!rc)
753       {
754         pk_from_block (pk, kb, found_key);
755       }
756     getkey_end (&ctx);
757     release_kbnode (kb);
758   }
759   if (!rc)
760     goto leave;
761
762   rc = GPG_ERR_NO_PUBKEY;
763
764 leave:
765   if (!rc)
766     cache_public_key (pk);
767   if (internal)
768     free_public_key (pk);
769   return rc;
770 }
771
772
773 /* Similar to get_pubkey, but it does not take PK->REQ_USAGE into
774  * account nor does it merge in the self-signed data.  This function
775  * also only considers primary keys.  It is intended to be used as a
776  * quick check of the key to avoid recursion.  It should only be used
777  * in very certain cases.  Like get_pubkey and unlike any of the other
778  * lookup functions, this function also consults the user id cache
779  * (see cache_public_key).
780  *
781  * Return the public key in *PK.  The resources in *PK should be
782  * released using release_public_key_parts().  */
783 int
784 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
785 {
786   int rc = 0;
787   KEYDB_HANDLE hd;
788   KBNODE keyblock;
789   u32 pkid[2];
790
791   log_assert (pk);
792 #if MAX_PK_CACHE_ENTRIES
793   {
794     /* Try to get it from the cache */
795     pk_cache_entry_t ce;
796
797     for (ce = pk_cache; ce; ce = ce->next)
798       {
799         if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
800             /* Only consider primary keys.  */
801             && ce->pk->keyid[0] == ce->pk->main_keyid[0]
802             && ce->pk->keyid[1] == ce->pk->main_keyid[1])
803           {
804             if (pk)
805               copy_public_key (pk, ce->pk);
806             return 0;
807           }
808       }
809   }
810 #endif
811
812   hd = keydb_new ();
813   if (!hd)
814     return gpg_error_from_syserror ();
815   rc = keydb_search_kid (hd, keyid);
816   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
817     {
818       keydb_release (hd);
819       return GPG_ERR_NO_PUBKEY;
820     }
821   rc = keydb_get_keyblock (hd, &keyblock);
822   keydb_release (hd);
823   if (rc)
824     {
825       log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
826       return GPG_ERR_NO_PUBKEY;
827     }
828
829   log_assert (keyblock && keyblock->pkt
830               && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
831
832   /* We return the primary key.  If KEYID matched a subkey, then we
833      return an error.  */
834   keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
835   if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
836     copy_public_key (pk, keyblock->pkt->pkt.public_key);
837   else
838     rc = GPG_ERR_NO_PUBKEY;
839
840   release_kbnode (keyblock);
841
842   /* Not caching key here since it won't have all of the fields
843      properly set. */
844
845   return rc;
846 }
847
848
849 /* Return the key block for the key with key id KEYID or NULL, if an
850  * error occurs.  Use release_kbnode() to release the key block.
851  *
852  * The self-signed data has already been merged into the public key
853  * using merge_selfsigs.  */
854 kbnode_t
855 get_pubkeyblock (u32 * keyid)
856 {
857   struct getkey_ctx_s ctx;
858   int rc = 0;
859   KBNODE keyblock = NULL;
860
861   memset (&ctx, 0, sizeof ctx);
862   /* No need to set exact here because we want the entire block.  */
863   ctx.not_allocated = 1;
864   ctx.kr_handle = keydb_new ();
865   if (!ctx.kr_handle)
866     return NULL;
867   ctx.nitems = 1;
868   ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
869   ctx.items[0].u.kid[0] = keyid[0];
870   ctx.items[0].u.kid[1] = keyid[1];
871   rc = lookup (&ctx, &keyblock, NULL, 0);
872   getkey_end (&ctx);
873
874   return rc ? NULL : keyblock;
875 }
876
877
878 /* Return the public key with the key id KEYID iff the secret key is
879  * available and store it at PK.  The resources should be released
880  * using release_public_key_parts().
881  *
882  * Unlike other lookup functions, PK may not be NULL.  PK->REQ_USAGE
883  * is passed through to the lookup function and is a mask of
884  * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  Thus, it
885  * must be valid!  If this is non-zero, only keys with the specified
886  * usage will be returned.
887  *
888  * Returns 0 on success.  If a public key with the specified key id is
889  * not found or a secret key is not available for that public key, an
890  * error code is returned.  Note: this function ignores legacy keys.
891  * An error code is also return if an error occurs.
892  *
893  * The self-signed data has already been merged into the public key
894  * using merge_selfsigs.  */
895 gpg_error_t
896 get_seckey (PKT_public_key *pk, u32 *keyid)
897 {
898   gpg_error_t err;
899   struct getkey_ctx_s ctx;
900   kbnode_t keyblock = NULL;
901   kbnode_t found_key = NULL;
902
903   memset (&ctx, 0, sizeof ctx);
904   ctx.exact = 1; /* Use the key ID exactly as given.  */
905   ctx.not_allocated = 1;
906   ctx.kr_handle = keydb_new ();
907   if (!ctx.kr_handle)
908     return gpg_error_from_syserror ();
909   ctx.nitems = 1;
910   ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
911   ctx.items[0].u.kid[0] = keyid[0];
912   ctx.items[0].u.kid[1] = keyid[1];
913   ctx.req_usage = pk->req_usage;
914   err = lookup (&ctx, &keyblock, &found_key, 1);
915   if (!err)
916     {
917       pk_from_block (pk, keyblock, found_key);
918     }
919   getkey_end (&ctx);
920   release_kbnode (keyblock);
921
922   if (!err)
923     {
924       err = agent_probe_secret_key (/*ctrl*/NULL, pk);
925       if (err)
926         release_public_key_parts (pk);
927     }
928
929   return err;
930 }
931
932
933 /* Skip unusable keys.  A key is unusable if it is revoked, expired or
934    disabled or if the selected user id is revoked or expired.  */
935 static int
936 skip_unusable (void *dummy, u32 * keyid, int uid_no)
937 {
938   int unusable = 0;
939   KBNODE keyblock;
940   PKT_public_key *pk;
941
942   (void) dummy;
943
944   keyblock = get_pubkeyblock (keyid);
945   if (!keyblock)
946     {
947       log_error ("error checking usability status of %s\n", keystr (keyid));
948       goto leave;
949     }
950
951   pk = keyblock->pkt->pkt.public_key;
952
953   /* Is the key revoked or expired?  */
954   if (pk->flags.revoked || pk->has_expired)
955     unusable = 1;
956
957   /* Is the user ID in question revoked or expired? */
958   if (!unusable && uid_no)
959     {
960       KBNODE node;
961       int uids_seen = 0;
962
963       for (node = keyblock; node; node = node->next)
964         {
965           if (node->pkt->pkttype == PKT_USER_ID)
966             {
967               PKT_user_id *user_id = node->pkt->pkt.user_id;
968
969               uids_seen ++;
970               if (uids_seen != uid_no)
971                 continue;
972
973               if (user_id->is_revoked || user_id->is_expired)
974                 unusable = 1;
975
976               break;
977             }
978         }
979
980       /* If UID_NO is non-zero, then the keyblock better have at least
981          that many UIDs.  */
982       log_assert (uids_seen == uid_no);
983     }
984
985   if (!unusable)
986     unusable = pk_is_disabled (pk);
987
988 leave:
989   release_kbnode (keyblock);
990   return unusable;
991 }
992
993
994 /* Search for keys matching some criteria.
995
996    If RETCTX is not NULL, then the constructed context is returned in
997    *RETCTX so that getpubkey_next can be used to get subsequent
998    results.  In this case, getkey_end() must be used to free the
999    search context.  If RETCTX is not NULL, then RET_KDBHD must be
1000    NULL.
1001
1002    If NAMELIST is not NULL, then a search query is constructed using
1003    classify_user_id on each of the strings in the list.  (Recall: the
1004    database does an OR of the terms, not an AND.)  If NAMELIST is
1005    NULL, then all results are returned.
1006
1007    If PK is not NULL, the public key of the first result is returned
1008    in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
1009    set, it is used to filter the search results.  See the
1010    documentation for finish_lookup to understand exactly how this is
1011    used.  Note: The self-signed data has already been merged into the
1012    public key using merge_selfsigs.  Free *PK by calling
1013    release_public_key_parts (or, if PK was allocated using xfree, you
1014    can use free_public_key, which calls release_public_key_parts(PK)
1015    and then xfree(PK)).
1016
1017    If WANT_SECRET is set, then only keys with an available secret key
1018    (either locally or via key registered on a smartcard) are returned.
1019
1020    If INCLUDE_UNUSABLE is set, then unusable keys (see the
1021    documentation for skip_unusable for an exact definition) are
1022    skipped unless they are looked up by key id or by fingerprint.
1023
1024    If RET_KB is not NULL, the keyblock is returned in *RET_KB.  This
1025    should be freed using release_kbnode().
1026
1027    If RET_KDBHD is not NULL, then the new database handle used to
1028    conduct the search is returned in *RET_KDBHD.  This can be used to
1029    get subsequent results using keydb_search_next.  Note: in this
1030    case, no advanced filtering is done for subsequent results (e.g.,
1031    WANT_SECRET and PK->REQ_USAGE are not respected).
1032
1033    This function returns 0 on success.  Otherwise, an error code is
1034    returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1035    (if want_secret is set) is returned if the key is not found.  */
1036 static int
1037 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
1038             PKT_public_key *pk,
1039             int want_secret, int include_unusable,
1040             KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
1041 {
1042   int rc = 0;
1043   int n;
1044   strlist_t r;
1045   GETKEY_CTX ctx;
1046   KBNODE help_kb = NULL;
1047   KBNODE found_key = NULL;
1048
1049   if (retctx)
1050     {
1051       /* Reset the returned context in case of error.  */
1052       log_assert (!ret_kdbhd); /* Not allowed because the handle is stored
1053                                   in the context.  */
1054       *retctx = NULL;
1055     }
1056   if (ret_kdbhd)
1057     *ret_kdbhd = NULL;
1058
1059   if (!namelist)
1060     /* No search terms: iterate over the whole DB.  */
1061     {
1062       ctx = xmalloc_clear (sizeof *ctx);
1063       ctx->nitems = 1;
1064       ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
1065       if (!include_unusable)
1066         ctx->items[0].skipfnc = skip_unusable;
1067     }
1068   else
1069     {
1070       /* Build the search context.  */
1071       for (n = 0, r = namelist; r; r = r->next)
1072         n++;
1073
1074       /* CTX has space for a single search term at the end.  Thus, we
1075          need to allocate sizeof *CTX plus (n - 1) sizeof
1076          CTX->ITEMS.  */
1077       ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
1078       ctx->nitems = n;
1079
1080       for (n = 0, r = namelist; r; r = r->next, n++)
1081         {
1082           gpg_error_t err;
1083
1084           err = classify_user_id (r->d, &ctx->items[n], 1);
1085
1086           if (ctx->items[n].exact)
1087             ctx->exact = 1;
1088           if (err)
1089             {
1090               xfree (ctx);
1091               return gpg_err_code (err); /* FIXME: remove gpg_err_code.  */
1092             }
1093           if (!include_unusable
1094               && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
1095               && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
1096               && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
1097               && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
1098               && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
1099             ctx->items[n].skipfnc = skip_unusable;
1100         }
1101     }
1102
1103   ctx->want_secret = want_secret;
1104   ctx->kr_handle = keydb_new ();
1105   if (!ctx->kr_handle)
1106     {
1107       rc = gpg_error_from_syserror ();
1108       getkey_end (ctx);
1109       return rc;
1110     }
1111
1112   if (!ret_kb)
1113     ret_kb = &help_kb;
1114
1115   if (pk)
1116     {
1117       ctx->req_usage = pk->req_usage;
1118     }
1119
1120   rc = lookup (ctx, ret_kb, &found_key, want_secret);
1121   if (!rc && pk)
1122     {
1123       pk_from_block (pk, *ret_kb, found_key);
1124     }
1125
1126   release_kbnode (help_kb);
1127
1128   if (retctx) /* Caller wants the context.  */
1129     *retctx = ctx;
1130   else
1131     {
1132       if (ret_kdbhd)
1133         {
1134           *ret_kdbhd = ctx->kr_handle;
1135           ctx->kr_handle = NULL;
1136         }
1137       getkey_end (ctx);
1138     }
1139
1140   return rc;
1141 }
1142
1143
1144 /* Find a public key identified by NAME.
1145  *
1146  * If name appears to be a valid valid RFC822 mailbox (i.e., email
1147  * address) and auto key lookup is enabled (no_akl == 0), then the
1148  * specified auto key lookup methods (--auto-key-lookup) are used to
1149  * import the key into the local keyring.  Otherwise, just the local
1150  * keyring is consulted.
1151  *
1152  * If RETCTX is not NULL, then the constructed context is returned in
1153  * *RETCTX so that getpubkey_next can be used to get subsequent
1154  * results.  In this case, getkey_end() must be used to free the
1155  * search context.  If RETCTX is not NULL, then RET_KDBHD must be
1156  * NULL.
1157  *
1158  * If PK is not NULL, the public key of the first result is returned
1159  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  PK->REQ_USAGE is
1160  * passed through to the lookup function and is a mask of
1161  * PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  If this
1162  * is non-zero, only keys with the specified usage will be returned.
1163  * Note: The self-signed data has already been merged into the public
1164  * key using merge_selfsigs.  Free *PK by calling
1165  * release_public_key_parts (or, if PK was allocated using xfree, you
1166  * can use free_public_key, which calls release_public_key_parts(PK)
1167  * and then xfree(PK)).
1168  *
1169  * NAME is a string, which is turned into a search query using
1170  * classify_user_id.
1171  *
1172  * If RET_KEYBLOCK is not NULL, the keyblock is returned in
1173  * *RET_KEYBLOCK.  This should be freed using release_kbnode().
1174  *
1175  * If RET_KDBHD is not NULL, then the new database handle used to
1176  * conduct the search is returned in *RET_KDBHD.  This can be used to
1177  * get subsequent results using keydb_search_next or to modify the
1178  * returned record.  Note: in this case, no advanced filtering is done
1179  * for subsequent results (e.g., PK->REQ_USAGE is not respected).
1180  * Unlike RETCTX, this is always returned.
1181  *
1182  * If INCLUDE_UNUSABLE is set, then unusable keys (see the
1183  * documentation for skip_unusable for an exact definition) are
1184  * skipped unless they are looked up by key id or by fingerprint.
1185  *
1186  * If NO_AKL is set, then the auto key locate functionality is
1187  * disabled and only the local key ring is considered.  Note: the
1188  * local key ring is consulted even if local is not in the
1189  * --auto-key-locate option list!
1190  *
1191  * This function returns 0 on success.  Otherwise, an error code is
1192  * returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
1193  * (if want_secret is set) is returned if the key is not found.  */
1194 int
1195 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
1196                    const char *name, KBNODE * ret_keyblock,
1197                    KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
1198 {
1199   int rc;
1200   strlist_t namelist = NULL;
1201   struct akl *akl;
1202   int is_mbox;
1203   int nodefault = 0;
1204   int anylocalfirst = 0;
1205
1206   /* If RETCTX is not NULL, then RET_KDBHD must be NULL.  */
1207   log_assert (retctx == NULL || ret_kdbhd == NULL);
1208
1209   if (retctx)
1210     *retctx = NULL;
1211
1212   /* Does NAME appear to be a mailbox (mail address)?  */
1213   is_mbox = is_valid_mailbox (name);
1214
1215   /* The auto-key-locate feature works as follows: there are a number
1216    * of methods to look up keys.  By default, the local keyring is
1217    * tried first.  Then, each method listed in the --auto-key-locate is
1218    * tried in the order it appears.
1219    *
1220    * This can be changed as follows:
1221    *
1222    *   - if nodefault appears anywhere in the list of options, then
1223    *     the local keyring is not tried first, or,
1224    *
1225    *   - if local appears anywhere in the list of options, then the
1226    *     local keyring is not tried first, but in the order in which
1227    *     it was listed in the --auto-key-locate option.
1228    *
1229    * Note: we only save the search context in RETCTX if the local
1230    * method is the first method tried (either explicitly or
1231    * implicitly).  */
1232   if (!no_akl)
1233     {
1234       /* auto-key-locate is enabled.  */
1235
1236       /* nodefault is true if "nodefault" or "local" appear.  */
1237       for (akl = opt.auto_key_locate; akl; akl = akl->next)
1238         if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
1239           {
1240             nodefault = 1;
1241             break;
1242           }
1243       /* anylocalfirst is true if "local" appears before any other
1244          search methods (except "nodefault").  */
1245       for (akl = opt.auto_key_locate; akl; akl = akl->next)
1246         if (akl->type != AKL_NODEFAULT)
1247           {
1248             if (akl->type == AKL_LOCAL)
1249               anylocalfirst = 1;
1250             break;
1251           }
1252     }
1253
1254   if (!nodefault)
1255     {
1256       /* "nodefault" didn't occur.  Thus, "local" is implicitly the
1257        *  first method to try.  */
1258       anylocalfirst = 1;
1259     }
1260
1261   if (nodefault && is_mbox)
1262     {
1263       /* Either "nodefault" or "local" (explicitly) appeared in the
1264        * auto key locate list and NAME appears to be an email address.
1265        * Don't try the local keyring.  */
1266       rc = GPG_ERR_NO_PUBKEY;
1267     }
1268   else
1269     {
1270       /* Either "nodefault" and "local" don't appear in the auto key
1271        * locate list (in which case we try the local keyring first) or
1272        * NAME does not appear to be an email address (in which case we
1273        * only try the local keyring).  In this case, lookup NAME in
1274        * the local keyring.  */
1275       add_to_strlist (&namelist, name);
1276       rc = key_byname (retctx, namelist, pk, 0,
1277                        include_unusable, ret_keyblock, ret_kdbhd);
1278     }
1279
1280   /* If the requested name resembles a valid mailbox and automatic
1281      retrieval has been enabled, we try to import the key. */
1282   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
1283     {
1284       /* NAME wasn't present in the local keyring (or we didn't try
1285        * the local keyring).  Since the auto key locate feature is
1286        * enabled and NAME appears to be an email address, try the auto
1287        * locate feature.  */
1288       for (akl = opt.auto_key_locate; akl; akl = akl->next)
1289         {
1290           unsigned char *fpr = NULL;
1291           size_t fpr_len;
1292           int did_akl_local = 0;
1293           int no_fingerprint = 0;
1294           const char *mechanism = "?";
1295
1296           switch (akl->type)
1297             {
1298             case AKL_NODEFAULT:
1299               /* This is a dummy mechanism.  */
1300               mechanism = "None";
1301               rc = GPG_ERR_NO_PUBKEY;
1302               break;
1303
1304             case AKL_LOCAL:
1305               mechanism = "Local";
1306               did_akl_local = 1;
1307               if (retctx)
1308                 {
1309                   getkey_end (*retctx);
1310                   *retctx = NULL;
1311                 }
1312               add_to_strlist (&namelist, name);
1313               rc = key_byname (anylocalfirst ? retctx : NULL,
1314                                namelist, pk, 0,
1315                                include_unusable, ret_keyblock, ret_kdbhd);
1316               break;
1317
1318             case AKL_CERT:
1319               mechanism = "DNS CERT";
1320               glo_ctrl.in_auto_key_retrieve++;
1321               rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
1322               glo_ctrl.in_auto_key_retrieve--;
1323               break;
1324
1325             case AKL_PKA:
1326               mechanism = "PKA";
1327               glo_ctrl.in_auto_key_retrieve++;
1328               rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
1329               glo_ctrl.in_auto_key_retrieve--;
1330               break;
1331
1332             case AKL_DANE:
1333               mechanism = "DANE";
1334               glo_ctrl.in_auto_key_retrieve++;
1335               rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
1336               glo_ctrl.in_auto_key_retrieve--;
1337               break;
1338
1339             case AKL_WKD:
1340               mechanism = "WKD";
1341               glo_ctrl.in_auto_key_retrieve++;
1342               rc = keyserver_import_wkd (ctrl, name, 0, &fpr, &fpr_len);
1343               glo_ctrl.in_auto_key_retrieve--;
1344               break;
1345
1346             case AKL_LDAP:
1347               mechanism = "LDAP";
1348               glo_ctrl.in_auto_key_retrieve++;
1349               rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
1350               glo_ctrl.in_auto_key_retrieve--;
1351               break;
1352
1353             case AKL_KEYSERVER:
1354               /* Strictly speaking, we don't need to only use a valid
1355                * mailbox for the getname search, but it helps cut down
1356                * on the problem of searching for something like "john"
1357                * and getting a whole lot of keys back. */
1358               if (keyserver_any_configured (ctrl))
1359                 {
1360                   mechanism = "keyserver";
1361                   glo_ctrl.in_auto_key_retrieve++;
1362                   rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
1363                                               opt.keyserver);
1364                   glo_ctrl.in_auto_key_retrieve--;
1365                 }
1366               else
1367                 {
1368                   mechanism = "Unconfigured keyserver";
1369                   rc = GPG_ERR_NO_PUBKEY;
1370                 }
1371               break;
1372
1373             case AKL_SPEC:
1374               {
1375                 struct keyserver_spec *keyserver;
1376
1377                 mechanism = akl->spec->uri;
1378                 keyserver = keyserver_match (akl->spec);
1379                 glo_ctrl.in_auto_key_retrieve++;
1380                 rc = keyserver_import_name (ctrl,
1381                                             name, &fpr, &fpr_len, keyserver);
1382                 glo_ctrl.in_auto_key_retrieve--;
1383               }
1384               break;
1385             }
1386
1387           /* Use the fingerprint of the key that we actually fetched.
1388            * This helps prevent problems where the key that we fetched
1389            * doesn't have the same name that we used to fetch it.  In
1390            * the case of CERT and PKA, this is an actual security
1391            * requirement as the URL might point to a key put in by an
1392            * attacker.  By forcing the use of the fingerprint, we
1393            * won't use the attacker's key here. */
1394           if (!rc && fpr)
1395             {
1396               char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
1397
1398               log_assert (fpr_len <= MAX_FINGERPRINT_LEN);
1399
1400               free_strlist (namelist);
1401               namelist = NULL;
1402
1403               bin2hex (fpr, fpr_len, fpr_string);
1404
1405               if (opt.verbose)
1406                 log_info ("auto-key-locate found fingerprint %s\n",
1407                           fpr_string);
1408
1409               add_to_strlist (&namelist, fpr_string);
1410             }
1411           else if (!rc && !fpr && !did_akl_local)
1412             { /* The acquisition method said no failure occurred, but
1413                * it didn't return a fingerprint.  That's a failure.  */
1414               no_fingerprint = 1;
1415               rc = GPG_ERR_NO_PUBKEY;
1416             }
1417           xfree (fpr);
1418           fpr = NULL;
1419
1420           if (!rc && !did_akl_local)
1421             { /* There was no error and we didn't do a local lookup.
1422                * This means that we imported a key into the local
1423                * keyring.  Try to read the imported key from the
1424                * keyring.  */
1425               if (retctx)
1426                 {
1427                   getkey_end (*retctx);
1428                   *retctx = NULL;
1429                 }
1430               rc = key_byname (anylocalfirst ? retctx : NULL,
1431                                namelist, pk, 0,
1432                                include_unusable, ret_keyblock, ret_kdbhd);
1433             }
1434           if (!rc)
1435             {
1436               /* Key found.  */
1437               log_info (_("automatically retrieved '%s' via %s\n"),
1438                         name, mechanism);
1439               break;
1440             }
1441           if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1442               || opt.verbose || no_fingerprint)
1443             log_info (_("error retrieving '%s' via %s: %s\n"),
1444                       name, mechanism,
1445                       no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1446         }
1447     }
1448
1449
1450   if (rc && retctx)
1451     {
1452       getkey_end (*retctx);
1453       *retctx = NULL;
1454     }
1455
1456   if (retctx && *retctx)
1457     {
1458       log_assert (!(*retctx)->extra_list);
1459       (*retctx)->extra_list = namelist;
1460     }
1461   else
1462     free_strlist (namelist);
1463
1464   return rc;
1465 }
1466
1467
1468 \f
1469
1470 /* Comparison machinery for get_best_pubkey_byname.  */
1471
1472 /* First we have a struct to cache computed information about the key
1473  * in question.  */
1474 struct pubkey_cmp_cookie
1475 {
1476   int valid;                    /* Is this cookie valid?  */
1477   PKT_public_key key;           /* The key.  */
1478   PKT_user_id *uid;             /* The matching UID packet.  */
1479   unsigned int validity;        /* Computed validity of (KEY, UID).  */
1480   u32 creation_time;            /* Creation time of the newest subkey
1481                                    capable of encryption.  */
1482 };
1483
1484
1485 /* Then we have a series of helper functions.  */
1486 static int
1487 key_is_ok (const PKT_public_key *key)
1488 {
1489   return (! key->has_expired && ! key->flags.revoked
1490           && key->flags.valid && ! key->flags.disabled);
1491 }
1492
1493
1494 static int
1495 uid_is_ok (const PKT_public_key *key, const PKT_user_id *uid)
1496 {
1497   return key_is_ok (key) && ! uid->is_revoked;
1498 }
1499
1500
1501 static int
1502 subkey_is_ok (const PKT_public_key *sub)
1503 {
1504   return ! sub->flags.revoked && sub->flags.valid && ! sub->flags.disabled;
1505 }
1506
1507
1508 /* Finally this function compares a NEW key to the former candidate
1509  * OLD.  Returns < 0 if the old key is worse, > 0 if the old key is
1510  * better, == 0 if it is a tie.  */
1511 static int
1512 pubkey_cmp (ctrl_t ctrl, const char *name, struct pubkey_cmp_cookie *old,
1513             struct pubkey_cmp_cookie *new, KBNODE new_keyblock)
1514 {
1515   kbnode_t n;
1516
1517   new->creation_time = 0;
1518   for (n = find_next_kbnode (new_keyblock, PKT_PUBLIC_SUBKEY);
1519        n; n = find_next_kbnode (n, PKT_PUBLIC_SUBKEY))
1520     {
1521       PKT_public_key *sub = n->pkt->pkt.public_key;
1522
1523       if ((sub->pubkey_usage & PUBKEY_USAGE_ENC) == 0)
1524         continue;
1525
1526       if (! subkey_is_ok (sub))
1527         continue;
1528
1529       if (sub->timestamp > new->creation_time)
1530         new->creation_time = sub->timestamp;
1531     }
1532
1533   for (n = find_next_kbnode (new_keyblock, PKT_USER_ID);
1534        n; n = find_next_kbnode (n, PKT_USER_ID))
1535     {
1536       PKT_user_id *uid = n->pkt->pkt.user_id;
1537       char *mbox = mailbox_from_userid (uid->name);
1538       int match = mbox ? strcasecmp (name, mbox) == 0 : 0;
1539
1540       xfree (mbox);
1541       if (! match)
1542         continue;
1543
1544       new->uid = scopy_user_id (uid);
1545       new->validity =
1546         get_validity (ctrl, new_keyblock, &new->key, uid, NULL, 0) & TRUST_MASK;
1547       new->valid = 1;
1548
1549       if (! old->valid)
1550         return -1;      /* No OLD key.  */
1551
1552       if (! uid_is_ok (&old->key, old->uid) && uid_is_ok (&new->key, uid))
1553         return -1;      /* Validity of the NEW key is better.  */
1554
1555       if (old->validity < new->validity)
1556         return -1;      /* Validity of the NEW key is better.  */
1557
1558       if (old->validity == new->validity && uid_is_ok (&new->key, uid)
1559           && old->creation_time < new->creation_time)
1560         return -1;      /* Both keys are of the same validity, but the
1561                            NEW key is newer.  */
1562     }
1563
1564   /* Stick with the OLD key.  */
1565   return 1;
1566 }
1567
1568
1569 /* This function works like get_pubkey_byname, but if the name
1570  * resembles a mail address, the results are ranked and only the best
1571  * result is returned.  */
1572 int
1573 get_best_pubkey_byname (ctrl_t ctrl, GETKEY_CTX *retctx, PKT_public_key *pk,
1574                         const char *name, KBNODE *ret_keyblock,
1575                         int include_unusable, int no_akl)
1576 {
1577   int rc;
1578   struct getkey_ctx_s *ctx = NULL;
1579
1580   if (retctx)
1581     *retctx = NULL;
1582
1583   rc = get_pubkey_byname (ctrl, &ctx, pk, name, ret_keyblock,
1584                           NULL, include_unusable, no_akl);
1585   if (rc)
1586     {
1587       if (ctx)
1588         getkey_end (ctx);
1589       return rc;
1590     }
1591
1592   if (is_valid_mailbox (name) && ctx)
1593     {
1594       /* Rank results and return only the most relevant key.  */
1595       struct pubkey_cmp_cookie best = { 0 };
1596       struct pubkey_cmp_cookie new;
1597       kbnode_t new_keyblock;
1598
1599       while (getkey_next (ctx, &new.key, &new_keyblock) == 0)
1600         {
1601           int diff = pubkey_cmp (ctrl, name, &best, &new, new_keyblock);
1602           release_kbnode (new_keyblock);
1603           if (diff < 0)
1604             {
1605               /* New key is better.  */
1606               release_public_key_parts (&best.key);
1607               free_user_id (best.uid);
1608               best = new;
1609             }
1610           else if (diff > 0)
1611             {
1612               /* Old key is better.  */
1613               release_public_key_parts (&new.key);
1614               free_user_id (new.uid);
1615               new.uid = NULL;
1616             }
1617           else
1618             {
1619               /* A tie.  Keep the old key.  */
1620               release_public_key_parts (&new.key);
1621               free_user_id (new.uid);
1622               new.uid = NULL;
1623             }
1624         }
1625       getkey_end (ctx);
1626       ctx = NULL;
1627       free_user_id (best.uid);
1628       best.uid = NULL;
1629
1630       if (best.valid)
1631         {
1632           if (retctx || ret_keyblock)
1633             {
1634               ctx = xtrycalloc (1, sizeof **retctx);
1635               if (! ctx)
1636                 rc = gpg_error_from_syserror ();
1637               else
1638                 {
1639                   ctx->kr_handle = keydb_new ();
1640                   if (! ctx->kr_handle)
1641                     {
1642                       xfree (ctx);
1643                       *retctx = NULL;
1644                       rc = gpg_error_from_syserror ();
1645                     }
1646                   else
1647                     {
1648                       u32 *keyid = pk_keyid (&best.key);
1649                       ctx->exact = 1;
1650                       ctx->nitems = 1;
1651                       ctx->items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
1652                       ctx->items[0].u.kid[0] = keyid[0];
1653                       ctx->items[0].u.kid[1] = keyid[1];
1654
1655                       if (ret_keyblock)
1656                         {
1657                           release_kbnode (*ret_keyblock);
1658                           *ret_keyblock = NULL;
1659                           rc = getkey_next (ctx, NULL, ret_keyblock);
1660                         }
1661                     }
1662                 }
1663             }
1664
1665           if (pk)
1666             *pk = best.key;
1667           else
1668             release_public_key_parts (&best.key);
1669         }
1670     }
1671
1672   if (rc && ctx)
1673     {
1674       getkey_end (ctx);
1675       ctx = NULL;
1676     }
1677
1678   if (retctx && ctx)
1679     *retctx = ctx;
1680   else
1681     getkey_end (ctx);
1682
1683   return rc;
1684 }
1685
1686 \f
1687
1688 /* Get a public key from a file.
1689  *
1690  * PK is the buffer to store the key.  The caller needs to make sure
1691  * that PK->REQ_USAGE is valid.  PK->REQ_USAGE is passed through to
1692  * the lookup function and is a mask of PUBKEY_USAGE_SIG,
1693  * PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.  If this is non-zero, only
1694  * keys with the specified usage will be returned.
1695  *
1696  * FNAME is the file name.  That file should contain exactly one
1697  * keyblock.
1698  *
1699  * This function returns 0 on success.  Otherwise, an error code is
1700  * returned.  In particular, GPG_ERR_NO_PUBKEY is returned if the key
1701  * is not found.
1702  *
1703  * The self-signed data has already been merged into the public key
1704  * using merge_selfsigs.  The caller must release the content of PK by
1705  * calling release_public_key_parts (or, if PK was malloced, using
1706  * free_public_key).
1707  */
1708 gpg_error_t
1709 get_pubkey_fromfile (ctrl_t ctrl, PKT_public_key *pk, const char *fname)
1710 {
1711   gpg_error_t err;
1712   kbnode_t keyblock;
1713   kbnode_t found_key;
1714   unsigned int infoflags;
1715
1716   err = read_key_from_file (ctrl, fname, &keyblock);
1717   if (!err)
1718     {
1719       /* Warning: node flag bits 0 and 1 should be preserved by
1720        * merge_selfsigs.  FIXME: Check whether this still holds. */
1721       merge_selfsigs (keyblock);
1722       found_key = finish_lookup (keyblock, pk->req_usage, 0, &infoflags);
1723       print_status_key_considered (keyblock, infoflags);
1724       if (found_key)
1725         pk_from_block (pk, keyblock, found_key);
1726       else
1727         err = gpg_error (GPG_ERR_UNUSABLE_PUBKEY);
1728     }
1729
1730   release_kbnode (keyblock);
1731   return err;
1732 }
1733
1734
1735 /* Lookup a key with the specified fingerprint.
1736  *
1737  * If PK is not NULL, the public key of the first result is returned
1738  * in *PK.  Note: this function does an exact search and thus the
1739  * returned public key may be a subkey rather than the primary key.
1740  * Note: The self-signed data has already been merged into the public
1741  * key using merge_selfsigs.  Free *PK by calling
1742  * release_public_key_parts (or, if PK was allocated using xfree, you
1743  * can use free_public_key, which calls release_public_key_parts(PK)
1744  * and then xfree(PK)).
1745  *
1746  * If PK->REQ_USAGE is set, it is used to filter the search results.
1747  * (Thus, if PK is not NULL, PK->REQ_USAGE must be valid!!!)  See the
1748  * documentation for finish_lookup to understand exactly how this is
1749  * used.
1750  *
1751  * If R_KEYBLOCK is not NULL, then the first result's keyblock is
1752  * returned in *R_KEYBLOCK.  This should be freed using
1753  * release_kbnode().
1754  *
1755  * FPRINT is a byte array whose contents is the fingerprint to use as
1756  * the search term.  FPRINT_LEN specifies the length of the
1757  * fingerprint (in bytes).  Currently, only 16 and 20-byte
1758  * fingerprints are supported.
1759  *
1760  * FIXME: We should replace this with the _byname function.  This can
1761  * be done by creating a userID conforming to the unified fingerprint
1762  * style.  */
1763 int
1764 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
1765                      const byte * fprint, size_t fprint_len)
1766 {
1767   int rc;
1768
1769   if (r_keyblock)
1770     *r_keyblock = NULL;
1771
1772   if (fprint_len == 20 || fprint_len == 16)
1773     {
1774       struct getkey_ctx_s ctx;
1775       KBNODE kb = NULL;
1776       KBNODE found_key = NULL;
1777
1778       memset (&ctx, 0, sizeof ctx);
1779       ctx.exact = 1;
1780       ctx.not_allocated = 1;
1781       ctx.kr_handle = keydb_new ();
1782       if (!ctx.kr_handle)
1783         return gpg_error_from_syserror ();
1784
1785       ctx.nitems = 1;
1786       ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1787         : KEYDB_SEARCH_MODE_FPR20;
1788       memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1789       rc = lookup (&ctx, &kb, &found_key, 0);
1790       if (!rc && pk)
1791         pk_from_block (pk, kb, found_key);
1792       if (!rc && r_keyblock)
1793         {
1794           *r_keyblock = kb;
1795           kb = NULL;
1796         }
1797       release_kbnode (kb);
1798       getkey_end (&ctx);
1799     }
1800   else
1801     rc = GPG_ERR_GENERAL; /* Oops */
1802   return rc;
1803 }
1804
1805
1806 /* This function is similar to get_pubkey_byfprint, but it doesn't
1807  * merge the self-signed data into the public key and subkeys or into
1808  * the user ids.  It also doesn't add the key to the user id cache.
1809  * Further, this function ignores PK->REQ_USAGE.
1810  *
1811  * This function is intended to avoid recursion and, as such, should
1812  * only be used in very specific situations.
1813  *
1814  * Like get_pubkey_byfprint, PK may be NULL.  In that case, this
1815  * function effectively just checks for the existence of the key.  */
1816 int
1817 get_pubkey_byfprint_fast (PKT_public_key * pk,
1818                           const byte * fprint, size_t fprint_len)
1819 {
1820   int rc = 0;
1821   KEYDB_HANDLE hd;
1822   KBNODE keyblock;
1823   byte fprbuf[MAX_FINGERPRINT_LEN];
1824   int i;
1825
1826   for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1827     fprbuf[i] = fprint[i];
1828   while (i < MAX_FINGERPRINT_LEN)
1829     fprbuf[i++] = 0;
1830
1831   hd = keydb_new ();
1832   if (!hd)
1833     return gpg_error_from_syserror ();
1834
1835   rc = keydb_search_fpr (hd, fprbuf);
1836   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1837     {
1838       keydb_release (hd);
1839       return GPG_ERR_NO_PUBKEY;
1840     }
1841   rc = keydb_get_keyblock (hd, &keyblock);
1842   keydb_release (hd);
1843   if (rc)
1844     {
1845       log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1846       return GPG_ERR_NO_PUBKEY;
1847     }
1848
1849   log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1850               || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1851   if (pk)
1852     copy_public_key (pk, keyblock->pkt->pkt.public_key);
1853   release_kbnode (keyblock);
1854
1855   /* Not caching key here since it won't have all of the fields
1856      properly set. */
1857
1858   return 0;
1859 }
1860
1861 const char *
1862 parse_def_secret_key (ctrl_t ctrl)
1863 {
1864   KEYDB_HANDLE hd = NULL;
1865   strlist_t t;
1866   static int warned;
1867
1868   for (t = opt.def_secret_key; t; t = t->next)
1869     {
1870       gpg_error_t err;
1871       KEYDB_SEARCH_DESC desc;
1872       KBNODE kb;
1873       KBNODE node;
1874
1875       err = classify_user_id (t->d, &desc, 1);
1876       if (err)
1877         {
1878           log_error (_("secret key \"%s\" not found: %s\n"),
1879                      t->d, gpg_strerror (err));
1880           if (!opt.quiet)
1881             log_info (_("(check argument of option '%s')\n"), "--default-key");
1882           continue;
1883         }
1884
1885       if (! hd)
1886         {
1887           hd = keydb_new ();
1888           if (!hd)
1889             return NULL;
1890         }
1891       else
1892         keydb_search_reset (hd);
1893
1894
1895       err = keydb_search (hd, &desc, 1, NULL);
1896       if (gpg_err_code (err) == GPG_ERR_NOT_FOUND)
1897         continue;
1898
1899       if (err)
1900         {
1901           log_error (_("key \"%s\" not found: %s\n"), t->d, gpg_strerror (err));
1902           t = NULL;
1903           break;
1904         }
1905
1906       err = keydb_get_keyblock (hd, &kb);
1907       if (err)
1908         {
1909           log_error (_("error reading keyblock: %s\n"),
1910                      gpg_strerror (err));
1911           continue;
1912         }
1913
1914       merge_selfsigs (kb);
1915
1916       err = gpg_error (GPG_ERR_NO_SECKEY);
1917       node = kb;
1918       do
1919         {
1920           PKT_public_key *pk = node->pkt->pkt.public_key;
1921
1922           /* Check that the key has the signing capability.  */
1923           if (! (pk->pubkey_usage & PUBKEY_USAGE_SIG))
1924             continue;
1925
1926           /* Check if the key is valid.  */
1927           if (pk->flags.revoked)
1928             {
1929               if (DBG_LOOKUP)
1930                 log_debug ("not using %s as default key, %s",
1931                            keystr_from_pk (pk), "revoked");
1932               continue;
1933             }
1934           if (pk->has_expired)
1935             {
1936               if (DBG_LOOKUP)
1937                 log_debug ("not using %s as default key, %s",
1938                            keystr_from_pk (pk), "expired");
1939               continue;
1940             }
1941           if (pk_is_disabled (pk))
1942             {
1943               if (DBG_LOOKUP)
1944                 log_debug ("not using %s as default key, %s",
1945                            keystr_from_pk (pk), "disabled");
1946               continue;
1947             }
1948
1949           err = agent_probe_secret_key (ctrl, pk);
1950           if (! err)
1951             /* This is a valid key.  */
1952             break;
1953         }
1954       while ((node = find_next_kbnode (node, PKT_PUBLIC_SUBKEY)));
1955
1956       release_kbnode (kb);
1957       if (err)
1958         {
1959           if (! warned && ! opt.quiet)
1960             {
1961               log_info (_("Warning: not using '%s' as default key: %s\n"),
1962                         t->d, gpg_strerror (GPG_ERR_NO_SECKEY));
1963               print_reported_error (err, GPG_ERR_NO_SECKEY);
1964             }
1965         }
1966       else
1967         {
1968           if (! warned && ! opt.quiet)
1969             log_info (_("using \"%s\" as default secret key for signing\n"),
1970                       t->d);
1971           break;
1972         }
1973     }
1974
1975   if (! warned && opt.def_secret_key && ! t)
1976     log_info (_("all values passed to '%s' ignored\n"),
1977               "--default-key");
1978
1979   warned = 1;
1980
1981   if (hd)
1982     keydb_release (hd);
1983
1984   if (t)
1985     return t->d;
1986   return NULL;
1987 }
1988
1989
1990 /* Look up a secret key.
1991  *
1992  * If PK is not NULL, the public key of the first result is returned
1993  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
1994  * set, it is used to filter the search results.  See the
1995  * documentation for finish_lookup to understand exactly how this is
1996  * used.  Note: The self-signed data has already been merged into the
1997  * public key using merge_selfsigs.  Free *PK by calling
1998  * release_public_key_parts (or, if PK was allocated using xfree, you
1999  * can use free_public_key, which calls release_public_key_parts(PK)
2000  * and then xfree(PK)).
2001  *
2002  * If --default-key was set, then the specified key is looked up.  (In
2003  * this case, the default key is returned even if it is considered
2004  * unusable.  See the documentation for skip_unusable for exactly what
2005  * this means.)
2006  *
2007  * Otherwise, this initiates a DB scan that returns all keys that are
2008  * usable (see previous paragraph for exactly what usable means) and
2009  * for which a secret key is available.
2010  *
2011  * This function returns the first match.  Additional results can be
2012  * returned using getkey_next.  */
2013 gpg_error_t
2014 get_seckey_default (ctrl_t ctrl, PKT_public_key *pk)
2015 {
2016   gpg_error_t err;
2017   strlist_t namelist = NULL;
2018   int include_unusable = 1;
2019
2020
2021   const char *def_secret_key = parse_def_secret_key (ctrl);
2022   if (def_secret_key)
2023     add_to_strlist (&namelist, def_secret_key);
2024   else
2025     include_unusable = 0;
2026
2027   err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
2028
2029   free_strlist (namelist);
2030
2031   return err;
2032 }
2033
2034
2035 \f
2036 /* Search for keys matching some criteria.
2037  *
2038  * If RETCTX is not NULL, then the constructed context is returned in
2039  * *RETCTX so that getpubkey_next can be used to get subsequent
2040  * results.  In this case, getkey_end() must be used to free the
2041  * search context.  If RETCTX is not NULL, then RET_KDBHD must be
2042  * NULL.
2043  *
2044  * If PK is not NULL, the public key of the first result is returned
2045  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
2046  * set, it is used to filter the search results.  See the
2047  * documentation for finish_lookup to understand exactly how this is
2048  * used.  Note: The self-signed data has already been merged into the
2049  * public key using merge_selfsigs.  Free *PK by calling
2050  * release_public_key_parts (or, if PK was allocated using xfree, you
2051  * can use free_public_key, which calls release_public_key_parts(PK)
2052  * and then xfree(PK)).
2053  *
2054  * If NAMES is not NULL, then a search query is constructed using
2055  * classify_user_id on each of the strings in the list.  (Recall: the
2056  * database does an OR of the terms, not an AND.)  If NAMES is
2057  * NULL, then all results are returned.
2058  *
2059  * If WANT_SECRET is set, then only keys with an available secret key
2060  * (either locally or via key registered on a smartcard) are returned.
2061  *
2062  * This function does not skip unusable keys (see the documentation
2063  * for skip_unusable for an exact definition).
2064  *
2065  * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2066  * *RET_KEYBLOCK.  This should be freed using release_kbnode().
2067  *
2068  * This function returns 0 on success.  Otherwise, an error code is
2069  * returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2070  * (if want_secret is set) is returned if the key is not found.  */
2071 gpg_error_t
2072 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
2073                 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
2074 {
2075   return key_byname (retctx, names, pk, want_secret, 1,
2076                      ret_keyblock, NULL);
2077 }
2078
2079
2080 /* Search for one key matching some criteria.
2081  *
2082  * If RETCTX is not NULL, then the constructed context is returned in
2083  * *RETCTX so that getpubkey_next can be used to get subsequent
2084  * results.  In this case, getkey_end() must be used to free the
2085  * search context.  If RETCTX is not NULL, then RET_KDBHD must be
2086  * NULL.
2087  *
2088  * If PK is not NULL, the public key of the first result is returned
2089  * in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
2090  * set, it is used to filter the search results.  See the
2091  * documentation for finish_lookup to understand exactly how this is
2092  * used.  Note: The self-signed data has already been merged into the
2093  * public key using merge_selfsigs.  Free *PK by calling
2094  * release_public_key_parts (or, if PK was allocated using xfree, you
2095  * can use free_public_key, which calls release_public_key_parts(PK)
2096  * and then xfree(PK)).
2097  *
2098  * If NAME is not NULL, then a search query is constructed using
2099  * classify_user_id on the string.  In this case, even unusable keys
2100  * (see the documentation for skip_unusable for an exact definition of
2101  * unusable) are returned.  Otherwise, if --default-key was set, then
2102  * that key is returned (even if it is unusable).  If neither of these
2103  * conditions holds, then the first usable key is returned.
2104  *
2105  * If WANT_SECRET is set, then only keys with an available secret key
2106  * (either locally or via key registered on a smartcard) are returned.
2107  *
2108  * This function does not skip unusable keys (see the documentation
2109  * for skip_unusable for an exact definition).
2110  *
2111  * If RET_KEYBLOCK is not NULL, the keyblock is returned in
2112  * *RET_KEYBLOCK.  This should be freed using release_kbnode().
2113  *
2114  * This function returns 0 on success.  Otherwise, an error code is
2115  * returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
2116  * (if want_secret is set) is returned if the key is not found.
2117  *
2118  * FIXME: We also have the get_pubkey_byname function which has a
2119  * different semantic.  Should be merged with this one.  */
2120 gpg_error_t
2121 getkey_byname (ctrl_t ctrl, getkey_ctx_t *retctx, PKT_public_key *pk,
2122                const char *name, int want_secret, kbnode_t *ret_keyblock)
2123 {
2124   gpg_error_t err;
2125   strlist_t namelist = NULL;
2126   int with_unusable = 1;
2127   const char *def_secret_key = NULL;
2128
2129   if (want_secret && !name)
2130     def_secret_key = parse_def_secret_key (ctrl);
2131
2132   if (want_secret && !name && def_secret_key)
2133     add_to_strlist (&namelist, def_secret_key);
2134   else if (name)
2135     add_to_strlist (&namelist, name);
2136   else
2137     with_unusable = 0;
2138
2139   err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
2140                     ret_keyblock, NULL);
2141
2142   /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
2143      WANT_SECRET has been used.  */
2144
2145   free_strlist (namelist);
2146
2147   return err;
2148 }
2149
2150
2151 /* Return the next search result.
2152  *
2153  * If PK is not NULL, the public key of the next result is returned in
2154  * *PK.  Note: The self-signed data has already been merged into the
2155  * public key using merge_selfsigs.  Free *PK by calling
2156  * release_public_key_parts (or, if PK was allocated using xmalloc, you
2157  * can use free_public_key, which calls release_public_key_parts(PK)
2158  * and then xfree(PK)).
2159  *
2160  * RET_KEYBLOCK can be given as NULL; if it is not NULL it the entire
2161  * found keyblock is returned which must be released with
2162  * release_kbnode.  If the function returns an error NULL is stored at
2163  * RET_KEYBLOCK.
2164  *
2165  * The self-signed data has already been merged into the public key
2166  * using merge_selfsigs.  */
2167 gpg_error_t
2168 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
2169 {
2170   int rc; /* Fixme:  Make sure this is proper gpg_error */
2171   KBNODE keyblock = NULL;
2172   KBNODE found_key = NULL;
2173
2174   /* We need to disable the caching so that for an exact key search we
2175      won't get the result back from the cache and thus end up in an
2176      endless loop.  The endless loop can occur, because the cache is
2177      used without respecting the current file pointer!  */
2178   keydb_disable_caching (ctx->kr_handle);
2179
2180   /* FOUND_KEY is only valid as long as RET_KEYBLOCK is.  If the
2181    * caller wants PK, but not RET_KEYBLOCK, we need hand in our own
2182    * keyblock.  */
2183   if (pk && ret_keyblock == NULL)
2184       ret_keyblock = &keyblock;
2185
2186   rc = lookup (ctx, ret_keyblock, pk ? &found_key : NULL, ctx->want_secret);
2187   if (!rc && pk)
2188     {
2189       log_assert (found_key);
2190       pk_from_block (pk, NULL, found_key);
2191       release_kbnode (keyblock);
2192     }
2193
2194   return rc;
2195 }
2196
2197
2198 /* Release any resources used by a key listing context.  This must be
2199  * called on the context returned by, e.g., getkey_byname.  */
2200 void
2201 getkey_end (getkey_ctx_t ctx)
2202 {
2203   if (ctx)
2204     {
2205       keydb_release (ctx->kr_handle);
2206       free_strlist (ctx->extra_list);
2207       if (!ctx->not_allocated)
2208         xfree (ctx);
2209     }
2210 }
2211
2212
2213 \f
2214 /************************************************
2215  ************* Merging stuff ********************
2216  ************************************************/
2217
2218 /* Set the mainkey_id fields for all keys in KEYBLOCK.  This is
2219  * usually done by merge_selfsigs but at some places we only need the
2220  * main_kid not a full merge.  The function also guarantees that all
2221  * pk->keyids are computed.  */
2222 void
2223 setup_main_keyids (kbnode_t keyblock)
2224 {
2225   u32 kid[2], mainkid[2];
2226   kbnode_t kbctx, node;
2227   PKT_public_key *pk;
2228
2229   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2230     BUG ();
2231   pk = keyblock->pkt->pkt.public_key;
2232
2233   keyid_from_pk (pk, mainkid);
2234   for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
2235     {
2236       if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
2237             || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
2238         continue;
2239       pk = node->pkt->pkt.public_key;
2240       keyid_from_pk (pk, kid); /* Make sure pk->keyid is set.  */
2241       if (!pk->main_keyid[0] && !pk->main_keyid[1])
2242         {
2243           pk->main_keyid[0] = mainkid[0];
2244           pk->main_keyid[1] = mainkid[1];
2245         }
2246     }
2247 }
2248
2249
2250 /* KEYBLOCK corresponds to a public key block.  This function merges
2251  * much of the information from the self-signed data into the public
2252  * key, public subkey and user id data structures.  If you use the
2253  * high-level search API (e.g., get_pubkey) for looking up key blocks,
2254  * then you don't need to call this function.  This function is
2255  * useful, however, if you change the keyblock, e.g., by adding or
2256  * removing a self-signed data packet.  */
2257 void
2258 merge_keys_and_selfsig (KBNODE keyblock)
2259 {
2260   if (!keyblock)
2261     ;
2262   else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
2263     merge_selfsigs (keyblock);
2264   else
2265     log_debug ("FIXME: merging secret key blocks is not anymore available\n");
2266 }
2267
2268
2269 static int
2270 parse_key_usage (PKT_signature * sig)
2271 {
2272   int key_usage = 0;
2273   const byte *p;
2274   size_t n;
2275   byte flags;
2276
2277   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
2278   if (p && n)
2279     {
2280       /* First octet of the keyflags.  */
2281       flags = *p;
2282
2283       if (flags & 1)
2284         {
2285           key_usage |= PUBKEY_USAGE_CERT;
2286           flags &= ~1;
2287         }
2288
2289       if (flags & 2)
2290         {
2291           key_usage |= PUBKEY_USAGE_SIG;
2292           flags &= ~2;
2293         }
2294
2295       /* We do not distinguish between encrypting communications and
2296          encrypting storage. */
2297       if (flags & (0x04 | 0x08))
2298         {
2299           key_usage |= PUBKEY_USAGE_ENC;
2300           flags &= ~(0x04 | 0x08);
2301         }
2302
2303       if (flags & 0x20)
2304         {
2305           key_usage |= PUBKEY_USAGE_AUTH;
2306           flags &= ~0x20;
2307         }
2308
2309       if (flags)
2310         key_usage |= PUBKEY_USAGE_UNKNOWN;
2311
2312       if (!key_usage)
2313         key_usage |= PUBKEY_USAGE_NONE;
2314     }
2315   else if (p) /* Key flags of length zero.  */
2316     key_usage |= PUBKEY_USAGE_NONE;
2317
2318   /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
2319      capability that we do not handle.  This serves to distinguish
2320      between a zero key usage which we handle as the default
2321      capabilities for that algorithm, and a usage that we do not
2322      handle.  Likewise we use PUBKEY_USAGE_NONE to indicate that
2323      key_flags have been given but they do not specify any usage.  */
2324
2325   return key_usage;
2326 }
2327
2328
2329 /* Apply information from SIGNODE (which is the valid self-signature
2330  * associated with that UID) to the UIDNODE:
2331  * - weather the UID has been revoked
2332  * - assumed creation date of the UID
2333  * - temporary store the keyflags here
2334  * - temporary store the key expiration time here
2335  * - mark whether the primary user ID flag hat been set.
2336  * - store the preferences
2337  */
2338 static void
2339 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
2340 {
2341   PKT_user_id *uid = uidnode->pkt->pkt.user_id;
2342   PKT_signature *sig = signode->pkt->pkt.signature;
2343   const byte *p, *sym, *hash, *zip;
2344   size_t n, nsym, nhash, nzip;
2345
2346   sig->flags.chosen_selfsig = 1;/* We chose this one. */
2347   uid->created = 0;             /* Not created == invalid. */
2348   if (IS_UID_REV (sig))
2349     {
2350       uid->is_revoked = 1;
2351       return; /* Has been revoked.  */
2352     }
2353   else
2354     uid->is_revoked = 0;
2355
2356   uid->expiredate = sig->expiredate;
2357
2358   if (sig->flags.expired)
2359     {
2360       uid->is_expired = 1;
2361       return; /* Has expired.  */
2362     }
2363   else
2364     uid->is_expired = 0;
2365
2366   uid->created = sig->timestamp; /* This one is okay. */
2367   uid->selfsigversion = sig->version;
2368   /* If we got this far, it's not expired :) */
2369   uid->is_expired = 0;
2370
2371   /* Store the key flags in the helper variable for later processing.  */
2372   uid->help_key_usage = parse_key_usage (sig);
2373
2374   /* Ditto for the key expiration.  */
2375   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2376   if (p && buf32_to_u32 (p))
2377     uid->help_key_expire = keycreated + buf32_to_u32 (p);
2378   else
2379     uid->help_key_expire = 0;
2380
2381   /* Set the primary user ID flag - we will later wipe out some
2382    * of them to only have one in our keyblock.  */
2383   uid->is_primary = 0;
2384   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
2385   if (p && *p)
2386     uid->is_primary = 2;
2387
2388   /* We could also query this from the unhashed area if it is not in
2389    * the hased area and then later try to decide which is the better
2390    * there should be no security problem with this.
2391    * For now we only look at the hashed one.  */
2392
2393   /* Now build the preferences list.  These must come from the
2394      hashed section so nobody can modify the ciphers a key is
2395      willing to accept.  */
2396   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
2397   sym = p;
2398   nsym = p ? n : 0;
2399   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
2400   hash = p;
2401   nhash = p ? n : 0;
2402   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
2403   zip = p;
2404   nzip = p ? n : 0;
2405   if (uid->prefs)
2406     xfree (uid->prefs);
2407   n = nsym + nhash + nzip;
2408   if (!n)
2409     uid->prefs = NULL;
2410   else
2411     {
2412       uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
2413       n = 0;
2414       for (; nsym; nsym--, n++)
2415         {
2416           uid->prefs[n].type = PREFTYPE_SYM;
2417           uid->prefs[n].value = *sym++;
2418         }
2419       for (; nhash; nhash--, n++)
2420         {
2421           uid->prefs[n].type = PREFTYPE_HASH;
2422           uid->prefs[n].value = *hash++;
2423         }
2424       for (; nzip; nzip--, n++)
2425         {
2426           uid->prefs[n].type = PREFTYPE_ZIP;
2427           uid->prefs[n].value = *zip++;
2428         }
2429       uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker  */
2430       uid->prefs[n].value = 0;
2431     }
2432
2433   /* See whether we have the MDC feature.  */
2434   uid->flags.mdc = 0;
2435   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
2436   if (p && n && (p[0] & 0x01))
2437     uid->flags.mdc = 1;
2438
2439   /* And the keyserver modify flag.  */
2440   uid->flags.ks_modify = 1;
2441   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
2442   if (p && n && (p[0] & 0x80))
2443     uid->flags.ks_modify = 0;
2444 }
2445
2446 static void
2447 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
2448 {
2449   rinfo->date = sig->timestamp;
2450   rinfo->algo = sig->pubkey_algo;
2451   rinfo->keyid[0] = sig->keyid[0];
2452   rinfo->keyid[1] = sig->keyid[1];
2453 }
2454
2455
2456 /* Given a keyblock, parse the key block and extract various pieces of
2457    information and save them with the primary key packet and the user
2458    id packets.  For instance, some information is stored in signature
2459    packets.  We find the latest such valid packet (since the user can
2460    change that information) and copy its contents into the
2461    PKT_public_key.
2462
2463    Note that R_REVOKED may be set to 0, 1 or 2.
2464
2465    This function fills in the following fields in the primary key's
2466    keyblock:
2467
2468      main_keyid          (computed)
2469      revkey / numrevkeys (derived from self signed key data)
2470      flags.valid         (whether we have at least 1 self-sig)
2471      flags.maybe_revoked (whether a designed revoked the key, but
2472                           we are missing the key to check the sig)
2473      selfsigversion      (highest version of any valid self-sig)
2474      pubkey_usage        (derived from most recent self-sig or most
2475                           recent user id)
2476      has_expired         (various sources)
2477      expiredate          (various sources)
2478
2479   See the documentation for fixup_uidnode for how the user id packets
2480   are modified.  In addition to that the primary user id's is_primary
2481   field is set to 1 and the other user id's is_primary are set to
2482   0.  */
2483 static void
2484 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
2485                      struct revoke_info *rinfo)
2486 {
2487   PKT_public_key *pk = NULL;
2488   KBNODE k;
2489   u32 kid[2];
2490   u32 sigdate, uiddate, uiddate2;
2491   KBNODE signode, uidnode, uidnode2;
2492   u32 curtime = make_timestamp ();
2493   unsigned int key_usage = 0;
2494   u32 keytimestamp = 0;
2495   u32 key_expire = 0;
2496   int key_expire_seen = 0;
2497   byte sigversion = 0;
2498
2499   *r_revoked = 0;
2500   memset (rinfo, 0, sizeof (*rinfo));
2501
2502   /* Section 11.1 of RFC 4880 determines the order of packets within a
2503      message.  There are three sections, which must occur in the
2504      following order: the public key, the user ids and user attributes
2505      and the subkeys.  Within each section, each primary packet (e.g.,
2506      a user id packet) is followed by one or more signature packets,
2507      which modify that packet.  */
2508
2509   /* According to Section 11.1 of RFC 4880, the public key must be the
2510      first packet.  */
2511   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2512     /* parse_keyblock_image ensures that the first packet is the
2513        public key.  */
2514     BUG ();
2515   pk = keyblock->pkt->pkt.public_key;
2516   keytimestamp = pk->timestamp;
2517
2518   keyid_from_pk (pk, kid);
2519   pk->main_keyid[0] = kid[0];
2520   pk->main_keyid[1] = kid[1];
2521
2522   if (pk->version < 4)
2523     {
2524       /* Before v4 the key packet itself contains the expiration date
2525        * and there was no way to change it, so we start with the one
2526        * from the key packet.  */
2527       key_expire = pk->max_expiredate;
2528       key_expire_seen = 1;
2529     }
2530
2531   /* First pass:
2532
2533       - Find the latest direct key self-signature.  We assume that the
2534         newest one overrides all others.
2535
2536       - Determine whether the key has been revoked.
2537
2538       - Gather all revocation keys (unlike other data, we don't just
2539         take them from the latest self-signed packet).
2540
2541       - Determine max (sig[...]->version).
2542    */
2543
2544   /* Reset this in case this key was already merged. */
2545   xfree (pk->revkey);
2546   pk->revkey = NULL;
2547   pk->numrevkeys = 0;
2548
2549   signode = NULL;
2550   sigdate = 0; /* Helper variable to find the latest signature.  */
2551
2552   /* According to Section 11.1 of RFC 4880, the public key comes first
2553      and is immediately followed by any signature packets that modify
2554      it.  */
2555   for (k = keyblock;
2556        k && k->pkt->pkttype != PKT_USER_ID
2557          && k->pkt->pkttype != PKT_ATTRIBUTE
2558          && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2559        k = k->next)
2560     {
2561       if (k->pkt->pkttype == PKT_SIGNATURE)
2562         {
2563           PKT_signature *sig = k->pkt->pkt.signature;
2564           if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2565             /* Self sig.  */
2566             {
2567               if (check_key_signature (keyblock, k, NULL))
2568                 ; /* Signature did not verify.  */
2569               else if (IS_KEY_REV (sig))
2570                 {
2571                   /* Key has been revoked - there is no way to
2572                    * override such a revocation, so we theoretically
2573                    * can stop now.  We should not cope with expiration
2574                    * times for revocations here because we have to
2575                    * assume that an attacker can generate all kinds of
2576                    * signatures.  However due to the fact that the key
2577                    * has been revoked it does not harm either and by
2578                    * continuing we gather some more info on that
2579                    * key.  */
2580                   *r_revoked = 1;
2581                   sig_to_revoke_info (sig, rinfo);
2582                 }
2583               else if (IS_KEY_SIG (sig))
2584                 {
2585                   /* Add the indicated revocations keys from all
2586                      signatures not just the latest.  We do this
2587                      because you need multiple 1F sigs to properly
2588                      handle revocation keys (PGP does it this way, and
2589                      a revocation key could be sensitive and hence in
2590                      a different signature). */
2591                   if (sig->revkey)
2592                     {
2593                       int i;
2594
2595                       pk->revkey =
2596                         xrealloc (pk->revkey, sizeof (struct revocation_key) *
2597                                   (pk->numrevkeys + sig->numrevkeys));
2598
2599                       for (i = 0; i < sig->numrevkeys; i++)
2600                         memcpy (&pk->revkey[pk->numrevkeys++],
2601                                 &sig->revkey[i],
2602                                 sizeof (struct revocation_key));
2603                     }
2604
2605                   if (sig->timestamp >= sigdate)
2606                     /* This is the latest signature so far.  */
2607                     {
2608                       if (sig->flags.expired)
2609                         ; /* Signature has expired - ignore it.  */
2610                       else
2611                         {
2612                           sigdate = sig->timestamp;
2613                           signode = k;
2614                           if (sig->version > sigversion)
2615                             sigversion = sig->version;
2616
2617                         }
2618                     }
2619                 }
2620             }
2621         }
2622     }
2623
2624   /* Remove dupes from the revocation keys.  */
2625   if (pk->revkey)
2626     {
2627       int i, j, x, changed = 0;
2628
2629       for (i = 0; i < pk->numrevkeys; i++)
2630         {
2631           for (j = i + 1; j < pk->numrevkeys; j++)
2632             {
2633               if (memcmp (&pk->revkey[i], &pk->revkey[j],
2634                           sizeof (struct revocation_key)) == 0)
2635                 {
2636                   /* remove j */
2637
2638                   for (x = j; x < pk->numrevkeys - 1; x++)
2639                     pk->revkey[x] = pk->revkey[x + 1];
2640
2641                   pk->numrevkeys--;
2642                   j--;
2643                   changed = 1;
2644                 }
2645             }
2646         }
2647
2648       if (changed)
2649         pk->revkey = xrealloc (pk->revkey,
2650                                pk->numrevkeys *
2651                                sizeof (struct revocation_key));
2652     }
2653
2654   if (signode)
2655     /* SIGNODE is the 1F signature packet with the latest creation
2656        time.  Extract some information from it.  */
2657     {
2658       /* Some information from a direct key signature take precedence
2659        * over the same information given in UID sigs.  */
2660       PKT_signature *sig = signode->pkt->pkt.signature;
2661       const byte *p;
2662
2663       key_usage = parse_key_usage (sig);
2664
2665       p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2666       if (p && buf32_to_u32 (p))
2667         {
2668           key_expire = keytimestamp + buf32_to_u32 (p);
2669           key_expire_seen = 1;
2670         }
2671
2672       /* Mark that key as valid: One direct key signature should
2673        * render a key as valid.  */
2674       pk->flags.valid = 1;
2675     }
2676
2677   /* Pass 1.5: Look for key revocation signatures that were not made
2678      by the key (i.e. did a revocation key issue a revocation for
2679      us?).  Only bother to do this if there is a revocation key in the
2680      first place and we're not revoked already.  */
2681
2682   if (!*r_revoked && pk->revkey)
2683     for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
2684       {
2685         if (k->pkt->pkttype == PKT_SIGNATURE)
2686           {
2687             PKT_signature *sig = k->pkt->pkt.signature;
2688
2689             if (IS_KEY_REV (sig) &&
2690                 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
2691               {
2692                 int rc = check_revocation_keys (pk, sig);
2693                 if (rc == 0)
2694                   {
2695                     *r_revoked = 2;
2696                     sig_to_revoke_info (sig, rinfo);
2697                     /* Don't continue checking since we can't be any
2698                        more revoked than this.  */
2699                     break;
2700                   }
2701                 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
2702                   pk->flags.maybe_revoked = 1;
2703
2704                 /* A failure here means the sig did not verify, was
2705                    not issued by a revocation key, or a revocation
2706                    key loop was broken.  If a revocation key isn't
2707                    findable, however, the key might be revoked and
2708                    we don't know it.  */
2709
2710                 /* TODO: In the future handle subkey and cert
2711                    revocations?  PGP doesn't, but it's in 2440. */
2712               }
2713           }
2714       }
2715
2716   /* Second pass: Look at the self-signature of all user IDs.  */
2717
2718   /* According to RFC 4880 section 11.1, user id and attribute packets
2719      are in the second section, after the public key packet and before
2720      the subkey packets.  */
2721   signode = uidnode = NULL;
2722   sigdate = 0; /* Helper variable to find the latest signature in one UID. */
2723   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2724     {
2725       if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
2726         /* New user id packet.  */
2727         {
2728           if (uidnode && signode)
2729             /* Apply the data from the most recent self-signed packet
2730                to the preceding user id packet.  */
2731             {
2732               fixup_uidnode (uidnode, signode, keytimestamp);
2733               pk->flags.valid = 1;
2734             }
2735           /* Clear SIGNODE.  The only relevant self-signed data for
2736              UIDNODE follows it.  */
2737           if (k->pkt->pkttype == PKT_USER_ID)
2738             uidnode = k;
2739           else
2740             uidnode = NULL;
2741           signode = NULL;
2742           sigdate = 0;
2743         }
2744       else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2745         {
2746           PKT_signature *sig = k->pkt->pkt.signature;
2747           if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
2748             {
2749               if (check_key_signature (keyblock, k, NULL))
2750                 ;               /* signature did not verify */
2751               else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
2752                        && sig->timestamp >= sigdate)
2753                 {
2754                   /* Note: we allow invalidation of cert revocations
2755                    * by a newer signature.  An attacker can't use this
2756                    * because a key should be revoked with a key revocation.
2757                    * The reason why we have to allow for that is that at
2758                    * one time an email address may become invalid but later
2759                    * the same email address may become valid again (hired,
2760                    * fired, hired again).  */
2761
2762                   sigdate = sig->timestamp;
2763                   signode = k;
2764                   signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2765                   if (sig->version > sigversion)
2766                     sigversion = sig->version;
2767                 }
2768             }
2769         }
2770     }
2771   if (uidnode && signode)
2772     {
2773       fixup_uidnode (uidnode, signode, keytimestamp);
2774       pk->flags.valid = 1;
2775     }
2776
2777   /* If the key isn't valid yet, and we have
2778      --allow-non-selfsigned-uid set, then force it valid. */
2779   if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
2780     {
2781       if (opt.verbose)
2782         log_info (_("Invalid key %s made valid by"
2783                     " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
2784       pk->flags.valid = 1;
2785     }
2786
2787   /* The key STILL isn't valid, so try and find an ultimately
2788      trusted signature. */
2789   if (!pk->flags.valid)
2790     {
2791       uidnode = NULL;
2792
2793       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2794            k = k->next)
2795         {
2796           if (k->pkt->pkttype == PKT_USER_ID)
2797             uidnode = k;
2798           else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
2799             {
2800               PKT_signature *sig = k->pkt->pkt.signature;
2801
2802               if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
2803                 {
2804                   PKT_public_key *ultimate_pk;
2805
2806                   ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
2807
2808                   /* We don't want to use the full get_pubkey to
2809                      avoid infinite recursion in certain cases.
2810                      There is no reason to check that an ultimately
2811                      trusted key is still valid - if it has been
2812                      revoked the user should also remove the
2813                      ultimate trust flag.  */
2814                   if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
2815                       && check_key_signature2 (keyblock, k, ultimate_pk,
2816                                                NULL, NULL, NULL, NULL) == 0
2817                       && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
2818                     {
2819                       free_public_key (ultimate_pk);
2820                       pk->flags.valid = 1;
2821                       break;
2822                     }
2823
2824                   free_public_key (ultimate_pk);
2825                 }
2826             }
2827         }
2828     }
2829
2830   /* Record the highest selfsig version so we know if this is a v3
2831      key through and through, or a v3 key with a v4 selfsig
2832      somewhere.  This is useful in a few places to know if the key
2833      must be treated as PGP2-style or OpenPGP-style.  Note that a
2834      selfsig revocation with a higher version number will also raise
2835      this value.  This is okay since such a revocation must be
2836      issued by the user (i.e. it cannot be issued by someone else to
2837      modify the key behavior.) */
2838
2839   pk->selfsigversion = sigversion;
2840
2841   /* Now that we had a look at all user IDs we can now get some information
2842    * from those user IDs.
2843    */
2844
2845   if (!key_usage)
2846     {
2847       /* Find the latest user ID with key flags set. */
2848       uiddate = 0; /* Helper to find the latest user ID.  */
2849       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2850            k = k->next)
2851         {
2852           if (k->pkt->pkttype == PKT_USER_ID)
2853             {
2854               PKT_user_id *uid = k->pkt->pkt.user_id;
2855               if (uid->help_key_usage && uid->created > uiddate)
2856                 {
2857                   key_usage = uid->help_key_usage;
2858                   uiddate = uid->created;
2859                 }
2860             }
2861         }
2862     }
2863   if (!key_usage)
2864     {
2865       /* No key flags at all: get it from the algo.  */
2866       key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
2867     }
2868   else
2869     {
2870       /* Check that the usage matches the usage as given by the algo.  */
2871       int x = openpgp_pk_algo_usage (pk->pubkey_algo);
2872       if (x) /* Mask it down to the actual allowed usage.  */
2873         key_usage &= x;
2874     }
2875
2876   /* Whatever happens, it's a primary key, so it can certify. */
2877   pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
2878
2879   if (!key_expire_seen)
2880     {
2881       /* Find the latest valid user ID with a key expiration set
2882        * Note, that this may be a different one from the above because
2883        * some user IDs may have no expiration date set.  */
2884       uiddate = 0;
2885       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2886            k = k->next)
2887         {
2888           if (k->pkt->pkttype == PKT_USER_ID)
2889             {
2890               PKT_user_id *uid = k->pkt->pkt.user_id;
2891               if (uid->help_key_expire && uid->created > uiddate)
2892                 {
2893                   key_expire = uid->help_key_expire;
2894                   uiddate = uid->created;
2895                 }
2896             }
2897         }
2898     }
2899
2900   /* Currently only v3 keys have a maximum expiration date, but I'll
2901      bet v5 keys get this feature again. */
2902   if (key_expire == 0
2903       || (pk->max_expiredate && key_expire > pk->max_expiredate))
2904     key_expire = pk->max_expiredate;
2905
2906   pk->has_expired = key_expire >= curtime ? 0 : key_expire;
2907   pk->expiredate = key_expire;
2908
2909   /* Fixme: we should see how to get rid of the expiretime fields  but
2910    * this needs changes at other places too. */
2911
2912   /* And now find the real primary user ID and delete all others.  */
2913   uiddate = uiddate2 = 0;
2914   uidnode = uidnode2 = NULL;
2915   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2916     {
2917       if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
2918         {
2919           PKT_user_id *uid = k->pkt->pkt.user_id;
2920           if (uid->is_primary)
2921             {
2922               if (uid->created > uiddate)
2923                 {
2924                   uiddate = uid->created;
2925                   uidnode = k;
2926                 }
2927               else if (uid->created == uiddate && uidnode)
2928                 {
2929                   /* The dates are equal, so we need to do a
2930                      different (and arbitrary) comparison.  This
2931                      should rarely, if ever, happen.  It's good to
2932                      try and guarantee that two different GnuPG
2933                      users with two different keyrings at least pick
2934                      the same primary. */
2935                   if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
2936                     uidnode = k;
2937                 }
2938             }
2939           else
2940             {
2941               if (uid->created > uiddate2)
2942                 {
2943                   uiddate2 = uid->created;
2944                   uidnode2 = k;
2945                 }
2946               else if (uid->created == uiddate2 && uidnode2)
2947                 {
2948                   if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
2949                     uidnode2 = k;
2950                 }
2951             }
2952         }
2953     }
2954   if (uidnode)
2955     {
2956       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2957            k = k->next)
2958         {
2959           if (k->pkt->pkttype == PKT_USER_ID &&
2960               !k->pkt->pkt.user_id->attrib_data)
2961             {
2962               PKT_user_id *uid = k->pkt->pkt.user_id;
2963               if (k != uidnode)
2964                 uid->is_primary = 0;
2965             }
2966         }
2967     }
2968   else if (uidnode2)
2969     {
2970       /* None is flagged primary - use the latest user ID we have,
2971          and disambiguate with the arbitrary packet comparison. */
2972       uidnode2->pkt->pkt.user_id->is_primary = 1;
2973     }
2974   else
2975     {
2976       /* None of our uids were self-signed, so pick the one that
2977          sorts first to be the primary.  This is the best we can do
2978          here since there are no self sigs to date the uids. */
2979
2980       uidnode = NULL;
2981
2982       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2983            k = k->next)
2984         {
2985           if (k->pkt->pkttype == PKT_USER_ID
2986               && !k->pkt->pkt.user_id->attrib_data)
2987             {
2988               if (!uidnode)
2989                 {
2990                   uidnode = k;
2991                   uidnode->pkt->pkt.user_id->is_primary = 1;
2992                   continue;
2993                 }
2994               else
2995                 {
2996                   if (cmp_user_ids (k->pkt->pkt.user_id,
2997                                     uidnode->pkt->pkt.user_id) > 0)
2998                     {
2999                       uidnode->pkt->pkt.user_id->is_primary = 0;
3000                       uidnode = k;
3001                       uidnode->pkt->pkt.user_id->is_primary = 1;
3002                     }
3003                   else
3004                     k->pkt->pkt.user_id->is_primary = 0;        /* just to be
3005                                                                    safe */
3006                 }
3007             }
3008         }
3009     }
3010 }
3011
3012 /* Convert a buffer to a signature.  Useful for 0x19 embedded sigs.
3013    Caller must free the signature when they are done. */
3014 static PKT_signature *
3015 buf_to_sig (const byte * buf, size_t len)
3016 {
3017   PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
3018   IOBUF iobuf = iobuf_temp_with_content (buf, len);
3019   int save_mode = set_packet_list_mode (0);
3020
3021   if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
3022     {
3023       xfree (sig);
3024       sig = NULL;
3025     }
3026
3027   set_packet_list_mode (save_mode);
3028   iobuf_close (iobuf);
3029
3030   return sig;
3031 }
3032
3033 /* Use the self-signed data to fill in various fields in subkeys.
3034
3035    KEYBLOCK is the whole keyblock.  SUBNODE is the subkey to fill in.
3036
3037    Sets the following fields on the subkey:
3038
3039      main_keyid
3040      flags.valid        if the subkey has a valid self-sig binding
3041      flags.revoked
3042      flags.backsig
3043      pubkey_usage
3044      has_expired
3045      expired_date
3046
3047    On this subkey's most revent valid self-signed packet, the
3048    following field is set:
3049
3050      flags.chosen_selfsig
3051   */
3052 static void
3053 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
3054 {
3055   PKT_public_key *mainpk = NULL, *subpk = NULL;
3056   PKT_signature *sig;
3057   KBNODE k;
3058   u32 mainkid[2];
3059   u32 sigdate = 0;
3060   KBNODE signode;
3061   u32 curtime = make_timestamp ();
3062   unsigned int key_usage = 0;
3063   u32 keytimestamp = 0;
3064   u32 key_expire = 0;
3065   const byte *p;
3066
3067   if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3068     BUG ();
3069   mainpk = keyblock->pkt->pkt.public_key;
3070   if (mainpk->version < 4)
3071     return;/* (actually this should never happen) */
3072   keyid_from_pk (mainpk, mainkid);
3073   subpk = subnode->pkt->pkt.public_key;
3074   keytimestamp = subpk->timestamp;
3075
3076   subpk->flags.valid = 0;
3077   subpk->flags.exact = 0;
3078   subpk->main_keyid[0] = mainpk->main_keyid[0];
3079   subpk->main_keyid[1] = mainpk->main_keyid[1];
3080
3081   /* Find the latest key binding self-signature.  */
3082   signode = NULL;
3083   sigdate = 0; /* Helper to find the latest signature.  */
3084   for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
3085        k = k->next)
3086     {
3087       if (k->pkt->pkttype == PKT_SIGNATURE)
3088         {
3089           sig = k->pkt->pkt.signature;
3090           if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
3091             {
3092               if (check_key_signature (keyblock, k, NULL))
3093                 ; /* Signature did not verify.  */
3094               else if (IS_SUBKEY_REV (sig))
3095                 {
3096                   /* Note that this means that the date on a
3097                      revocation sig does not matter - even if the
3098                      binding sig is dated after the revocation sig,
3099                      the subkey is still marked as revoked.  This
3100                      seems ok, as it is just as easy to make new
3101                      subkeys rather than re-sign old ones as the
3102                      problem is in the distribution.  Plus, PGP (7)
3103                      does this the same way.  */
3104                   subpk->flags.revoked = 1;
3105                   sig_to_revoke_info (sig, &subpk->revoked);
3106                   /* Although we could stop now, we continue to
3107                    * figure out other information like the old expiration
3108                    * time.  */
3109                 }
3110               else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
3111                 {
3112                   if (sig->flags.expired)
3113                     ; /* Signature has expired - ignore it.  */
3114                   else
3115                     {
3116                       sigdate = sig->timestamp;
3117                       signode = k;
3118                       signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
3119                     }
3120                 }
3121             }
3122         }
3123     }
3124
3125   /* No valid key binding.  */
3126   if (!signode)
3127     return;
3128
3129   sig = signode->pkt->pkt.signature;
3130   sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later.  */
3131
3132   key_usage = parse_key_usage (sig);
3133   if (!key_usage)
3134     {
3135       /* No key flags at all: get it from the algo.  */
3136       key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
3137     }
3138   else
3139     {
3140       /* Check that the usage matches the usage as given by the algo.  */
3141       int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
3142       if (x) /* Mask it down to the actual allowed usage.  */
3143         key_usage &= x;
3144     }
3145
3146   subpk->pubkey_usage = key_usage;
3147
3148   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
3149   if (p && buf32_to_u32 (p))
3150     key_expire = keytimestamp + buf32_to_u32 (p);
3151   else
3152     key_expire = 0;
3153   subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
3154   subpk->expiredate = key_expire;
3155
3156   /* Algo doesn't exist.  */
3157   if (openpgp_pk_test_algo (subpk->pubkey_algo))
3158     return;
3159
3160   subpk->flags.valid = 1;
3161
3162   /* Find the most recent 0x19 embedded signature on our self-sig. */
3163   if (!subpk->flags.backsig)
3164     {
3165       int seq = 0;
3166       size_t n;
3167       PKT_signature *backsig = NULL;
3168
3169       sigdate = 0;
3170
3171       /* We do this while() since there may be other embedded
3172          signatures in the future.  We only want 0x19 here. */
3173
3174       while ((p = enum_sig_subpkt (sig->hashed,
3175                                    SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
3176         if (n > 3
3177             && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3178           {
3179             PKT_signature *tempsig = buf_to_sig (p, n);
3180             if (tempsig)
3181               {
3182                 if (tempsig->timestamp > sigdate)
3183                   {
3184                     if (backsig)
3185                       free_seckey_enc (backsig);
3186
3187                     backsig = tempsig;
3188                     sigdate = backsig->timestamp;
3189                   }
3190                 else
3191                   free_seckey_enc (tempsig);
3192               }
3193           }
3194
3195       seq = 0;
3196
3197       /* It is safe to have this in the unhashed area since the 0x19
3198          is located on the selfsig for convenience, not security. */
3199
3200       while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
3201                                    &n, &seq, NULL)))
3202         if (n > 3
3203             && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
3204           {
3205             PKT_signature *tempsig = buf_to_sig (p, n);
3206             if (tempsig)
3207               {
3208                 if (tempsig->timestamp > sigdate)
3209                   {
3210                     if (backsig)
3211                       free_seckey_enc (backsig);
3212
3213                     backsig = tempsig;
3214                     sigdate = backsig->timestamp;
3215                   }
3216                 else
3217                   free_seckey_enc (tempsig);
3218               }
3219           }
3220
3221       if (backsig)
3222         {
3223           /* At this point, backsig contains the most recent 0x19 sig.
3224              Let's see if it is good. */
3225
3226           /* 2==valid, 1==invalid, 0==didn't check */
3227           if (check_backsig (mainpk, subpk, backsig) == 0)
3228             subpk->flags.backsig = 2;
3229           else
3230             subpk->flags.backsig = 1;
3231
3232           free_seckey_enc (backsig);
3233         }
3234     }
3235 }
3236
3237
3238 /* Merge information from the self-signatures with the public key,
3239    subkeys and user ids to make using them more easy.
3240
3241    See documentation for merge_selfsigs_main, merge_selfsigs_subkey
3242    and fixup_uidnode for exactly which fields are updated.  */
3243 static void
3244 merge_selfsigs (KBNODE keyblock)
3245 {
3246   KBNODE k;
3247   int revoked;
3248   struct revoke_info rinfo;
3249   PKT_public_key *main_pk;
3250   prefitem_t *prefs;
3251   unsigned int mdc_feature;
3252
3253   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
3254     {
3255       if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
3256         {
3257           log_error ("expected public key but found secret key "
3258                      "- must stop\n");
3259           /* We better exit here because a public key is expected at
3260              other places too.  FIXME: Figure this out earlier and
3261              don't get to here at all */
3262           g10_exit (1);
3263         }
3264       BUG ();
3265     }
3266
3267   merge_selfsigs_main (keyblock, &revoked, &rinfo);
3268
3269   /* Now merge in the data from each of the subkeys.  */
3270   for (k = keyblock; k; k = k->next)
3271     {
3272       if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3273         {
3274           merge_selfsigs_subkey (keyblock, k);
3275         }
3276     }
3277
3278   main_pk = keyblock->pkt->pkt.public_key;
3279   if (revoked || main_pk->has_expired || !main_pk->flags.valid)
3280     {
3281       /* If the primary key is revoked, expired, or invalid we
3282        * better set the appropriate flags on that key and all
3283        * subkeys.  */
3284       for (k = keyblock; k; k = k->next)
3285         {
3286           if (k->pkt->pkttype == PKT_PUBLIC_KEY
3287               || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3288             {
3289               PKT_public_key *pk = k->pkt->pkt.public_key;
3290               if (!main_pk->flags.valid)
3291                 pk->flags.valid = 0;
3292               if (revoked && !pk->flags.revoked)
3293                 {
3294                   pk->flags.revoked = revoked;
3295                   memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
3296                 }
3297               if (main_pk->has_expired)
3298                 pk->has_expired = main_pk->has_expired;
3299             }
3300         }
3301       return;
3302     }
3303
3304   /* Set the preference list of all keys to those of the primary real
3305    * user ID.  Note: we use these preferences when we don't know by
3306    * which user ID the key has been selected.
3307    * fixme: we should keep atoms of commonly used preferences or
3308    * use reference counting to optimize the preference lists storage.
3309    * FIXME: it might be better to use the intersection of
3310    * all preferences.
3311    * Do a similar thing for the MDC feature flag.  */
3312   prefs = NULL;
3313   mdc_feature = 0;
3314   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
3315     {
3316       if (k->pkt->pkttype == PKT_USER_ID
3317           && !k->pkt->pkt.user_id->attrib_data
3318           && k->pkt->pkt.user_id->is_primary)
3319         {
3320           prefs = k->pkt->pkt.user_id->prefs;
3321           mdc_feature = k->pkt->pkt.user_id->flags.mdc;
3322           break;
3323         }
3324     }
3325   for (k = keyblock; k; k = k->next)
3326     {
3327       if (k->pkt->pkttype == PKT_PUBLIC_KEY
3328           || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3329         {
3330           PKT_public_key *pk = k->pkt->pkt.public_key;
3331           if (pk->prefs)
3332             xfree (pk->prefs);
3333           pk->prefs = copy_prefs (prefs);
3334           pk->flags.mdc = mdc_feature;
3335         }
3336     }
3337 }
3338
3339
3340 \f
3341 /* See whether the key satisfies any additional requirements specified
3342  * in CTX.  If so, return the node of an appropriate key or subkey.
3343  * Otherwise, return NULL if there was no appropriate key.
3344  *
3345  * Note that we do not return a reference, i.e. the result must not be
3346  * freed using 'release_kbnode'.
3347  *
3348  * In case the primary key is not required, select a suitable subkey.
3349  * We need the primary key if PUBKEY_USAGE_CERT is set in REQ_USAGE or
3350  * we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG is set in
3351  * REQ_USAGE.
3352  *
3353  * If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
3354  * are set in REQ_USAGE, we filter by the key's function.  Concretely,
3355  * if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then we only
3356  * return a key if it is (at least) either a signing or a
3357  * certification key.
3358  *
3359  * If REQ_USAGE is set, then we reject any keys that are not good
3360  * (i.e., valid, not revoked, not expired, etc.).  This allows the
3361  * getkey functions to be used for plain key listings.
3362  *
3363  * Sets the matched key's user id field (pk->user_id) to the user id
3364  * that matched the low-level search criteria or NULL.
3365  *
3366  * If R_FLAGS is not NULL set certain flags for more detailed error
3367  * reporting.  Used flags are:
3368  *
3369  * - LOOKUP_ALL_SUBKEYS_EXPIRED :: All Subkeys are expired or have
3370  *                                 been revoked.
3371  * - LOOKUP_NOT_SELECTED :: No suitable key found
3372  *
3373  * This function needs to handle several different cases:
3374  *
3375  *  1. No requested usage and no primary key requested
3376  *     Examples for this case are that we have a keyID to be used
3377  *     for decrytion or verification.
3378  *  2. No usage but primary key requested
3379  *     This is the case for all functions which work on an
3380  *     entire keyblock, e.g. for editing or listing
3381  *  3. Usage and primary key requested
3382  *     FIXME
3383  *  4. Usage but no primary key requested
3384  *     FIXME
3385  *
3386  */
3387 static kbnode_t
3388 finish_lookup (kbnode_t keyblock, unsigned int req_usage, int want_exact,
3389                unsigned int *r_flags)
3390 {
3391   kbnode_t k;
3392
3393   /* If WANT_EXACT is set, the key or subkey that actually matched the
3394      low-level search criteria.  */
3395   kbnode_t foundk = NULL;
3396   /* The user id (if any) that matched the low-level search criteria.  */
3397   PKT_user_id *foundu = NULL;
3398
3399   u32 latest_date;
3400   kbnode_t latest_key;
3401   PKT_public_key *pk;
3402   int req_prim;
3403   u32 curtime = make_timestamp ();
3404
3405   if (r_flags)
3406     *r_flags = 0;
3407
3408 #define USAGE_MASK  (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
3409   req_usage &= USAGE_MASK;
3410
3411   /* Request the primary if we're certifying another key, and also if
3412    * signing data while --pgp6 or --pgp7 is on since pgp 6 and 7 do
3413    * not understand signatures made by a signing subkey.  PGP 8 does. */
3414   req_prim = ((req_usage & PUBKEY_USAGE_CERT)
3415               || ((PGP6 || PGP7) && (req_usage & PUBKEY_USAGE_SIG)));
3416
3417
3418   log_assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
3419
3420   /* For an exact match mark the primary or subkey that matched the
3421      low-level search criteria.  */
3422   if (want_exact)
3423     {
3424       for (k = keyblock; k; k = k->next)
3425         {
3426           if ((k->flag & 1))
3427             {
3428               log_assert (k->pkt->pkttype == PKT_PUBLIC_KEY
3429                           || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3430               foundk = k;
3431               pk = k->pkt->pkt.public_key;
3432               pk->flags.exact = 1;
3433               break;
3434             }
3435         }
3436     }
3437
3438   /* Get the user id that matched that low-level search criteria.  */
3439   for (k = keyblock; k; k = k->next)
3440     {
3441       if ((k->flag & 2))
3442         {
3443           log_assert (k->pkt->pkttype == PKT_USER_ID);
3444           foundu = k->pkt->pkt.user_id;
3445           break;
3446         }
3447     }
3448
3449   if (DBG_LOOKUP)
3450     log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
3451                (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
3452                foundk ? "one" : "all", req_usage);
3453
3454   if (!req_usage)
3455     {
3456       latest_key = foundk ? foundk : keyblock;
3457       goto found;
3458     }
3459
3460   latest_date = 0;
3461   latest_key = NULL;
3462   /* Set LATEST_KEY to the latest (the one with the most recent
3463    * timestamp) good (valid, not revoked, not expired, etc.) subkey.
3464    *
3465    * Don't bother if we are only looking for a primary key or we need
3466    * an exact match and the exact match is not a subkey.  */
3467   if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
3468     ;
3469   else
3470     {
3471       kbnode_t nextk;
3472       int n_subkeys = 0;
3473       int n_revoked_or_expired = 0;
3474
3475       /* Either start a loop or check just this one subkey.  */
3476       for (k = foundk ? foundk : keyblock; k; k = nextk)
3477         {
3478           if (foundk)
3479             {
3480               /* If FOUNDK is not NULL, then only consider that exact
3481                  key, i.e., don't iterate.  */
3482               nextk = NULL;
3483             }
3484           else
3485             nextk = k->next;
3486
3487           if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
3488             continue;
3489
3490           pk = k->pkt->pkt.public_key;
3491           if (DBG_LOOKUP)
3492             log_debug ("\tchecking subkey %08lX\n",
3493                        (ulong) keyid_from_pk (pk, NULL));
3494
3495           if (!pk->flags.valid)
3496             {
3497               if (DBG_LOOKUP)
3498                 log_debug ("\tsubkey not valid\n");
3499               continue;
3500             }
3501           if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3502             {
3503               if (DBG_LOOKUP)
3504                 log_debug ("\tusage does not match: want=%x have=%x\n",
3505                            req_usage, pk->pubkey_usage);
3506               continue;
3507             }
3508
3509           n_subkeys++;
3510           if (pk->flags.revoked)
3511             {
3512               if (DBG_LOOKUP)
3513                 log_debug ("\tsubkey has been revoked\n");
3514               n_revoked_or_expired++;
3515               continue;
3516             }
3517           if (pk->has_expired)
3518             {
3519               if (DBG_LOOKUP)
3520                 log_debug ("\tsubkey has expired\n");
3521               n_revoked_or_expired++;
3522               continue;
3523             }
3524           if (pk->timestamp > curtime && !opt.ignore_valid_from)
3525             {
3526               if (DBG_LOOKUP)
3527                 log_debug ("\tsubkey not yet valid\n");
3528               continue;
3529             }
3530
3531           if (DBG_LOOKUP)
3532             log_debug ("\tsubkey might be fine\n");
3533           /* In case a key has a timestamp of 0 set, we make sure
3534              that it is used.  A better change would be to compare
3535              ">=" but that might also change the selected keys and
3536              is as such a more intrusive change.  */
3537           if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
3538             {
3539               latest_date = pk->timestamp;
3540               latest_key = k;
3541             }
3542         }
3543       if (n_subkeys == n_revoked_or_expired && r_flags)
3544         *r_flags |= LOOKUP_ALL_SUBKEYS_EXPIRED;
3545     }
3546
3547   /* Check if the primary key is ok (valid, not revoke, not expire,
3548    * matches requested usage) if:
3549    *
3550    *   - we didn't find an appropriate subkey and we're not doing an
3551    *     exact search,
3552    *
3553    *   - we're doing an exact match and the exact match was the
3554    *     primary key, or,
3555    *
3556    *   - we're just considering the primary key.  */
3557   if ((!latest_key && !want_exact) || foundk == keyblock || req_prim)
3558     {
3559       if (DBG_LOOKUP && !foundk && !req_prim)
3560         log_debug ("\tno suitable subkeys found - trying primary\n");
3561       pk = keyblock->pkt->pkt.public_key;
3562       if (!pk->flags.valid)
3563         {
3564           if (DBG_LOOKUP)
3565             log_debug ("\tprimary key not valid\n");
3566         }
3567       else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
3568         {
3569           if (DBG_LOOKUP)
3570             log_debug ("\tprimary key usage does not match: "
3571                        "want=%x have=%x\n", req_usage, pk->pubkey_usage);
3572         }
3573       else if (pk->flags.revoked)
3574         {
3575           if (DBG_LOOKUP)
3576             log_debug ("\tprimary key has been revoked\n");
3577         }
3578       else if (pk->has_expired)
3579         {
3580           if (DBG_LOOKUP)
3581             log_debug ("\tprimary key has expired\n");
3582         }
3583       else /* Okay.  */
3584         {
3585           if (DBG_LOOKUP)
3586             log_debug ("\tprimary key may be used\n");
3587           latest_key = keyblock;
3588         }
3589     }
3590
3591   if (!latest_key)
3592     {
3593       if (DBG_LOOKUP)
3594         log_debug ("\tno suitable key found -  giving up\n");
3595       if (r_flags)
3596         *r_flags |= LOOKUP_NOT_SELECTED;
3597       return NULL; /* Not found.  */
3598     }
3599
3600  found:
3601   if (DBG_LOOKUP)
3602     log_debug ("\tusing key %08lX\n",
3603                (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
3604
3605   if (latest_key)
3606     {
3607       pk = latest_key->pkt->pkt.public_key;
3608       free_user_id (pk->user_id);
3609       pk->user_id = scopy_user_id (foundu);
3610     }
3611
3612   if (latest_key != keyblock && opt.verbose)
3613     {
3614       char *tempkeystr =
3615         xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
3616       log_info (_("using subkey %s instead of primary key %s\n"),
3617                 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
3618       xfree (tempkeystr);
3619     }
3620
3621   cache_user_id (keyblock);
3622
3623   return latest_key ? latest_key : keyblock; /* Found.  */
3624 }
3625
3626
3627 /* Print a KEY_CONSIDERED status line.  */
3628 static void
3629 print_status_key_considered (kbnode_t keyblock, unsigned int flags)
3630 {
3631   char hexfpr[2*MAX_FINGERPRINT_LEN + 1];
3632   kbnode_t node;
3633   char flagbuf[20];
3634
3635   if (!is_status_enabled ())
3636     return;
3637
3638   for (node=keyblock; node; node = node->next)
3639     if (node->pkt->pkttype == PKT_PUBLIC_KEY
3640         || node->pkt->pkttype == PKT_SECRET_KEY)
3641       break;
3642   if (!node)
3643     {
3644       log_error ("%s: keyblock w/o primary key\n", __func__);
3645       return;
3646     }
3647
3648   hexfingerprint (node->pkt->pkt.public_key, hexfpr, sizeof hexfpr);
3649   snprintf (flagbuf, sizeof flagbuf, " %u", flags);
3650   write_status_strings (STATUS_KEY_CONSIDERED, hexfpr, flagbuf, NULL);
3651 }
3652
3653
3654
3655 /* A high-level function to lookup keys.
3656
3657    This function builds on top of the low-level keydb API.  It first
3658    searches the database using the description stored in CTX->ITEMS,
3659    then it filters the results using CTX and, finally, if WANT_SECRET
3660    is set, it ignores any keys for which no secret key is available.
3661
3662    Unlike the low-level search functions, this function also merges
3663    all of the self-signed data into the keys, subkeys and user id
3664    packets (see the merge_selfsigs for details).
3665
3666    On success the key's keyblock is stored at *RET_KEYBLOCK, and the
3667    specific subkey is stored at *RET_FOUND_KEY.  Note that we do not
3668    return a reference in *RET_FOUND_KEY, i.e. the result must not be
3669    freed using 'release_kbnode', and it is only valid until
3670    *RET_KEYBLOCK is deallocated.  Therefore, if RET_FOUND_KEY is not
3671    NULL, then RET_KEYBLOCK must not be NULL.  */
3672 static int
3673 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
3674         int want_secret)
3675 {
3676   int rc;
3677   int no_suitable_key = 0;
3678   KBNODE keyblock = NULL;
3679   KBNODE found_key = NULL;
3680   unsigned int infoflags;
3681
3682   log_assert (ret_found_key == NULL || ret_keyblock != NULL);
3683   if (ret_keyblock)
3684     *ret_keyblock = NULL;
3685
3686   for (;;)
3687     {
3688       rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
3689       if (rc)
3690         break;
3691
3692       /* If we are iterating over the entire database, then we need to
3693          change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
3694          reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next
3695          record.  */
3696       if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
3697         ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
3698
3699       rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
3700       if (rc)
3701         {
3702           log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
3703           goto skip;
3704         }
3705
3706       if (want_secret && agent_probe_any_secret_key (NULL, keyblock))
3707         goto skip; /* No secret key available.  */
3708
3709       /* Warning: node flag bits 0 and 1 should be preserved by
3710        * merge_selfsigs.  */
3711       merge_selfsigs (keyblock);
3712       found_key = finish_lookup (keyblock, ctx->req_usage, ctx->exact,
3713                                  &infoflags);
3714       print_status_key_considered (keyblock, infoflags);
3715       if (found_key)
3716         {
3717           no_suitable_key = 0;
3718           goto found;
3719         }
3720       else
3721         {
3722           no_suitable_key = 1;
3723         }
3724
3725     skip:
3726       /* Release resources and continue search. */
3727       release_kbnode (keyblock);
3728       keyblock = NULL;
3729       /* The keyblock cache ignores the current "file position".
3730          Thus, if we request the next result and the cache matches
3731          (and it will since it is what we just looked for), we'll get
3732          the same entry back!  We can avoid this infinite loop by
3733          disabling the cache.  */
3734       keydb_disable_caching (ctx->kr_handle);
3735     }
3736
3737  found:
3738   if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
3739     log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
3740
3741   if (!rc)
3742     {
3743       if (ret_keyblock)
3744         {
3745           *ret_keyblock = keyblock; /* Return the keyblock.  */
3746           keyblock = NULL;
3747         }
3748     }
3749   else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND && no_suitable_key)
3750     rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
3751   else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
3752     rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
3753
3754   release_kbnode (keyblock);
3755
3756   if (ret_found_key)
3757     {
3758       if (! rc)
3759         *ret_found_key = found_key;
3760       else
3761         *ret_found_key = NULL;
3762     }
3763
3764   return rc;
3765 }
3766
3767
3768 /* Enumerate some secret keys (specifically, those specified with
3769  * --default-key and --try-secret-key).  Use the following procedure:
3770  *
3771  *  1) Initialize a void pointer to NULL
3772  *  2) Pass a reference to this pointer to this function (content)
3773  *     and provide space for the secret key (sk)
3774  *  3) Call this function as long as it does not return an error (or
3775  *     until you are done).  The error code GPG_ERR_EOF indicates the
3776  *     end of the listing.
3777  *  4) Call this function a last time with SK set to NULL,
3778  *     so that can free it's context.
3779  *
3780  * In pseudo-code:
3781  *
3782  *   void *ctx = NULL;
3783  *   PKT_public_key *sk = xmalloc_clear (sizeof (*sk));
3784  *
3785  *   while ((err = enum_secret_keys (&ctx, sk)))
3786  *     { // Process SK.
3787  *       if (done)
3788  *         break;
3789  *       free_public_key (sk);
3790  *       sk = xmalloc_clear (sizeof (*sk));
3791  *     }
3792  *
3793  *   // Release any resources used by CTX.
3794  *   enum_secret_keys (&ctx, NULL);
3795  *   free_public_key (sk);
3796  *
3797  *   if (gpg_err_code (err) != GPG_ERR_EOF)
3798  *     ; // An error occurred.
3799  */
3800 gpg_error_t
3801 enum_secret_keys (ctrl_t ctrl, void **context, PKT_public_key *sk)
3802 {
3803   gpg_error_t err = 0;
3804   const char *name;
3805   kbnode_t keyblock;
3806   struct
3807   {
3808     int eof;
3809     int state;
3810     strlist_t sl;
3811     kbnode_t keyblock;
3812     kbnode_t node;
3813     getkey_ctx_t ctx;
3814   } *c = *context;
3815
3816   if (!c)
3817     {
3818       /* Make a new context.  */
3819       c = xtrycalloc (1, sizeof *c);
3820       if (!c)
3821         return gpg_error_from_syserror ();
3822       *context = c;
3823     }
3824
3825   if (!sk)
3826     {
3827       /* Free the context.  */
3828       release_kbnode (c->keyblock);
3829       getkey_end (c->ctx);
3830       xfree (c);
3831       *context = NULL;
3832       return 0;
3833     }
3834
3835   if (c->eof)
3836     return gpg_error (GPG_ERR_EOF);
3837
3838   for (;;)
3839     {
3840       /* Loop until we have a keyblock.  */
3841       while (!c->keyblock)
3842         {
3843           /* Loop over the list of secret keys.  */
3844           do
3845             {
3846               name = NULL;
3847               keyblock = NULL;
3848               switch (c->state)
3849                 {
3850                 case 0: /* First try to use the --default-key.  */
3851                   name = parse_def_secret_key (ctrl);
3852                   c->state = 1;
3853                   break;
3854
3855                 case 1: /* Init list of keys to try.  */
3856                   c->sl = opt.secret_keys_to_try;
3857                   c->state++;
3858                   break;
3859
3860                 case 2: /* Get next item from list.  */
3861                   if (c->sl)
3862                     {
3863                       name = c->sl->d;
3864                       c->sl = c->sl->next;
3865                     }
3866                   else
3867                     c->state++;
3868                   break;
3869
3870                 case 3: /* Init search context to enum all secret keys.  */
3871                   err = getkey_bynames (&c->ctx, NULL, NULL, 1, &keyblock);
3872                   if (err)
3873                     {
3874                       release_kbnode (keyblock);
3875                       keyblock = NULL;
3876                       getkey_end (c->ctx);
3877                       c->ctx = NULL;
3878                     }
3879                   c->state++;
3880                   break;
3881
3882                 case 4: /* Get next item from the context.  */
3883                   if (c->ctx)
3884                     {
3885                       err = getkey_next (c->ctx, NULL, &keyblock);
3886                       if (err)
3887                         {
3888                           release_kbnode (keyblock);
3889                           keyblock = NULL;
3890                           getkey_end (c->ctx);
3891                           c->ctx = NULL;
3892                         }
3893                     }
3894                   else
3895                     c->state++;
3896                   break;
3897
3898                 default: /* No more names to check - stop.  */
3899                   c->eof = 1;
3900                   return gpg_error (GPG_ERR_EOF);
3901                 }
3902             }
3903           while ((!name || !*name) && !keyblock);
3904
3905           if (keyblock)
3906             c->node = c->keyblock = keyblock;
3907           else
3908             {
3909               err = getkey_byname (ctrl, NULL, NULL, name, 1, &c->keyblock);
3910               if (err)
3911                 {
3912                   /* getkey_byname might return a keyblock even in the
3913                      error case - I have not checked.  Thus better release
3914                      it.  */
3915                   release_kbnode (c->keyblock);
3916                   c->keyblock = NULL;
3917                 }
3918               else
3919                 c->node = c->keyblock;
3920             }
3921         }
3922
3923       /* Get the next key from the current keyblock.  */
3924       for (; c->node; c->node = c->node->next)
3925         {
3926           if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
3927               || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
3928             {
3929               copy_public_key (sk, c->node->pkt->pkt.public_key);
3930               c->node = c->node->next;
3931               return 0; /* Found.  */
3932             }
3933         }
3934
3935       /* Dispose the keyblock and continue.  */
3936       release_kbnode (c->keyblock);
3937       c->keyblock = NULL;
3938     }
3939 }
3940
3941 \f
3942 /*********************************************
3943  ***********  User ID printing helpers *******
3944  *********************************************/
3945
3946 /* Return a string with a printable representation of the user_id.
3947  * this string must be freed by xfree.   */
3948 static char *
3949 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
3950 {
3951   user_id_db_t r;
3952   keyid_list_t a;
3953   int pass = 0;
3954   char *p;
3955
3956   /* Try it two times; second pass reads from the database.  */
3957   do
3958     {
3959       for (r = user_id_db; r; r = r->next)
3960         {
3961           for (a = r->keyids; a; a = a->next)
3962             {
3963               if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
3964                 {
3965                   if (mode == 2)
3966                     {
3967                       /* An empty string as user id is possible.  Make
3968                          sure that the malloc allocates one byte and
3969                          does not bail out.  */
3970                       p = xmalloc (r->len? r->len : 1);
3971                       memcpy (p, r->name, r->len);
3972                       if (r_len)
3973                         *r_len = r->len;
3974                     }
3975                   else
3976                     {
3977                       if (mode)
3978                         p = xasprintf ("%08lX%08lX %.*s",
3979                                        (ulong) keyid[0], (ulong) keyid[1],
3980                                        r->len, r->name);
3981                       else
3982                         p = xasprintf ("%s %.*s", keystr (keyid),
3983                                        r->len, r->name);
3984                       if (r_len)
3985                         *r_len = strlen (p);
3986                     }
3987
3988                   return p;
3989                 }
3990             }
3991         }
3992     }
3993   while (++pass < 2 && !get_pubkey (NULL, keyid));
3994
3995   if (mode == 2)
3996     p = xstrdup (user_id_not_found_utf8 ());
3997   else if (mode)
3998     p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
3999   else
4000     p = xasprintf ("%s [?]", keystr (keyid));
4001
4002   if (r_len)
4003     *r_len = strlen (p);
4004   return p;
4005 }
4006
4007
4008 char *
4009 get_user_id_string_native (u32 * keyid)
4010 {
4011   char *p = get_user_id_string (keyid, 0, NULL);
4012   char *p2 = utf8_to_native (p, strlen (p), 0);
4013   xfree (p);
4014   return p2;
4015 }
4016
4017
4018 char *
4019 get_long_user_id_string (u32 * keyid)
4020 {
4021   return get_user_id_string (keyid, 1, NULL);
4022 }
4023
4024
4025 /* Please try to use get_user_byfpr instead of this one.  */
4026 char *
4027 get_user_id (u32 * keyid, size_t * rn)
4028 {
4029   return get_user_id_string (keyid, 2, rn);
4030 }
4031
4032
4033 /* Please try to use get_user_id_byfpr_native instead of this one.  */
4034 char *
4035 get_user_id_native (u32 * keyid)
4036 {
4037   size_t rn;
4038   char *p = get_user_id (keyid, &rn);
4039   char *p2 = utf8_to_native (p, rn, 0);
4040   xfree (p);
4041   return p2;
4042 }
4043
4044
4045 /* Return the user id for a key designated by its fingerprint, FPR,
4046    which must be MAX_FINGERPRINT_LEN bytes in size.  Note: the
4047    returned string, which must be freed using xfree, may not be NUL
4048    terminated.  To determine the length of the string, you must use
4049    *RN.  */
4050 char *
4051 get_user_id_byfpr (const byte *fpr, size_t *rn)
4052 {
4053   user_id_db_t r;
4054   char *p;
4055   int pass = 0;
4056
4057   /* Try it two times; second pass reads from the database.  */
4058   do
4059     {
4060       for (r = user_id_db; r; r = r->next)
4061         {
4062           keyid_list_t a;
4063           for (a = r->keyids; a; a = a->next)
4064             {
4065               if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
4066                 {
4067                   /* An empty string as user id is possible.  Make
4068                      sure that the malloc allocates one byte and does
4069                      not bail out.  */
4070                   p = xmalloc (r->len? r->len : 1);
4071                   memcpy (p, r->name, r->len);
4072                   *rn = r->len;
4073                   return p;
4074                 }
4075             }
4076         }
4077     }
4078   while (++pass < 2
4079          && !get_pubkey_byfprint (NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
4080   p = xstrdup (user_id_not_found_utf8 ());
4081   *rn = strlen (p);
4082   return p;
4083 }
4084
4085 /* Like get_user_id_byfpr, but convert the string to the native
4086    encoding.  The returned string needs to be freed.  Unlike
4087    get_user_id_byfpr, the returned string is NUL terminated.  */
4088 char *
4089 get_user_id_byfpr_native (const byte *fpr)
4090 {
4091   size_t rn;
4092   char *p = get_user_id_byfpr (fpr, &rn);
4093   char *p2 = utf8_to_native (p, rn, 0);
4094   xfree (p);
4095   return p2;
4096 }
4097
4098
4099 /* Return the database handle used by this context.  The context still
4100    owns the handle.  */
4101 KEYDB_HANDLE
4102 get_ctx_handle (GETKEY_CTX ctx)
4103 {
4104   return ctx->kr_handle;
4105 }
4106
4107 static void
4108 free_akl (struct akl *akl)
4109 {
4110   if (! akl)
4111     return;
4112
4113   if (akl->spec)
4114     free_keyserver_spec (akl->spec);
4115
4116   xfree (akl);
4117 }
4118
4119 void
4120 release_akl (void)
4121 {
4122   while (opt.auto_key_locate)
4123     {
4124       struct akl *akl2 = opt.auto_key_locate;
4125       opt.auto_key_locate = opt.auto_key_locate->next;
4126       free_akl (akl2);
4127     }
4128 }
4129
4130 /* Returns false on error. */
4131 int
4132 parse_auto_key_locate (char *options)
4133 {
4134   char *tok;
4135
4136   while ((tok = optsep (&options)))
4137     {
4138       struct akl *akl, *check, *last = NULL;
4139       int dupe = 0;
4140
4141       if (tok[0] == '\0')
4142         continue;
4143
4144       akl = xmalloc_clear (sizeof (*akl));
4145
4146       if (ascii_strcasecmp (tok, "clear") == 0)
4147         {
4148           xfree (akl);
4149           free_akl (opt.auto_key_locate);
4150           opt.auto_key_locate = NULL;
4151           continue;
4152         }
4153       else if (ascii_strcasecmp (tok, "nodefault") == 0)
4154         akl->type = AKL_NODEFAULT;
4155       else if (ascii_strcasecmp (tok, "local") == 0)
4156         akl->type = AKL_LOCAL;
4157       else if (ascii_strcasecmp (tok, "ldap") == 0)
4158         akl->type = AKL_LDAP;
4159       else if (ascii_strcasecmp (tok, "keyserver") == 0)
4160         akl->type = AKL_KEYSERVER;
4161       else if (ascii_strcasecmp (tok, "cert") == 0)
4162         akl->type = AKL_CERT;
4163       else if (ascii_strcasecmp (tok, "pka") == 0)
4164         akl->type = AKL_PKA;
4165       else if (ascii_strcasecmp (tok, "dane") == 0)
4166         akl->type = AKL_DANE;
4167       else if (ascii_strcasecmp (tok, "wkd") == 0)
4168         akl->type = AKL_WKD;
4169       else if ((akl->spec = parse_keyserver_uri (tok, 1)))
4170         akl->type = AKL_SPEC;
4171       else
4172         {
4173           free_akl (akl);
4174           return 0;
4175         }
4176
4177       /* We must maintain the order the user gave us */
4178       for (check = opt.auto_key_locate; check;
4179            last = check, check = check->next)
4180         {
4181           /* Check for duplicates */
4182           if (check->type == akl->type
4183               && (akl->type != AKL_SPEC
4184                   || (akl->type == AKL_SPEC
4185                       && strcmp (check->spec->uri, akl->spec->uri) == 0)))
4186             {
4187               dupe = 1;
4188               free_akl (akl);
4189               break;
4190             }
4191         }
4192
4193       if (!dupe)
4194         {
4195           if (last)
4196             last->next = akl;
4197           else
4198             opt.auto_key_locate = akl;
4199         }
4200     }
4201
4202   return 1;
4203 }
4204
4205
4206 /* Returns true if a secret key is available for the public key with
4207    key id KEYID; returns false if not.  This function ignores legacy
4208    keys.  Note: this is just a fast check and does not tell us whether
4209    the secret key is valid; this check merely indicates whether there
4210    is some secret key with the specified key id.  */
4211 int
4212 have_secret_key_with_kid (u32 *keyid)
4213 {
4214   gpg_error_t err;
4215   KEYDB_HANDLE kdbhd;
4216   KEYDB_SEARCH_DESC desc;
4217   kbnode_t keyblock;
4218   kbnode_t node;
4219   int result = 0;
4220
4221   kdbhd = keydb_new ();
4222   if (!kdbhd)
4223     return 0;
4224   memset (&desc, 0, sizeof desc);
4225   desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
4226   desc.u.kid[0] = keyid[0];
4227   desc.u.kid[1] = keyid[1];
4228   while (!result)
4229     {
4230       err = keydb_search (kdbhd, &desc, 1, NULL);
4231       if (err)
4232         break;
4233
4234       err = keydb_get_keyblock (kdbhd, &keyblock);
4235       if (err)
4236         {
4237           log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
4238           break;
4239         }
4240
4241       for (node = keyblock; node; node = node->next)
4242         {
4243           /* Bit 0 of the flags is set if the search found the key
4244              using that key or subkey.  Note: a search will only ever
4245              match a single key or subkey.  */
4246           if ((node->flag & 1))
4247             {
4248               log_assert (node->pkt->pkttype == PKT_PUBLIC_KEY
4249                           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
4250
4251               if (!agent_probe_secret_key (NULL, node->pkt->pkt.public_key))
4252                 result = 1; /* Secret key available.  */
4253               else
4254                 result = 0;
4255
4256               break;
4257             }
4258         }
4259       release_kbnode (keyblock);
4260     }
4261
4262   keydb_release (kdbhd);
4263   return result;
4264 }