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