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