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