Imported Upstream version 2.1.9
[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 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 <http://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <assert.h>
27 #include <ctype.h>
28
29 #include "gpg.h"
30 #include "util.h"
31 #include "packet.h"
32 #include "iobuf.h"
33 #include "keydb.h"
34 #include "options.h"
35 #include "main.h"
36 #include "trustdb.h"
37 #include "i18n.h"
38 #include "keyserver-internal.h"
39 #include "call-agent.h"
40 #include "host2net.h"
41 #include "mbox-util.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 struct getkey_ctx_s
51 {
52   /* Part of the search criteria: whether the search is an exact
53      search or not.  A search that is exact requires that a key or
54      subkey meet all of the specified criteria.  A search that is not
55      exact allows selecting a different key or subkey from the
56      keyblock that matched the critera.  Further, an exact search
57      returns the key or subkey that matched whereas a non-exact search
58      typically returns the primary key.  See finish_lookup for
59      details.  */
60   int exact;
61
62   /* Part of the search criteria: Whether the caller only wants keys
63      with an available secret key.  This is used by getkey_next to get
64      the next result with the same initial criteria.  */
65   int want_secret;
66
67   /* Part of the search criteria: The type of the requested key.  A
68      mask of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT.
69      If non-zero, then for a key to match, it must implement one of
70      the required uses.  */
71   int req_usage;
72
73   /* The database handle.  */
74   KEYDB_HANDLE kr_handle;
75
76   /* Whether we should call xfree() on the context when the context is
77      released using getkey_end()).  */
78   int not_allocated;
79
80   /* Part of the search criteria: The low-level search specification
81      as passed to keydb_search.  */
82   int nitems;
83   /* This must be the last element in the structure.  When we allocate
84      the structure, we allocate it so that ITEMS can hold NITEMS.  */
85   KEYDB_SEARCH_DESC items[1];
86 };
87
88 #if 0
89 static struct
90 {
91   int any;
92   int okay_count;
93   int nokey_count;
94   int error_count;
95 } lkup_stats[21];
96 #endif
97
98 typedef struct keyid_list
99 {
100   struct keyid_list *next;
101   char fpr[MAX_FINGERPRINT_LEN];
102   u32 keyid[2];
103 } *keyid_list_t;
104
105
106 #if MAX_PK_CACHE_ENTRIES
107 typedef struct pk_cache_entry
108 {
109   struct pk_cache_entry *next;
110   u32 keyid[2];
111   PKT_public_key *pk;
112 } *pk_cache_entry_t;
113 static pk_cache_entry_t pk_cache;
114 static int pk_cache_entries;    /* Number of entries in pk cache.  */
115 static int pk_cache_disabled;
116 #endif
117
118 #if MAX_UID_CACHE_ENTRIES < 5
119 #error we really need the userid cache
120 #endif
121 typedef struct user_id_db
122 {
123   struct user_id_db *next;
124   keyid_list_t keyids;
125   int len;
126   char name[1];
127 } *user_id_db_t;
128 static user_id_db_t user_id_db;
129 static int uid_cache_entries;   /* Number of entries in uid cache. */
130
131 static void merge_selfsigs (kbnode_t keyblock);
132 static int lookup (getkey_ctx_t ctx,
133                    kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
134                    int want_secret);
135
136 #if 0
137 static void
138 print_stats ()
139 {
140   int i;
141   for (i = 0; i < DIM (lkup_stats); i++)
142     {
143       if (lkup_stats[i].any)
144         es_fprintf (es_stderr,
145                  "lookup stats: mode=%-2d  ok=%-6d  nokey=%-6d  err=%-6d\n",
146                  i,
147                  lkup_stats[i].okay_count,
148                  lkup_stats[i].nokey_count, lkup_stats[i].error_count);
149     }
150 }
151 #endif
152
153
154 /* For documentation see keydb.h.  */
155 void
156 cache_public_key (PKT_public_key * pk)
157 {
158 #if MAX_PK_CACHE_ENTRIES
159   pk_cache_entry_t ce, ce2;
160   u32 keyid[2];
161
162   if (pk_cache_disabled)
163     return;
164
165   if (pk->flags.dont_cache)
166     return;
167
168   if (is_ELGAMAL (pk->pubkey_algo)
169       || pk->pubkey_algo == PUBKEY_ALGO_DSA
170       || pk->pubkey_algo == PUBKEY_ALGO_ECDSA
171       || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
172       || pk->pubkey_algo == PUBKEY_ALGO_ECDH
173       || is_RSA (pk->pubkey_algo))
174     {
175       keyid_from_pk (pk, keyid);
176     }
177   else
178     return; /* Don't know how to get the keyid.  */
179
180   for (ce = pk_cache; ce; ce = ce->next)
181     if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
182       {
183         if (DBG_CACHE)
184           log_debug ("cache_public_key: already in cache\n");
185         return;
186       }
187
188   if (pk_cache_entries >= MAX_PK_CACHE_ENTRIES)
189     {
190       int n;
191
192       /* Remove the last 50% of the entries.  */
193       for (ce = pk_cache, n = 0; ce && n < pk_cache_entries/2; n++)
194         ce = ce->next;
195       if (ce != pk_cache && ce->next)
196         {
197           ce2 = ce->next;
198           ce->next = NULL;
199           ce = ce2;
200           for (; ce; ce = ce2)
201             {
202               ce2 = ce->next;
203               free_public_key (ce->pk);
204               xfree (ce);
205               pk_cache_entries--;
206             }
207         }
208       assert (pk_cache_entries < MAX_PK_CACHE_ENTRIES);
209     }
210   pk_cache_entries++;
211   ce = xmalloc (sizeof *ce);
212   ce->next = pk_cache;
213   pk_cache = ce;
214   ce->pk = copy_public_key (NULL, pk);
215   ce->keyid[0] = keyid[0];
216   ce->keyid[1] = keyid[1];
217 #endif
218 }
219
220
221 /* Return a const utf-8 string with the text "[User ID not found]".
222    This function is required so that we don't need to switch gettext's
223    encoding temporary.  */
224 static const char *
225 user_id_not_found_utf8 (void)
226 {
227   static char *text;
228
229   if (!text)
230     text = native_to_utf8 (_("[User ID not found]"));
231   return text;
232 }
233
234
235
236 /* Return the user ID from the given keyblock.
237  * We use the primary uid flag which has been set by the merge_selfsigs
238  * function.  The returned value is only valid as long as the given
239  * keyblock is not changed.  */
240 static const char *
241 get_primary_uid (KBNODE keyblock, size_t * uidlen)
242 {
243   KBNODE k;
244   const char *s;
245
246   for (k = keyblock; k; k = k->next)
247     {
248       if (k->pkt->pkttype == PKT_USER_ID
249           && !k->pkt->pkt.user_id->attrib_data
250           && k->pkt->pkt.user_id->is_primary)
251         {
252           *uidlen = k->pkt->pkt.user_id->len;
253           return k->pkt->pkt.user_id->name;
254         }
255     }
256   s = user_id_not_found_utf8 ();
257   *uidlen = strlen (s);
258   return s;
259 }
260
261
262 static void
263 release_keyid_list (keyid_list_t k)
264 {
265   while (k)
266     {
267       keyid_list_t k2 = k->next;
268       xfree (k);
269       k = k2;
270     }
271 }
272
273 /****************
274  * Store the association of keyid and userid
275  * Feed only public keys to this function.
276  */
277 static void
278 cache_user_id (KBNODE keyblock)
279 {
280   user_id_db_t r;
281   const char *uid;
282   size_t uidlen;
283   keyid_list_t keyids = NULL;
284   KBNODE k;
285
286   for (k = keyblock; k; k = k->next)
287     {
288       if (k->pkt->pkttype == PKT_PUBLIC_KEY
289           || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
290         {
291           keyid_list_t a = xmalloc_clear (sizeof *a);
292           /* Hmmm: For a long list of keyids it might be an advantage
293            * to append the keys.  */
294           fingerprint_from_pk (k->pkt->pkt.public_key, a->fpr, NULL);
295           keyid_from_pk (k->pkt->pkt.public_key, a->keyid);
296           /* First check for duplicates.  */
297           for (r = user_id_db; r; r = r->next)
298             {
299               keyid_list_t b = r->keyids;
300               for (b = r->keyids; b; b = b->next)
301                 {
302                   if (!memcmp (b->fpr, a->fpr, MAX_FINGERPRINT_LEN))
303                     {
304                       if (DBG_CACHE)
305                         log_debug ("cache_user_id: already in cache\n");
306                       release_keyid_list (keyids);
307                       xfree (a);
308                       return;
309                     }
310                 }
311             }
312           /* Now put it into the cache.  */
313           a->next = keyids;
314           keyids = a;
315         }
316     }
317   if (!keyids)
318     BUG (); /* No key no fun.  */
319
320
321   uid = get_primary_uid (keyblock, &uidlen);
322
323   if (uid_cache_entries >= MAX_UID_CACHE_ENTRIES)
324     {
325       /* fixme: use another algorithm to free some cache slots */
326       r = user_id_db;
327       user_id_db = r->next;
328       release_keyid_list (r->keyids);
329       xfree (r);
330       uid_cache_entries--;
331     }
332   r = xmalloc (sizeof *r + uidlen - 1);
333   r->keyids = keyids;
334   r->len = uidlen;
335   memcpy (r->name, uid, r->len);
336   r->next = user_id_db;
337   user_id_db = r;
338   uid_cache_entries++;
339 }
340
341
342 /* For documentation see keydb.h.  */
343 void
344 getkey_disable_caches ()
345 {
346 #if MAX_PK_CACHE_ENTRIES
347   {
348     pk_cache_entry_t ce, ce2;
349
350     for (ce = pk_cache; ce; ce = ce2)
351       {
352         ce2 = ce->next;
353         free_public_key (ce->pk);
354         xfree (ce);
355       }
356     pk_cache_disabled = 1;
357     pk_cache_entries = 0;
358     pk_cache = NULL;
359   }
360 #endif
361   /* fixme: disable user id cache ? */
362 }
363
364
365 static void
366 pk_from_block (GETKEY_CTX ctx, PKT_public_key * pk, KBNODE keyblock,
367                KBNODE found_key)
368 {
369   KBNODE a = found_key ? found_key : keyblock;
370
371   (void) ctx;
372
373   assert (a->pkt->pkttype == PKT_PUBLIC_KEY
374           || a->pkt->pkttype == PKT_PUBLIC_SUBKEY);
375
376   copy_public_key (pk, a->pkt->pkt.public_key);
377 }
378
379
380 /* For documentation see keydb.h.  */
381 int
382 get_pubkey (PKT_public_key * pk, u32 * keyid)
383 {
384   int internal = 0;
385   int rc = 0;
386
387 #if MAX_PK_CACHE_ENTRIES
388   if (pk)
389     {
390       /* Try to get it from the cache.  We don't do this when pk is
391          NULL as it does not guarantee that the user IDs are
392          cached. */
393       pk_cache_entry_t ce;
394       for (ce = pk_cache; ce; ce = ce->next)
395         {
396           if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
397             /* XXX: We don't check PK->REQ_USAGE here, but if we don't
398                read from the cache, we do check it!  */
399             {
400               copy_public_key (pk, ce->pk);
401               return 0;
402             }
403         }
404     }
405 #endif
406   /* More init stuff.  */
407   if (!pk)
408     {
409       pk = xmalloc_clear (sizeof *pk);
410       internal++;
411     }
412
413
414   /* Do a lookup.  */
415   {
416     struct getkey_ctx_s ctx;
417     KBNODE kb = NULL;
418     KBNODE found_key = NULL;
419     memset (&ctx, 0, sizeof ctx);
420     ctx.exact = 1; /* Use the key ID exactly as given.  */
421     ctx.not_allocated = 1;
422     ctx.kr_handle = keydb_new ();
423     ctx.nitems = 1;
424     ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
425     ctx.items[0].u.kid[0] = keyid[0];
426     ctx.items[0].u.kid[1] = keyid[1];
427     ctx.req_usage = pk->req_usage;
428     rc = lookup (&ctx, &kb, &found_key, 0);
429     if (!rc)
430       {
431         pk_from_block (&ctx, pk, kb, found_key);
432       }
433     getkey_end (&ctx);
434     release_kbnode (kb);
435   }
436   if (!rc)
437     goto leave;
438
439   rc = GPG_ERR_NO_PUBKEY;
440
441 leave:
442   if (!rc)
443     cache_public_key (pk);
444   if (internal)
445     free_public_key (pk);
446   return rc;
447 }
448
449
450 /* For documentation see keydb.h.  */
451 int
452 get_pubkey_fast (PKT_public_key * pk, u32 * keyid)
453 {
454   int rc = 0;
455   KEYDB_HANDLE hd;
456   KBNODE keyblock;
457   u32 pkid[2];
458
459   assert (pk);
460 #if MAX_PK_CACHE_ENTRIES
461   {
462     /* Try to get it from the cache */
463     pk_cache_entry_t ce;
464
465     for (ce = pk_cache; ce; ce = ce->next)
466       {
467         if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1]
468             /* Only consider primary keys.  */
469             && ce->pk->keyid[0] == ce->pk->main_keyid[0]
470             && ce->pk->keyid[1] == ce->pk->main_keyid[1])
471           {
472             if (pk)
473               copy_public_key (pk, ce->pk);
474             return 0;
475           }
476       }
477   }
478 #endif
479
480   hd = keydb_new ();
481   rc = keydb_search_kid (hd, keyid);
482   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
483     {
484       keydb_release (hd);
485       return GPG_ERR_NO_PUBKEY;
486     }
487   rc = keydb_get_keyblock (hd, &keyblock);
488   keydb_release (hd);
489   if (rc)
490     {
491       log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
492       return GPG_ERR_NO_PUBKEY;
493     }
494
495   assert (keyblock && keyblock->pkt
496           && keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
497
498   /* We return the primary key.  If KEYID matched a subkey, then we
499      return an error.  */
500   keyid_from_pk (keyblock->pkt->pkt.public_key, pkid);
501   if (keyid[0] == pkid[0] && keyid[1] == pkid[1])
502     copy_public_key (pk, keyblock->pkt->pkt.public_key);
503   else
504     rc = GPG_ERR_NO_PUBKEY;
505
506   release_kbnode (keyblock);
507
508   /* Not caching key here since it won't have all of the fields
509      properly set. */
510
511   return rc;
512 }
513
514
515 /* For documentation see keydb.h.  */
516 KBNODE
517 get_pubkeyblock (u32 * keyid)
518 {
519   struct getkey_ctx_s ctx;
520   int rc = 0;
521   KBNODE keyblock = NULL;
522
523   memset (&ctx, 0, sizeof ctx);
524   /* No need to set exact here because we want the entire block.  */
525   ctx.not_allocated = 1;
526   ctx.kr_handle = keydb_new ();
527   ctx.nitems = 1;
528   ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
529   ctx.items[0].u.kid[0] = keyid[0];
530   ctx.items[0].u.kid[1] = keyid[1];
531   rc = lookup (&ctx, &keyblock, NULL, 0);
532   getkey_end (&ctx);
533
534   return rc ? NULL : keyblock;
535 }
536
537
538 /* For documentation see keydb.h.  */
539 gpg_error_t
540 get_seckey (PKT_public_key *pk, u32 *keyid)
541 {
542   gpg_error_t err;
543   struct getkey_ctx_s ctx;
544   kbnode_t keyblock = NULL;
545   kbnode_t found_key = NULL;
546
547   memset (&ctx, 0, sizeof ctx);
548   ctx.exact = 1; /* Use the key ID exactly as given.  */
549   ctx.not_allocated = 1;
550   ctx.kr_handle = keydb_new ();
551   ctx.nitems = 1;
552   ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
553   ctx.items[0].u.kid[0] = keyid[0];
554   ctx.items[0].u.kid[1] = keyid[1];
555   ctx.req_usage = pk->req_usage;
556   err = lookup (&ctx, &keyblock, &found_key, 1);
557   if (!err)
558     {
559       pk_from_block (&ctx, pk, keyblock, found_key);
560     }
561   getkey_end (&ctx);
562   release_kbnode (keyblock);
563
564   if (!err)
565     {
566       err = agent_probe_secret_key (/*ctrl*/NULL, pk);
567       if (err)
568         release_public_key_parts (pk);
569     }
570
571   return err;
572 }
573
574
575 /* Skip unusable keys.  A key is unusable if it is revoked, expired or
576    disabled or if the selected user id is revoked or expired.  */
577 static int
578 skip_unusable (void *dummy, u32 * keyid, int uid_no)
579 {
580   int unusable = 0;
581   KBNODE keyblock;
582   PKT_public_key *pk;
583
584   (void) dummy;
585
586   keyblock = get_pubkeyblock (keyid);
587   if (!keyblock)
588     {
589       log_error ("error checking usability status of %s\n", keystr (keyid));
590       goto leave;
591     }
592
593   pk = keyblock->pkt->pkt.public_key;
594
595   /* Is the key revoked or expired?  */
596   if (pk->flags.revoked || pk->has_expired)
597     unusable = 1;
598
599   /* Is the user ID in question revoked or expired? */
600   if (!unusable && uid_no)
601     {
602       KBNODE node;
603       int uids_seen = 0;
604
605       for (node = keyblock; node; node = node->next)
606         {
607           if (node->pkt->pkttype == PKT_USER_ID)
608             {
609               PKT_user_id *user_id = node->pkt->pkt.user_id;
610
611               uids_seen ++;
612               if (uids_seen != uid_no)
613                 continue;
614
615               if (user_id->is_revoked || user_id->is_expired)
616                 unusable = 1;
617
618               break;
619             }
620         }
621
622       /* If UID_NO is non-zero, then the keyblock better have at least
623          that many UIDs.  */
624       assert (uids_seen == uid_no);
625     }
626
627   if (!unusable)
628     unusable = pk_is_disabled (pk);
629
630 leave:
631   release_kbnode (keyblock);
632   return unusable;
633 }
634
635
636 /* Search for keys matching some criteria.
637
638    If RETCTX is not NULL, then the constructed context is returned in
639    *RETCTX so that getpubkey_next can be used to get subsequent
640    results.  In this case, getkey_end() must be used to free the
641    search context.  If RETCTX is not NULL, then RET_KDBHD must be
642    NULL.
643
644    If NAMELIST is not NULL, then a search query is constructed using
645    classify_user_id on each of the strings in the list.  (Recall: the
646    database does an OR of the terms, not an AND.)  If NAMELIST is
647    NULL, then all results are returned.
648
649    If PK is not NULL, the public key of the first result is returned
650    in *PK.  Note: PK->REQ_USAGE must be valid!!!  If PK->REQ_USAGE is
651    set, it is used to filter the search results.  See the
652    documentation for finish_lookup to understand exactly how this is
653    used.  Note: The self-signed data has already been merged into the
654    public key using merge_selfsigs.  Free *PK by calling
655    release_public_key_parts (or, if PK was allocated using xfree, you
656    can use free_public_key, which calls release_public_key_parts(PK)
657    and then xfree(PK)).
658
659    If WANT_SECRET is set, then only keys with an available secret key
660    (either locally or via key registered on a smartcard) are returned.
661
662    If INCLUDE_UNUSABLE is set, then unusable keys (see the
663    documentation for skip_unusable for an exact definition) are
664    skipped unless they are looked up by key id or by fingerprint.
665
666    If RET_KB is not NULL, the keyblock is returned in *RET_KB.  This
667    should be freed using release_kbnode().
668
669    If RET_KDBHD is not NULL, then the new database handle used to
670    conduct the search is returned in *RET_KDBHD.  This can be used to
671    get subsequent results using keydb_search_next.  Note: in this
672    case, no advanced filtering is done for subsequent results (e.g.,
673    WANT_SECRET and PK->REQ_USAGE are not respected).
674
675    This function returns 0 on success.  Otherwise, an error code is
676    returned.  In particular, GPG_ERR_NO_PUBKEY or GPG_ERR_NO_SECKEY
677    (if want_secret is set) is returned if the key is not found.  */
678 static int
679 key_byname (GETKEY_CTX *retctx, strlist_t namelist,
680             PKT_public_key *pk,
681             int want_secret, int include_unusable,
682             KBNODE * ret_kb, KEYDB_HANDLE * ret_kdbhd)
683 {
684   int rc = 0;
685   int n;
686   strlist_t r;
687   GETKEY_CTX ctx;
688   KBNODE help_kb = NULL;
689   KBNODE found_key = NULL;
690
691   if (retctx)
692     {
693       /* Reset the returned context in case of error.  */
694       assert (!ret_kdbhd); /* Not allowed because the handle is stored
695                               in the context.  */
696       *retctx = NULL;
697     }
698   if (ret_kdbhd)
699     *ret_kdbhd = NULL;
700
701   if (!namelist)
702     /* No search terms: iterate over the whole DB.  */
703     {
704       ctx = xmalloc_clear (sizeof *ctx);
705       ctx->nitems = 1;
706       ctx->items[0].mode = KEYDB_SEARCH_MODE_FIRST;
707       if (!include_unusable)
708         ctx->items[0].skipfnc = skip_unusable;
709     }
710   else
711     {
712       /* Build the search context.  */
713       for (n = 0, r = namelist; r; r = r->next)
714         n++;
715
716       /* CTX has space for a single search term at the end.  Thus, we
717          need to allocate sizeof *CTX plus (n - 1) sizeof
718          CTX->ITEMS.  */
719       ctx = xmalloc_clear (sizeof *ctx + (n - 1) * sizeof ctx->items);
720       ctx->nitems = n;
721
722       for (n = 0, r = namelist; r; r = r->next, n++)
723         {
724           gpg_error_t err;
725
726           err = classify_user_id (r->d, &ctx->items[n], 1);
727
728           if (ctx->items[n].exact)
729             ctx->exact = 1;
730           if (err)
731             {
732               xfree (ctx);
733               return gpg_err_code (err); /* FIXME: remove gpg_err_code.  */
734             }
735           if (!include_unusable
736               && ctx->items[n].mode != KEYDB_SEARCH_MODE_SHORT_KID
737               && ctx->items[n].mode != KEYDB_SEARCH_MODE_LONG_KID
738               && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR16
739               && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR20
740               && ctx->items[n].mode != KEYDB_SEARCH_MODE_FPR)
741             ctx->items[n].skipfnc = skip_unusable;
742         }
743     }
744
745   ctx->want_secret = want_secret;
746   ctx->kr_handle = keydb_new ();
747   if (!ret_kb)
748     ret_kb = &help_kb;
749
750   if (pk)
751     {
752       ctx->req_usage = pk->req_usage;
753     }
754
755   rc = lookup (ctx, ret_kb, &found_key, want_secret);
756   if (!rc && pk)
757     {
758       pk_from_block (ctx, pk, *ret_kb, found_key);
759     }
760
761   release_kbnode (help_kb);
762
763   if (retctx) /* Caller wants the context.  */
764     *retctx = ctx;
765   else
766     {
767       if (ret_kdbhd)
768         {
769           *ret_kdbhd = ctx->kr_handle;
770           ctx->kr_handle = NULL;
771         }
772       getkey_end (ctx);
773     }
774
775   return rc;
776 }
777
778
779 /* For documentation see keydb.h.  */
780 int
781 get_pubkey_byname (ctrl_t ctrl, GETKEY_CTX * retctx, PKT_public_key * pk,
782                    const char *name, KBNODE * ret_keyblock,
783                    KEYDB_HANDLE * ret_kdbhd, int include_unusable, int no_akl)
784 {
785   int rc;
786   strlist_t namelist = NULL;
787   struct akl *akl;
788   int is_mbox;
789   int nodefault = 0;
790   int anylocalfirst = 0;
791
792   if (retctx)
793     *retctx = NULL;
794
795   /* Does NAME appear to be a mailbox (mail address)?  */
796   is_mbox = is_valid_mailbox (name);
797
798   /* The auto-key-locate feature works as follows: there are a number
799      of methods to look up keys.  By default, the local keyring is
800      tried first.  Then, each method listed in the --auto-key-locate is
801      tried in the order it appears.
802
803      This can be changed as follows:
804
805        - if nodefault appears anywhere in the list of options, then
806          the local keyring is not tried first, or,
807
808        - if local appears anywhere in the list of options, then the
809          local keyring is not tried first, but in the order in which
810          it was listed in the --auto-key-locate option.
811
812      Note: we only save the search context in RETCTX if the local
813      method is the first method tried (either explicitly or
814      implicitly).  */
815   if (!no_akl)
816     /* auto-key-locate is enabled.  */
817     {
818       /* nodefault is true if "nodefault" or "local" appear.  */
819       for (akl = opt.auto_key_locate; akl; akl = akl->next)
820         if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
821           {
822             nodefault = 1;
823             break;
824           }
825       /* anylocalfirst is true if "local" appears before any other
826          search methods (except "nodefault").  */
827       for (akl = opt.auto_key_locate; akl; akl = akl->next)
828         if (akl->type != AKL_NODEFAULT)
829           {
830             if (akl->type == AKL_LOCAL)
831               anylocalfirst = 1;
832             break;
833           }
834     }
835
836   if (!nodefault)
837     /* "nodefault" didn't occur.  Thus, "local" is implicitly the
838        first method to try.  */
839     anylocalfirst = 1;
840
841   if (nodefault && is_mbox)
842     /* Either "nodefault" or "local" (explicitly) appeared in the auto
843        key locate list and NAME appears to be an email address.  Don't
844        try the local keyring.  */
845     {
846       rc = GPG_ERR_NO_PUBKEY;
847     }
848   else
849     /* Either "nodefault" and "local" don't appear in the auto key
850        locate list (in which case we try the local keyring first) or
851        NAME does not appear to be an email address (in which case we
852        only try the local keyring).  In this case, lookup NAME in the
853        local keyring.  */
854     {
855       add_to_strlist (&namelist, name);
856       rc = key_byname (retctx, namelist, pk, 0,
857                        include_unusable, ret_keyblock, ret_kdbhd);
858     }
859
860   /* If the requested name resembles a valid mailbox and automatic
861      retrieval has been enabled, we try to import the key. */
862   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && !no_akl && is_mbox)
863     /* NAME wasn't present in the local keyring (or we didn't try the
864        local keyring).  Since the auto key locate feature is enabled
865        and NAME appears to be an email address, try the auto locate
866        feature.  */
867     {
868       for (akl = opt.auto_key_locate; akl; akl = akl->next)
869         {
870           unsigned char *fpr = NULL;
871           size_t fpr_len;
872           int did_key_byname = 0;
873           int no_fingerprint = 0;
874           const char *mechanism = "?";
875
876           switch (akl->type)
877             {
878             case AKL_NODEFAULT:
879               /* This is a dummy mechanism.  */
880               mechanism = "None";
881               rc = GPG_ERR_NO_PUBKEY;
882               break;
883
884             case AKL_LOCAL:
885               mechanism = "Local";
886               did_key_byname = 1;
887               if (retctx)
888                 {
889                   getkey_end (*retctx);
890                   *retctx = NULL;
891                 }
892               add_to_strlist (&namelist, name);
893               rc = key_byname (anylocalfirst ? retctx : NULL,
894                                namelist, pk, 0,
895                                include_unusable, ret_keyblock, ret_kdbhd);
896               break;
897
898             case AKL_CERT:
899               mechanism = "DNS CERT";
900               glo_ctrl.in_auto_key_retrieve++;
901               rc = keyserver_import_cert (ctrl, name, 0, &fpr, &fpr_len);
902               glo_ctrl.in_auto_key_retrieve--;
903               break;
904
905             case AKL_PKA:
906               mechanism = "PKA";
907               glo_ctrl.in_auto_key_retrieve++;
908               rc = keyserver_import_pka (ctrl, name, &fpr, &fpr_len);
909               glo_ctrl.in_auto_key_retrieve--;
910               break;
911
912             case AKL_DANE:
913               mechanism = "DANE";
914               glo_ctrl.in_auto_key_retrieve++;
915               rc = keyserver_import_cert (ctrl, name, 1, &fpr, &fpr_len);
916               glo_ctrl.in_auto_key_retrieve--;
917               break;
918
919             case AKL_LDAP:
920               mechanism = "LDAP";
921               glo_ctrl.in_auto_key_retrieve++;
922               rc = keyserver_import_ldap (ctrl, name, &fpr, &fpr_len);
923               glo_ctrl.in_auto_key_retrieve--;
924               break;
925
926             case AKL_KEYSERVER:
927               /* Strictly speaking, we don't need to only use a valid
928                  mailbox for the getname search, but it helps cut down
929                  on the problem of searching for something like "john"
930                  and getting a whole lot of keys back. */
931               if (opt.keyserver)
932                 {
933                   mechanism = opt.keyserver->uri;
934                   glo_ctrl.in_auto_key_retrieve++;
935                   rc = keyserver_import_name (ctrl, name, &fpr, &fpr_len,
936                                               opt.keyserver);
937                   glo_ctrl.in_auto_key_retrieve--;
938                 }
939               else
940                 {
941                   mechanism = "Unconfigured keyserver";
942                   rc = GPG_ERR_NO_PUBKEY;
943                 }
944               break;
945
946             case AKL_SPEC:
947               {
948                 struct keyserver_spec *keyserver;
949
950                 mechanism = akl->spec->uri;
951                 keyserver = keyserver_match (akl->spec);
952                 glo_ctrl.in_auto_key_retrieve++;
953                 rc = keyserver_import_name (ctrl,
954                                             name, &fpr, &fpr_len, keyserver);
955                 glo_ctrl.in_auto_key_retrieve--;
956               }
957               break;
958             }
959
960           /* Use the fingerprint of the key that we actually fetched.
961              This helps prevent problems where the key that we fetched
962              doesn't have the same name that we used to fetch it.  In
963              the case of CERT and PKA, this is an actual security
964              requirement as the URL might point to a key put in by an
965              attacker.  By forcing the use of the fingerprint, we
966              won't use the attacker's key here. */
967           if (!rc && fpr)
968             {
969               char fpr_string[MAX_FINGERPRINT_LEN * 2 + 1];
970
971               assert (fpr_len <= MAX_FINGERPRINT_LEN);
972
973               free_strlist (namelist);
974               namelist = NULL;
975
976               bin2hex (fpr, fpr_len, fpr_string);
977
978               if (opt.verbose)
979                 log_info ("auto-key-locate found fingerprint %s\n",
980                           fpr_string);
981
982               add_to_strlist (&namelist, fpr_string);
983             }
984           else if (!rc && !fpr && !did_key_byname)
985             /* The acquisition method said no failure occured, but it
986                didn't return a fingerprint.  That's a failure.  */
987             {
988               no_fingerprint = 1;
989               rc = GPG_ERR_NO_PUBKEY;
990             }
991           xfree (fpr);
992           fpr = NULL;
993
994           if (!rc && !did_key_byname)
995             /* There was no error and we didn't do a local lookup.
996                This means that we imported a key into the local
997                keyring.  Try to read the imported key from the
998                keyring.  */
999             {
1000               if (retctx)
1001                 {
1002                   getkey_end (*retctx);
1003                   *retctx = NULL;
1004                 }
1005               rc = key_byname (anylocalfirst ? retctx : NULL,
1006                                namelist, pk, 0,
1007                                include_unusable, ret_keyblock, ret_kdbhd);
1008             }
1009           if (!rc)
1010             {
1011               /* Key found.  */
1012               log_info (_("automatically retrieved '%s' via %s\n"),
1013                         name, mechanism);
1014               break;
1015             }
1016           if (gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
1017               || opt.verbose || no_fingerprint)
1018             log_info (_("error retrieving '%s' via %s: %s\n"),
1019                       name, mechanism,
1020                       no_fingerprint ? _("No fingerprint") : gpg_strerror (rc));
1021         }
1022     }
1023
1024
1025   if (rc && retctx)
1026     {
1027       getkey_end (*retctx);
1028       *retctx = NULL;
1029     }
1030
1031   free_strlist (namelist);
1032   return rc;
1033 }
1034
1035
1036 /* For documentation see keydb.h.
1037
1038    FIXME: We should replace this with the _byname function.  This can
1039    be done by creating a userID conforming to the unified fingerprint
1040    style.  */
1041 int
1042 get_pubkey_byfprint (PKT_public_key *pk, kbnode_t *r_keyblock,
1043                      const byte * fprint, size_t fprint_len)
1044 {
1045   int rc;
1046
1047   if (r_keyblock)
1048     *r_keyblock = NULL;
1049
1050   if (fprint_len == 20 || fprint_len == 16)
1051     {
1052       struct getkey_ctx_s ctx;
1053       KBNODE kb = NULL;
1054       KBNODE found_key = NULL;
1055
1056       memset (&ctx, 0, sizeof ctx);
1057       ctx.exact = 1;
1058       ctx.not_allocated = 1;
1059       ctx.kr_handle = keydb_new ();
1060       ctx.nitems = 1;
1061       ctx.items[0].mode = fprint_len == 16 ? KEYDB_SEARCH_MODE_FPR16
1062         : KEYDB_SEARCH_MODE_FPR20;
1063       memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1064       rc = lookup (&ctx, &kb, &found_key, 0);
1065       if (!rc && pk)
1066         pk_from_block (&ctx, pk, kb, found_key);
1067       if (!rc && r_keyblock)
1068         {
1069           *r_keyblock = kb;
1070           kb = NULL;
1071         }
1072       release_kbnode (kb);
1073       getkey_end (&ctx);
1074     }
1075   else
1076     rc = GPG_ERR_GENERAL; /* Oops */
1077   return rc;
1078 }
1079
1080
1081 /* For documentation see keydb.h.  */
1082 int
1083 get_pubkey_byfprint_fast (PKT_public_key * pk,
1084                           const byte * fprint, size_t fprint_len)
1085 {
1086   int rc = 0;
1087   KEYDB_HANDLE hd;
1088   KBNODE keyblock;
1089   byte fprbuf[MAX_FINGERPRINT_LEN];
1090   int i;
1091
1092   for (i = 0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1093     fprbuf[i] = fprint[i];
1094   while (i < MAX_FINGERPRINT_LEN)
1095     fprbuf[i++] = 0;
1096
1097   hd = keydb_new ();
1098   rc = keydb_search_fpr (hd, fprbuf);
1099   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
1100     {
1101       keydb_release (hd);
1102       return GPG_ERR_NO_PUBKEY;
1103     }
1104   rc = keydb_get_keyblock (hd, &keyblock);
1105   keydb_release (hd);
1106   if (rc)
1107     {
1108       log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
1109       return GPG_ERR_NO_PUBKEY;
1110     }
1111
1112   assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1113           || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY);
1114   if (pk)
1115     copy_public_key (pk, keyblock->pkt->pkt.public_key);
1116   release_kbnode (keyblock);
1117
1118   /* Not caching key here since it won't have all of the fields
1119      properly set. */
1120
1121   return 0;
1122 }
1123
1124
1125 /* For documentation see keydb.h.  */
1126 gpg_error_t
1127 get_seckey_default (PKT_public_key *pk)
1128 {
1129   gpg_error_t err;
1130   strlist_t namelist = NULL;
1131   int include_unusable = 1;
1132
1133   if (opt.def_secret_key && *opt.def_secret_key)
1134     add_to_strlist (&namelist, opt.def_secret_key);
1135   else
1136     include_unusable = 0;
1137
1138   err = key_byname (NULL, namelist, pk, 1, include_unusable, NULL, NULL);
1139
1140   free_strlist (namelist);
1141
1142   return err;
1143 }
1144 \f
1145 /* For documentation see keydb.h.  */
1146 gpg_error_t
1147 getkey_bynames (getkey_ctx_t *retctx, PKT_public_key *pk,
1148                 strlist_t names, int want_secret, kbnode_t *ret_keyblock)
1149 {
1150   return key_byname (retctx, names, pk, want_secret, 1,
1151                      ret_keyblock, NULL);
1152 }
1153
1154
1155 /* For documentation see keydb.h.  */
1156 gpg_error_t
1157 getkey_byname (getkey_ctx_t *retctx, PKT_public_key *pk,
1158                const char *name, int want_secret, kbnode_t *ret_keyblock)
1159 {
1160   gpg_error_t err;
1161   strlist_t namelist = NULL;
1162   int with_unusable = 1;
1163
1164   if (want_secret && !name && opt.def_secret_key && *opt.def_secret_key)
1165     add_to_strlist (&namelist, opt.def_secret_key);
1166   else if (name)
1167     add_to_strlist (&namelist, name);
1168   else
1169     with_unusable = 0;
1170
1171   err = key_byname (retctx, namelist, pk, want_secret, with_unusable,
1172                     ret_keyblock, NULL);
1173
1174   /* FIXME: Check that we really return GPG_ERR_NO_SECKEY if
1175      WANT_SECRET has been used.  */
1176
1177   free_strlist (namelist);
1178
1179   return err;
1180 }
1181
1182
1183 /* For documentation see keydb.h.  */
1184 gpg_error_t
1185 getkey_next (getkey_ctx_t ctx, PKT_public_key *pk, kbnode_t *ret_keyblock)
1186 {
1187   int rc; /* Fixme:  Make sure this is proper gpg_error */
1188   KBNODE found_key = NULL;
1189
1190   /* We need to disable the caching so that for an exact key search we
1191      won't get the result back from the cache and thus end up in an
1192      endless loop.  The endless loop can occur, because the cache is
1193      used without respecting the current file pointer!  */
1194   keydb_disable_caching (ctx->kr_handle);
1195
1196   rc = lookup (ctx, ret_keyblock, &found_key, ctx->want_secret);
1197   if (!rc && pk && ret_keyblock)
1198     pk_from_block (ctx, pk, *ret_keyblock, found_key);
1199
1200   return rc;
1201 }
1202
1203
1204 /* For documentation see keydb.h.  */
1205 void
1206 getkey_end (getkey_ctx_t ctx)
1207 {
1208   if (ctx)
1209     {
1210       keydb_release (ctx->kr_handle);
1211       if (!ctx->not_allocated)
1212         xfree (ctx);
1213     }
1214 }
1215
1216
1217 \f
1218 /************************************************
1219  ************* Merging stuff ********************
1220  ************************************************/
1221
1222 /* For documentation see keydb.h.  */
1223 void
1224 setup_main_keyids (kbnode_t keyblock)
1225 {
1226   u32 kid[2], mainkid[2];
1227   kbnode_t kbctx, node;
1228   PKT_public_key *pk;
1229
1230   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1231     BUG ();
1232   pk = keyblock->pkt->pkt.public_key;
1233
1234   keyid_from_pk (pk, mainkid);
1235   for (kbctx=NULL; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1236     {
1237       if (!(node->pkt->pkttype == PKT_PUBLIC_KEY
1238             || node->pkt->pkttype == PKT_PUBLIC_SUBKEY))
1239         continue;
1240       pk = node->pkt->pkt.public_key;
1241       keyid_from_pk (pk, kid); /* Make sure pk->keyid is set.  */
1242       if (!pk->main_keyid[0] && !pk->main_keyid[1])
1243         {
1244           pk->main_keyid[0] = mainkid[0];
1245           pk->main_keyid[1] = mainkid[1];
1246         }
1247     }
1248 }
1249
1250
1251 /* For documentation see keydb.h.  */
1252 void
1253 merge_keys_and_selfsig (KBNODE keyblock)
1254 {
1255   if (!keyblock)
1256     ;
1257   else if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
1258     merge_selfsigs (keyblock);
1259   else
1260     log_debug ("FIXME: merging secret key blocks is not anymore available\n");
1261 }
1262
1263
1264 static int
1265 parse_key_usage (PKT_signature * sig)
1266 {
1267   int key_usage = 0;
1268   const byte *p;
1269   size_t n;
1270   byte flags;
1271
1272   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n);
1273   if (p && n)
1274     {
1275       /* First octet of the keyflags.  */
1276       flags = *p;
1277
1278       if (flags & 1)
1279         {
1280           key_usage |= PUBKEY_USAGE_CERT;
1281           flags &= ~1;
1282         }
1283
1284       if (flags & 2)
1285         {
1286           key_usage |= PUBKEY_USAGE_SIG;
1287           flags &= ~2;
1288         }
1289
1290       /* We do not distinguish between encrypting communications and
1291          encrypting storage. */
1292       if (flags & (0x04 | 0x08))
1293         {
1294           key_usage |= PUBKEY_USAGE_ENC;
1295           flags &= ~(0x04 | 0x08);
1296         }
1297
1298       if (flags & 0x20)
1299         {
1300           key_usage |= PUBKEY_USAGE_AUTH;
1301           flags &= ~0x20;
1302         }
1303
1304       if (flags)
1305         key_usage |= PUBKEY_USAGE_UNKNOWN;
1306
1307       if (!key_usage)
1308         key_usage |= PUBKEY_USAGE_NONE;
1309     }
1310   else if (p) /* Key flags of length zero.  */
1311     key_usage |= PUBKEY_USAGE_NONE;
1312
1313   /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1314      capability that we do not handle.  This serves to distinguish
1315      between a zero key usage which we handle as the default
1316      capabilities for that algorithm, and a usage that we do not
1317      handle.  Likewise we use PUBKEY_USAGE_NONE to indicate that
1318      key_flags have been given but they do not specify any usage.  */
1319
1320   return key_usage;
1321 }
1322
1323
1324 /* Apply information from SIGNODE (which is the valid self-signature
1325  * associated with that UID) to the UIDNODE:
1326  * - weather the UID has been revoked
1327  * - assumed creation date of the UID
1328  * - temporary store the keyflags here
1329  * - temporary store the key expiration time here
1330  * - mark whether the primary user ID flag hat been set.
1331  * - store the preferences
1332  */
1333 static void
1334 fixup_uidnode (KBNODE uidnode, KBNODE signode, u32 keycreated)
1335 {
1336   PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1337   PKT_signature *sig = signode->pkt->pkt.signature;
1338   const byte *p, *sym, *hash, *zip;
1339   size_t n, nsym, nhash, nzip;
1340
1341   sig->flags.chosen_selfsig = 1;/* We chose this one. */
1342   uid->created = 0;             /* Not created == invalid. */
1343   if (IS_UID_REV (sig))
1344     {
1345       uid->is_revoked = 1;
1346       return; /* Has been revoked.  */
1347     }
1348   else
1349     uid->is_revoked = 0;
1350
1351   uid->expiredate = sig->expiredate;
1352
1353   if (sig->flags.expired)
1354     {
1355       uid->is_expired = 1;
1356       return; /* Has expired.  */
1357     }
1358   else
1359     uid->is_expired = 0;
1360
1361   uid->created = sig->timestamp; /* This one is okay. */
1362   uid->selfsigversion = sig->version;
1363   /* If we got this far, it's not expired :) */
1364   uid->is_expired = 0;
1365
1366   /* Store the key flags in the helper variable for later processing.  */
1367   uid->help_key_usage = parse_key_usage (sig);
1368
1369   /* Ditto for the key expiration.  */
1370   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1371   if (p && buf32_to_u32 (p))
1372     uid->help_key_expire = keycreated + buf32_to_u32 (p);
1373   else
1374     uid->help_key_expire = 0;
1375
1376   /* Set the primary user ID flag - we will later wipe out some
1377    * of them to only have one in our keyblock.  */
1378   uid->is_primary = 0;
1379   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL);
1380   if (p && *p)
1381     uid->is_primary = 2;
1382
1383   /* We could also query this from the unhashed area if it is not in
1384    * the hased area and then later try to decide which is the better
1385    * there should be no security problem with this.
1386    * For now we only look at the hashed one.  */
1387
1388   /* Now build the preferences list.  These must come from the
1389      hashed section so nobody can modify the ciphers a key is
1390      willing to accept.  */
1391   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM, &n);
1392   sym = p;
1393   nsym = p ? n : 0;
1394   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH, &n);
1395   hash = p;
1396   nhash = p ? n : 0;
1397   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR, &n);
1398   zip = p;
1399   nzip = p ? n : 0;
1400   if (uid->prefs)
1401     xfree (uid->prefs);
1402   n = nsym + nhash + nzip;
1403   if (!n)
1404     uid->prefs = NULL;
1405   else
1406     {
1407       uid->prefs = xmalloc (sizeof (*uid->prefs) * (n + 1));
1408       n = 0;
1409       for (; nsym; nsym--, n++)
1410         {
1411           uid->prefs[n].type = PREFTYPE_SYM;
1412           uid->prefs[n].value = *sym++;
1413         }
1414       for (; nhash; nhash--, n++)
1415         {
1416           uid->prefs[n].type = PREFTYPE_HASH;
1417           uid->prefs[n].value = *hash++;
1418         }
1419       for (; nzip; nzip--, n++)
1420         {
1421           uid->prefs[n].type = PREFTYPE_ZIP;
1422           uid->prefs[n].value = *zip++;
1423         }
1424       uid->prefs[n].type = PREFTYPE_NONE; /* End of list marker  */
1425       uid->prefs[n].value = 0;
1426     }
1427
1428   /* See whether we have the MDC feature.  */
1429   uid->flags.mdc = 0;
1430   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1431   if (p && n && (p[0] & 0x01))
1432     uid->flags.mdc = 1;
1433
1434   /* And the keyserver modify flag.  */
1435   uid->flags.ks_modify = 1;
1436   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1437   if (p && n && (p[0] & 0x80))
1438     uid->flags.ks_modify = 0;
1439 }
1440
1441 static void
1442 sig_to_revoke_info (PKT_signature * sig, struct revoke_info *rinfo)
1443 {
1444   rinfo->date = sig->timestamp;
1445   rinfo->algo = sig->pubkey_algo;
1446   rinfo->keyid[0] = sig->keyid[0];
1447   rinfo->keyid[1] = sig->keyid[1];
1448 }
1449
1450
1451 /* Given a keyblock, parse the key block and extract various pieces of
1452    information and save them with the primary key packet and the user
1453    id packets.  For instance, some information is stored in signature
1454    packets.  We find the latest such valid packet (since the user can
1455    change that information) and copy its contents into the
1456    PKT_public_key.
1457
1458    Note that R_REVOKED may be set to 0, 1 or 2.
1459
1460    This function fills in the following fields in the primary key's
1461    keyblock:
1462
1463      main_keyid          (computed)
1464      revkey / numrevkeys (derived from self signed key data)
1465      flags.valid         (whether we have at least 1 self-sig)
1466      flags.maybe_revoked (whether a designed revoked the key, but
1467                           we are missing the key to check the sig)
1468      selfsigversion      (highest version of any valid self-sig)
1469      pubkey_usage        (derived from most recent self-sig or most
1470                           recent user id)
1471      has_expired         (various sources)
1472      expiredate          (various sources)
1473
1474   See the documentation for fixup_uidnode for how the user id packets
1475   are modified.  In addition to that the primary user id's is_primary
1476   field is set to 1 and the other user id's is_primary are set to
1477   0.  */
1478 static void
1479 merge_selfsigs_main (KBNODE keyblock, int *r_revoked,
1480                      struct revoke_info *rinfo)
1481 {
1482   PKT_public_key *pk = NULL;
1483   KBNODE k;
1484   u32 kid[2];
1485   u32 sigdate, uiddate, uiddate2;
1486   KBNODE signode, uidnode, uidnode2;
1487   u32 curtime = make_timestamp ();
1488   unsigned int key_usage = 0;
1489   u32 keytimestamp = 0;
1490   u32 key_expire = 0;
1491   int key_expire_seen = 0;
1492   byte sigversion = 0;
1493
1494   *r_revoked = 0;
1495   memset (rinfo, 0, sizeof (*rinfo));
1496
1497   /* Section 11.1 of RFC 4880 determines the order of packets within a
1498      message.  There are three sections, which must occur in the
1499      following order: the public key, the user ids and user attributes
1500      and the subkeys.  Within each section, each primary packet (e.g.,
1501      a user id packet) is followed by one or more signature packets,
1502      which modify that packet.  */
1503
1504   /* According to Section 11.1 of RFC 4880, the public key must be the
1505      first packet.  */
1506   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
1507     /* parse_keyblock_image ensures that the first packet is the
1508        public key.  */
1509     BUG ();
1510   pk = keyblock->pkt->pkt.public_key;
1511   keytimestamp = pk->timestamp;
1512
1513   keyid_from_pk (pk, kid);
1514   pk->main_keyid[0] = kid[0];
1515   pk->main_keyid[1] = kid[1];
1516
1517   if (pk->version < 4)
1518     {
1519       /* Before v4 the key packet itself contains the expiration date
1520        * and there was no way to change it, so we start with the one
1521        * from the key packet.  */
1522       key_expire = pk->max_expiredate;
1523       key_expire_seen = 1;
1524     }
1525
1526   /* First pass:
1527
1528       - Find the latest direct key self-signature.  We assume that the
1529         newest one overrides all others.
1530
1531       - Determine whether the key has been revoked.
1532
1533       - Gather all revocation keys (unlike other data, we don't just
1534         take them from the latest self-signed packet).
1535
1536       - Determine max (sig[...]->version).
1537    */
1538
1539   /* Reset this in case this key was already merged. */
1540   xfree (pk->revkey);
1541   pk->revkey = NULL;
1542   pk->numrevkeys = 0;
1543
1544   signode = NULL;
1545   sigdate = 0; /* Helper variable to find the latest signature.  */
1546
1547   /* According to Section 11.1 of RFC 4880, the public key comes first
1548      and is immediately followed by any signature packets that modify
1549      it.  */
1550   for (k = keyblock;
1551        k && k->pkt->pkttype != PKT_USER_ID
1552          && k->pkt->pkttype != PKT_ATTRIBUTE
1553          && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1554        k = k->next)
1555     {
1556       if (k->pkt->pkttype == PKT_SIGNATURE)
1557         {
1558           PKT_signature *sig = k->pkt->pkt.signature;
1559           if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1560             /* Self sig.  */
1561             {
1562               if (check_key_signature (keyblock, k, NULL))
1563                 ; /* Signature did not verify.  */
1564               else if (IS_KEY_REV (sig))
1565                 {
1566                   /* Key has been revoked - there is no way to
1567                    * override such a revocation, so we theoretically
1568                    * can stop now.  We should not cope with expiration
1569                    * times for revocations here because we have to
1570                    * assume that an attacker can generate all kinds of
1571                    * signatures.  However due to the fact that the key
1572                    * has been revoked it does not harm either and by
1573                    * continuing we gather some more info on that
1574                    * key.  */
1575                   *r_revoked = 1;
1576                   sig_to_revoke_info (sig, rinfo);
1577                 }
1578               else if (IS_KEY_SIG (sig))
1579                 {
1580                   /* Add the indicated revocations keys from all
1581                      signatures not just the latest.  We do this
1582                      because you need multiple 1F sigs to properly
1583                      handle revocation keys (PGP does it this way, and
1584                      a revocation key could be sensitive and hence in
1585                      a different signature). */
1586                   if (sig->revkey)
1587                     {
1588                       int i;
1589
1590                       pk->revkey =
1591                         xrealloc (pk->revkey, sizeof (struct revocation_key) *
1592                                   (pk->numrevkeys + sig->numrevkeys));
1593
1594                       for (i = 0; i < sig->numrevkeys; i++)
1595                         memcpy (&pk->revkey[pk->numrevkeys++],
1596                                 &sig->revkey[i],
1597                                 sizeof (struct revocation_key));
1598                     }
1599
1600                   if (sig->timestamp >= sigdate)
1601                     /* This is the latest signature so far.  */
1602                     {
1603                       if (sig->flags.expired)
1604                         ; /* Signature has expired - ignore it.  */
1605                       else
1606                         {
1607                           sigdate = sig->timestamp;
1608                           signode = k;
1609                           if (sig->version > sigversion)
1610                             sigversion = sig->version;
1611
1612                         }
1613                     }
1614                 }
1615             }
1616         }
1617     }
1618
1619   /* Remove dupes from the revocation keys.  */
1620   if (pk->revkey)
1621     {
1622       int i, j, x, changed = 0;
1623
1624       for (i = 0; i < pk->numrevkeys; i++)
1625         {
1626           for (j = i + 1; j < pk->numrevkeys; j++)
1627             {
1628               if (memcmp (&pk->revkey[i], &pk->revkey[j],
1629                           sizeof (struct revocation_key)) == 0)
1630                 {
1631                   /* remove j */
1632
1633                   for (x = j; x < pk->numrevkeys - 1; x++)
1634                     pk->revkey[x] = pk->revkey[x + 1];
1635
1636                   pk->numrevkeys--;
1637                   j--;
1638                   changed = 1;
1639                 }
1640             }
1641         }
1642
1643       if (changed)
1644         pk->revkey = xrealloc (pk->revkey,
1645                                pk->numrevkeys *
1646                                sizeof (struct revocation_key));
1647     }
1648
1649   if (signode)
1650     /* SIGNODE is the 1F signature packet with the latest creation
1651        time.  Extract some information from it.  */
1652     {
1653       /* Some information from a direct key signature take precedence
1654        * over the same information given in UID sigs.  */
1655       PKT_signature *sig = signode->pkt->pkt.signature;
1656       const byte *p;
1657
1658       key_usage = parse_key_usage (sig);
1659
1660       p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1661       if (p && buf32_to_u32 (p))
1662         {
1663           key_expire = keytimestamp + buf32_to_u32 (p);
1664           key_expire_seen = 1;
1665         }
1666
1667       /* Mark that key as valid: One direct key signature should
1668        * render a key as valid.  */
1669       pk->flags.valid = 1;
1670     }
1671
1672   /* Pass 1.5: Look for key revocation signatures that were not made
1673      by the key (i.e. did a revocation key issue a revocation for
1674      us?).  Only bother to do this if there is a revocation key in the
1675      first place and we're not revoked already.  */
1676
1677   if (!*r_revoked && pk->revkey)
1678     for (k = keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next)
1679       {
1680         if (k->pkt->pkttype == PKT_SIGNATURE)
1681           {
1682             PKT_signature *sig = k->pkt->pkt.signature;
1683
1684             if (IS_KEY_REV (sig) &&
1685                 (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1]))
1686               {
1687                 int rc = check_revocation_keys (pk, sig);
1688                 if (rc == 0)
1689                   {
1690                     *r_revoked = 2;
1691                     sig_to_revoke_info (sig, rinfo);
1692                     /* Don't continue checking since we can't be any
1693                        more revoked than this.  */
1694                     break;
1695                   }
1696                 else if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
1697                   pk->flags.maybe_revoked = 1;
1698
1699                 /* A failure here means the sig did not verify, was
1700                    not issued by a revocation key, or a revocation
1701                    key loop was broken.  If a revocation key isn't
1702                    findable, however, the key might be revoked and
1703                    we don't know it.  */
1704
1705                 /* TODO: In the future handle subkey and cert
1706                    revocations?  PGP doesn't, but it's in 2440. */
1707               }
1708           }
1709       }
1710
1711   /* Second pass: Look at the self-signature of all user IDs.  */
1712
1713   /* According to RFC 4880 section 11.1, user id and attribute packets
1714      are in the second section, after the public key packet and before
1715      the subkey packets.  */
1716   signode = uidnode = NULL;
1717   sigdate = 0; /* Helper variable to find the latest signature in one UID. */
1718   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1719     {
1720       if (k->pkt->pkttype == PKT_USER_ID || k->pkt->pkttype == PKT_ATTRIBUTE)
1721         /* New user id packet.  */
1722         {
1723           if (uidnode && signode)
1724             /* Apply the data from the most recent self-signed packet
1725                to the preceding user id packet.  */
1726             {
1727               fixup_uidnode (uidnode, signode, keytimestamp);
1728               pk->flags.valid = 1;
1729             }
1730           /* Clear SIGNODE.  The only relevant self-signed data for
1731              UIDNODE follows it.  */
1732           if (k->pkt->pkttype == PKT_USER_ID)
1733             uidnode = k;
1734           else
1735             uidnode = NULL;
1736           signode = NULL;
1737           sigdate = 0;
1738         }
1739       else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1740         {
1741           PKT_signature *sig = k->pkt->pkt.signature;
1742           if (sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1])
1743             {
1744               if (check_key_signature (keyblock, k, NULL))
1745                 ;               /* signature did not verify */
1746               else if ((IS_UID_SIG (sig) || IS_UID_REV (sig))
1747                        && sig->timestamp >= sigdate)
1748                 {
1749                   /* Note: we allow to invalidate cert revocations
1750                    * by a newer signature.  An attacker can't use this
1751                    * because a key should be revoked with a key revocation.
1752                    * The reason why we have to allow for that is that at
1753                    * one time an email address may become invalid but later
1754                    * the same email address may become valid again (hired,
1755                    * fired, hired again).  */
1756
1757                   sigdate = sig->timestamp;
1758                   signode = k;
1759                   signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
1760                   if (sig->version > sigversion)
1761                     sigversion = sig->version;
1762                 }
1763             }
1764         }
1765     }
1766   if (uidnode && signode)
1767     {
1768       fixup_uidnode (uidnode, signode, keytimestamp);
1769       pk->flags.valid = 1;
1770     }
1771
1772   /* If the key isn't valid yet, and we have
1773      --allow-non-selfsigned-uid set, then force it valid. */
1774   if (!pk->flags.valid && opt.allow_non_selfsigned_uid)
1775     {
1776       if (opt.verbose)
1777         log_info (_("Invalid key %s made valid by"
1778                     " --allow-non-selfsigned-uid\n"), keystr_from_pk (pk));
1779       pk->flags.valid = 1;
1780     }
1781
1782   /* The key STILL isn't valid, so try and find an ultimately
1783      trusted signature. */
1784   if (!pk->flags.valid)
1785     {
1786       uidnode = NULL;
1787
1788       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1789            k = k->next)
1790         {
1791           if (k->pkt->pkttype == PKT_USER_ID)
1792             uidnode = k;
1793           else if (k->pkt->pkttype == PKT_SIGNATURE && uidnode)
1794             {
1795               PKT_signature *sig = k->pkt->pkt.signature;
1796
1797               if (sig->keyid[0] != kid[0] || sig->keyid[1] != kid[1])
1798                 {
1799                   PKT_public_key *ultimate_pk;
1800
1801                   ultimate_pk = xmalloc_clear (sizeof (*ultimate_pk));
1802
1803                   /* We don't want to use the full get_pubkey to
1804                      avoid infinite recursion in certain cases.
1805                      There is no reason to check that an ultimately
1806                      trusted key is still valid - if it has been
1807                      revoked the user should also remove the
1808                      ultimate trust flag.  */
1809                   if (get_pubkey_fast (ultimate_pk, sig->keyid) == 0
1810                       && check_key_signature2 (keyblock, k, ultimate_pk,
1811                                                NULL, NULL, NULL, NULL) == 0
1812                       && get_ownertrust (ultimate_pk) == TRUST_ULTIMATE)
1813                     {
1814                       free_public_key (ultimate_pk);
1815                       pk->flags.valid = 1;
1816                       break;
1817                     }
1818
1819                   free_public_key (ultimate_pk);
1820                 }
1821             }
1822         }
1823     }
1824
1825   /* Record the highest selfsig version so we know if this is a v3
1826      key through and through, or a v3 key with a v4 selfsig
1827      somewhere.  This is useful in a few places to know if the key
1828      must be treated as PGP2-style or OpenPGP-style.  Note that a
1829      selfsig revocation with a higher version number will also raise
1830      this value.  This is okay since such a revocation must be
1831      issued by the user (i.e. it cannot be issued by someone else to
1832      modify the key behavior.) */
1833
1834   pk->selfsigversion = sigversion;
1835
1836   /* Now that we had a look at all user IDs we can now get some information
1837    * from those user IDs.
1838    */
1839
1840   if (!key_usage)
1841     {
1842       /* Find the latest user ID with key flags set. */
1843       uiddate = 0; /* Helper to find the latest user ID.  */
1844       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1845            k = k->next)
1846         {
1847           if (k->pkt->pkttype == PKT_USER_ID)
1848             {
1849               PKT_user_id *uid = k->pkt->pkt.user_id;
1850               if (uid->help_key_usage && uid->created > uiddate)
1851                 {
1852                   key_usage = uid->help_key_usage;
1853                   uiddate = uid->created;
1854                 }
1855             }
1856         }
1857     }
1858   if (!key_usage)
1859     {
1860       /* No key flags at all: get it from the algo.  */
1861       key_usage = openpgp_pk_algo_usage (pk->pubkey_algo);
1862     }
1863   else
1864     {
1865       /* Check that the usage matches the usage as given by the algo.  */
1866       int x = openpgp_pk_algo_usage (pk->pubkey_algo);
1867       if (x) /* Mask it down to the actual allowed usage.  */
1868         key_usage &= x;
1869     }
1870
1871   /* Whatever happens, it's a primary key, so it can certify. */
1872   pk->pubkey_usage = key_usage | PUBKEY_USAGE_CERT;
1873
1874   if (!key_expire_seen)
1875     {
1876       /* Find the latest valid user ID with a key expiration set
1877        * Note, that this may be a different one from the above because
1878        * some user IDs may have no expiration date set.  */
1879       uiddate = 0;
1880       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1881            k = k->next)
1882         {
1883           if (k->pkt->pkttype == PKT_USER_ID)
1884             {
1885               PKT_user_id *uid = k->pkt->pkt.user_id;
1886               if (uid->help_key_expire && uid->created > uiddate)
1887                 {
1888                   key_expire = uid->help_key_expire;
1889                   uiddate = uid->created;
1890                 }
1891             }
1892         }
1893     }
1894
1895   /* Currently only v3 keys have a maximum expiration date, but I'll
1896      bet v5 keys get this feature again. */
1897   if (key_expire == 0
1898       || (pk->max_expiredate && key_expire > pk->max_expiredate))
1899     key_expire = pk->max_expiredate;
1900
1901   pk->has_expired = key_expire >= curtime ? 0 : key_expire;
1902   pk->expiredate = key_expire;
1903
1904   /* Fixme: we should see how to get rid of the expiretime fields  but
1905    * this needs changes at other places too. */
1906
1907   /* And now find the real primary user ID and delete all others.  */
1908   uiddate = uiddate2 = 0;
1909   uidnode = uidnode2 = NULL;
1910   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
1911     {
1912       if (k->pkt->pkttype == PKT_USER_ID && !k->pkt->pkt.user_id->attrib_data)
1913         {
1914           PKT_user_id *uid = k->pkt->pkt.user_id;
1915           if (uid->is_primary)
1916             {
1917               if (uid->created > uiddate)
1918                 {
1919                   uiddate = uid->created;
1920                   uidnode = k;
1921                 }
1922               else if (uid->created == uiddate && uidnode)
1923                 {
1924                   /* The dates are equal, so we need to do a
1925                      different (and arbitrary) comparison.  This
1926                      should rarely, if ever, happen.  It's good to
1927                      try and guarantee that two different GnuPG
1928                      users with two different keyrings at least pick
1929                      the same primary. */
1930                   if (cmp_user_ids (uid, uidnode->pkt->pkt.user_id) > 0)
1931                     uidnode = k;
1932                 }
1933             }
1934           else
1935             {
1936               if (uid->created > uiddate2)
1937                 {
1938                   uiddate2 = uid->created;
1939                   uidnode2 = k;
1940                 }
1941               else if (uid->created == uiddate2 && uidnode2)
1942                 {
1943                   if (cmp_user_ids (uid, uidnode2->pkt->pkt.user_id) > 0)
1944                     uidnode2 = k;
1945                 }
1946             }
1947         }
1948     }
1949   if (uidnode)
1950     {
1951       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1952            k = k->next)
1953         {
1954           if (k->pkt->pkttype == PKT_USER_ID &&
1955               !k->pkt->pkt.user_id->attrib_data)
1956             {
1957               PKT_user_id *uid = k->pkt->pkt.user_id;
1958               if (k != uidnode)
1959                 uid->is_primary = 0;
1960             }
1961         }
1962     }
1963   else if (uidnode2)
1964     {
1965       /* None is flagged primary - use the latest user ID we have,
1966          and disambiguate with the arbitrary packet comparison. */
1967       uidnode2->pkt->pkt.user_id->is_primary = 1;
1968     }
1969   else
1970     {
1971       /* None of our uids were self-signed, so pick the one that
1972          sorts first to be the primary.  This is the best we can do
1973          here since there are no self sigs to date the uids. */
1974
1975       uidnode = NULL;
1976
1977       for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1978            k = k->next)
1979         {
1980           if (k->pkt->pkttype == PKT_USER_ID
1981               && !k->pkt->pkt.user_id->attrib_data)
1982             {
1983               if (!uidnode)
1984                 {
1985                   uidnode = k;
1986                   uidnode->pkt->pkt.user_id->is_primary = 1;
1987                   continue;
1988                 }
1989               else
1990                 {
1991                   if (cmp_user_ids (k->pkt->pkt.user_id,
1992                                     uidnode->pkt->pkt.user_id) > 0)
1993                     {
1994                       uidnode->pkt->pkt.user_id->is_primary = 0;
1995                       uidnode = k;
1996                       uidnode->pkt->pkt.user_id->is_primary = 1;
1997                     }
1998                   else
1999                     k->pkt->pkt.user_id->is_primary = 0;        /* just to be
2000                                                                    safe */
2001                 }
2002             }
2003         }
2004     }
2005 }
2006
2007 /* Convert a buffer to a signature.  Useful for 0x19 embedded sigs.
2008    Caller must free the signature when they are done. */
2009 static PKT_signature *
2010 buf_to_sig (const byte * buf, size_t len)
2011 {
2012   PKT_signature *sig = xmalloc_clear (sizeof (PKT_signature));
2013   IOBUF iobuf = iobuf_temp_with_content (buf, len);
2014   int save_mode = set_packet_list_mode (0);
2015
2016   if (parse_signature (iobuf, PKT_SIGNATURE, len, sig) != 0)
2017     {
2018       xfree (sig);
2019       sig = NULL;
2020     }
2021
2022   set_packet_list_mode (save_mode);
2023   iobuf_close (iobuf);
2024
2025   return sig;
2026 }
2027
2028 /* Use the self-signed data to fill in various fields in subkeys.
2029
2030    KEYBLOCK is the whole keyblock.  SUBNODE is the subkey to fill in.
2031
2032    Sets the following fields on the subkey:
2033
2034      main_keyid
2035      flags.valid        if the subkey has a valid self-sig binding
2036      flags.revoked
2037      flags.backsig
2038      pubkey_usage
2039      has_expired
2040      expired_date
2041
2042    On this subkey's most revent valid self-signed packet, the
2043    following field is set:
2044
2045      flags.chosen_selfsig
2046   */
2047 static void
2048 merge_selfsigs_subkey (KBNODE keyblock, KBNODE subnode)
2049 {
2050   PKT_public_key *mainpk = NULL, *subpk = NULL;
2051   PKT_signature *sig;
2052   KBNODE k;
2053   u32 mainkid[2];
2054   u32 sigdate = 0;
2055   KBNODE signode;
2056   u32 curtime = make_timestamp ();
2057   unsigned int key_usage = 0;
2058   u32 keytimestamp = 0;
2059   u32 key_expire = 0;
2060   const byte *p;
2061
2062   if (subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2063     BUG ();
2064   mainpk = keyblock->pkt->pkt.public_key;
2065   if (mainpk->version < 4)
2066     return;/* (actually this should never happen) */
2067   keyid_from_pk (mainpk, mainkid);
2068   subpk = subnode->pkt->pkt.public_key;
2069   keytimestamp = subpk->timestamp;
2070
2071   subpk->flags.valid = 0;
2072   subpk->main_keyid[0] = mainpk->main_keyid[0];
2073   subpk->main_keyid[1] = mainpk->main_keyid[1];
2074
2075   /* Find the latest key binding self-signature.  */
2076   signode = NULL;
2077   sigdate = 0; /* Helper to find the latest signature.  */
2078   for (k = subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2079        k = k->next)
2080     {
2081       if (k->pkt->pkttype == PKT_SIGNATURE)
2082         {
2083           sig = k->pkt->pkt.signature;
2084           if (sig->keyid[0] == mainkid[0] && sig->keyid[1] == mainkid[1])
2085             {
2086               if (check_key_signature (keyblock, k, NULL))
2087                 ; /* Signature did not verify.  */
2088               else if (IS_SUBKEY_REV (sig))
2089                 {
2090                   /* Note that this means that the date on a
2091                      revocation sig does not matter - even if the
2092                      binding sig is dated after the revocation sig,
2093                      the subkey is still marked as revoked.  This
2094                      seems ok, as it is just as easy to make new
2095                      subkeys rather than re-sign old ones as the
2096                      problem is in the distribution.  Plus, PGP (7)
2097                      does this the same way.  */
2098                   subpk->flags.revoked = 1;
2099                   sig_to_revoke_info (sig, &subpk->revoked);
2100                   /* Although we could stop now, we continue to
2101                    * figure out other information like the old expiration
2102                    * time.  */
2103                 }
2104               else if (IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate)
2105                 {
2106                   if (sig->flags.expired)
2107                     ; /* Signature has expired - ignore it.  */
2108                   else
2109                     {
2110                       sigdate = sig->timestamp;
2111                       signode = k;
2112                       signode->pkt->pkt.signature->flags.chosen_selfsig = 0;
2113                     }
2114                 }
2115             }
2116         }
2117     }
2118
2119   /* No valid key binding.  */
2120   if (!signode)
2121     return;
2122
2123   sig = signode->pkt->pkt.signature;
2124   sig->flags.chosen_selfsig = 1; /* So we know which selfsig we chose later.  */
2125
2126   key_usage = parse_key_usage (sig);
2127   if (!key_usage)
2128     {
2129       /* No key flags at all: get it from the algo.  */
2130       key_usage = openpgp_pk_algo_usage (subpk->pubkey_algo);
2131     }
2132   else
2133     {
2134       /* Check that the usage matches the usage as given by the algo.  */
2135       int x = openpgp_pk_algo_usage (subpk->pubkey_algo);
2136       if (x) /* Mask it down to the actual allowed usage.  */
2137         key_usage &= x;
2138     }
2139
2140   subpk->pubkey_usage = key_usage;
2141
2142   p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2143   if (p && buf32_to_u32 (p))
2144     key_expire = keytimestamp + buf32_to_u32 (p);
2145   else
2146     key_expire = 0;
2147   subpk->has_expired = key_expire >= curtime ? 0 : key_expire;
2148   subpk->expiredate = key_expire;
2149
2150   /* Algo doesn't exist.  */
2151   if (openpgp_pk_test_algo (subpk->pubkey_algo))
2152     return;
2153
2154   subpk->flags.valid = 1;
2155
2156   /* Find the most recent 0x19 embedded signature on our self-sig. */
2157   if (!subpk->flags.backsig)
2158     {
2159       int seq = 0;
2160       size_t n;
2161       PKT_signature *backsig = NULL;
2162
2163       sigdate = 0;
2164
2165       /* We do this while() since there may be other embedded
2166          signatures in the future.  We only want 0x19 here. */
2167
2168       while ((p = enum_sig_subpkt (sig->hashed,
2169                                    SIGSUBPKT_SIGNATURE, &n, &seq, NULL)))
2170         if (n > 3
2171             && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2172           {
2173             PKT_signature *tempsig = buf_to_sig (p, n);
2174             if (tempsig)
2175               {
2176                 if (tempsig->timestamp > sigdate)
2177                   {
2178                     if (backsig)
2179                       free_seckey_enc (backsig);
2180
2181                     backsig = tempsig;
2182                     sigdate = backsig->timestamp;
2183                   }
2184                 else
2185                   free_seckey_enc (tempsig);
2186               }
2187           }
2188
2189       seq = 0;
2190
2191       /* It is safe to have this in the unhashed area since the 0x19
2192          is located on the selfsig for convenience, not security. */
2193
2194       while ((p = enum_sig_subpkt (sig->unhashed, SIGSUBPKT_SIGNATURE,
2195                                    &n, &seq, NULL)))
2196         if (n > 3
2197             && ((p[0] == 3 && p[2] == 0x19) || (p[0] == 4 && p[1] == 0x19)))
2198           {
2199             PKT_signature *tempsig = buf_to_sig (p, n);
2200             if (tempsig)
2201               {
2202                 if (tempsig->timestamp > sigdate)
2203                   {
2204                     if (backsig)
2205                       free_seckey_enc (backsig);
2206
2207                     backsig = tempsig;
2208                     sigdate = backsig->timestamp;
2209                   }
2210                 else
2211                   free_seckey_enc (tempsig);
2212               }
2213           }
2214
2215       if (backsig)
2216         {
2217           /* At ths point, backsig contains the most recent 0x19 sig.
2218              Let's see if it is good. */
2219
2220           /* 2==valid, 1==invalid, 0==didn't check */
2221           if (check_backsig (mainpk, subpk, backsig) == 0)
2222             subpk->flags.backsig = 2;
2223           else
2224             subpk->flags.backsig = 1;
2225
2226           free_seckey_enc (backsig);
2227         }
2228     }
2229 }
2230
2231
2232 /* Merge information from the self-signatures with the public key,
2233    subkeys and user ids to make using them more easy.
2234
2235    See documentation for merge_selfsigs_main, merge_selfsigs_subkey
2236    and fixup_uidnode for exactly which fields are updated.  */
2237 static void
2238 merge_selfsigs (KBNODE keyblock)
2239 {
2240   KBNODE k;
2241   int revoked;
2242   struct revoke_info rinfo;
2243   PKT_public_key *main_pk;
2244   prefitem_t *prefs;
2245   unsigned int mdc_feature;
2246
2247   if (keyblock->pkt->pkttype != PKT_PUBLIC_KEY)
2248     {
2249       if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
2250         {
2251           log_error ("expected public key but found secret key "
2252                      "- must stop\n");
2253           /* We better exit here because a public key is expected at
2254              other places too.  FIXME: Figure this out earlier and
2255              don't get to here at all */
2256           g10_exit (1);
2257         }
2258       BUG ();
2259     }
2260
2261   merge_selfsigs_main (keyblock, &revoked, &rinfo);
2262
2263   /* Now merge in the data from each of the subkeys.  */
2264   for (k = keyblock; k; k = k->next)
2265     {
2266       if (k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2267         {
2268           merge_selfsigs_subkey (keyblock, k);
2269         }
2270     }
2271
2272   main_pk = keyblock->pkt->pkt.public_key;
2273   if (revoked || main_pk->has_expired || !main_pk->flags.valid)
2274     {
2275       /* If the primary key is revoked, expired, or invalid we
2276        * better set the appropriate flags on that key and all
2277        * subkeys.  */
2278       for (k = keyblock; k; k = k->next)
2279         {
2280           if (k->pkt->pkttype == PKT_PUBLIC_KEY
2281               || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2282             {
2283               PKT_public_key *pk = k->pkt->pkt.public_key;
2284               if (!main_pk->flags.valid)
2285                 pk->flags.valid = 0;
2286               if (revoked && !pk->flags.revoked)
2287                 {
2288                   pk->flags.revoked = revoked;
2289                   memcpy (&pk->revoked, &rinfo, sizeof (rinfo));
2290                 }
2291               if (main_pk->has_expired)
2292                 pk->has_expired = main_pk->has_expired;
2293             }
2294         }
2295       return;
2296     }
2297
2298   /* Set the preference list of all keys to those of the primary real
2299    * user ID.  Note: we use these preferences when we don't know by
2300    * which user ID the key has been selected.
2301    * fixme: we should keep atoms of commonly used preferences or
2302    * use reference counting to optimize the preference lists storage.
2303    * FIXME: it might be better to use the intersection of
2304    * all preferences.
2305    * Do a similar thing for the MDC feature flag.  */
2306   prefs = NULL;
2307   mdc_feature = 0;
2308   for (k = keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next)
2309     {
2310       if (k->pkt->pkttype == PKT_USER_ID
2311           && !k->pkt->pkt.user_id->attrib_data
2312           && k->pkt->pkt.user_id->is_primary)
2313         {
2314           prefs = k->pkt->pkt.user_id->prefs;
2315           mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2316           break;
2317         }
2318     }
2319   for (k = keyblock; k; k = k->next)
2320     {
2321       if (k->pkt->pkttype == PKT_PUBLIC_KEY
2322           || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2323         {
2324           PKT_public_key *pk = k->pkt->pkt.public_key;
2325           if (pk->prefs)
2326             xfree (pk->prefs);
2327           pk->prefs = copy_prefs (prefs);
2328           pk->flags.mdc = mdc_feature;
2329         }
2330     }
2331 }
2332
2333
2334 \f
2335 /* See whether the key satisfies any additional requirements specified
2336    in CTX.  If so, return 1 and set CTX->FOUND_KEY to an appropriate
2337    key or subkey.  Otherwise, return 0 if there was no appropriate
2338    key.
2339
2340    In case the primary key is not required, select a suitable subkey.
2341    We need the primary key if PUBKEY_USAGE_CERT is set in
2342    CTX->REQ_USAGE or we are in PGP6 or PGP7 mode and PUBKEY_USAGE_SIG
2343    is set in CTX->REQ_USAGE.
2344
2345    If any of PUBKEY_USAGE_SIG, PUBKEY_USAGE_ENC and PUBKEY_USAGE_CERT
2346    are set in CTX->REQ_USAGE, we filter by the key's function.
2347    Concretely, if PUBKEY_USAGE_SIG and PUBKEY_USAGE_CERT are set, then
2348    we only return a key if it is (at least) either a signing or a
2349    certification key.
2350
2351    If CTX->REQ_USAGE is set, then we reject any keys that are not good
2352    (i.e., valid, not revoked, not expired, etc.).  This allows the
2353    getkey functions to be used for plain key listings.
2354
2355    Sets the matched key's user id field (pk->user_id) to the user id
2356    that matched the low-level search criteria or NULL.
2357
2358
2359    This function needs to handle several different cases:
2360
2361     1. No requested usage and no primary key requested
2362        Examples for this case are that we have a keyID to be used
2363        for decrytion or verification.
2364     2. No usage but primary key requested
2365        This is the case for all functions which work on an
2366        entire keyblock, e.g. for editing or listing
2367     3. Usage and primary key requested
2368        FXME
2369     4. Usage but no primary key requested
2370        FIXME
2371
2372  */
2373 static KBNODE
2374 finish_lookup (GETKEY_CTX ctx, KBNODE keyblock)
2375 {
2376   KBNODE k;
2377
2378   /* If CTX->EXACT is set, the key or subkey that actually matched the
2379      low-level search criteria.  */
2380   KBNODE foundk = NULL;
2381   /* The user id (if any) that matched the low-level search criteria.  */
2382   PKT_user_id *foundu = NULL;
2383
2384 #define USAGE_MASK  (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2385   unsigned int req_usage = (ctx->req_usage & USAGE_MASK);
2386
2387   /* Request the primary if we're certifying another key, and also
2388      if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2389      do not understand signatures made by a signing subkey.  PGP 8
2390      does. */
2391   int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2392     ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2393
2394   u32 curtime = make_timestamp ();
2395
2396   u32 latest_date;
2397   KBNODE latest_key;
2398
2399   assert (keyblock->pkt->pkttype == PKT_PUBLIC_KEY);
2400
2401   if (ctx->exact)
2402     /* Get the key or subkey that matched the low-level search
2403        criteria.  */
2404     {
2405       for (k = keyblock; k; k = k->next)
2406         {
2407           if ((k->flag & 1))
2408             {
2409               assert (k->pkt->pkttype == PKT_PUBLIC_KEY
2410                       || k->pkt->pkttype == PKT_PUBLIC_SUBKEY);
2411               foundk = k;
2412               break;
2413             }
2414         }
2415     }
2416
2417   /* Get the user id that matched that low-level search criteria.  */
2418   for (k = keyblock; k; k = k->next)
2419     {
2420       if ((k->flag & 2))
2421         {
2422           assert (k->pkt->pkttype == PKT_USER_ID);
2423           foundu = k->pkt->pkt.user_id;
2424           break;
2425         }
2426     }
2427
2428   if (DBG_LOOKUP)
2429     log_debug ("finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2430                (ulong) keyid_from_pk (keyblock->pkt->pkt.public_key, NULL),
2431                foundk ? "one" : "all", req_usage);
2432
2433   if (!req_usage)
2434     {
2435       latest_key = foundk ? foundk : keyblock;
2436       goto found;
2437     }
2438
2439   latest_date = 0;
2440   latest_key = NULL;
2441   /* Set latest_key to the latest (the one with the most recent
2442      timestamp) good (valid, not revoked, not expired, etc.) subkey.
2443
2444      Don't bother if we are only looking for a primary key or we need
2445      an exact match and the exact match is not a subkey.  */
2446   if (req_prim || (foundk && foundk->pkt->pkttype != PKT_PUBLIC_SUBKEY))
2447     ;
2448   else
2449     {
2450       KBNODE nextk;
2451
2452       /* Either start a loop or check just this one subkey.  */
2453       for (k = foundk ? foundk : keyblock; k; k = nextk)
2454         {
2455           PKT_public_key *pk;
2456
2457           if (foundk)
2458             /* If FOUNDK is not NULL, then only consider that exact
2459                key, i.e., don't iterate.  */
2460             nextk = NULL;
2461           else
2462             nextk = k->next;
2463
2464           if (k->pkt->pkttype != PKT_PUBLIC_SUBKEY)
2465             continue;
2466
2467           pk = k->pkt->pkt.public_key;
2468           if (DBG_LOOKUP)
2469             log_debug ("\tchecking subkey %08lX\n",
2470                        (ulong) keyid_from_pk (pk, NULL));
2471           if (!pk->flags.valid)
2472             {
2473               if (DBG_LOOKUP)
2474                 log_debug ("\tsubkey not valid\n");
2475               continue;
2476             }
2477           if (pk->flags.revoked)
2478             {
2479               if (DBG_LOOKUP)
2480                 log_debug ("\tsubkey has been revoked\n");
2481               continue;
2482             }
2483           if (pk->has_expired)
2484             {
2485               if (DBG_LOOKUP)
2486                 log_debug ("\tsubkey has expired\n");
2487               continue;
2488             }
2489           if (pk->timestamp > curtime && !opt.ignore_valid_from)
2490             {
2491               if (DBG_LOOKUP)
2492                 log_debug ("\tsubkey not yet valid\n");
2493               continue;
2494             }
2495
2496           if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2497             {
2498               if (DBG_LOOKUP)
2499                 log_debug ("\tusage does not match: want=%x have=%x\n",
2500                            req_usage, pk->pubkey_usage);
2501               continue;
2502             }
2503
2504           if (DBG_LOOKUP)
2505             log_debug ("\tsubkey might be fine\n");
2506           /* In case a key has a timestamp of 0 set, we make sure
2507              that it is used.  A better change would be to compare
2508              ">=" but that might also change the selected keys and
2509              is as such a more intrusive change.  */
2510           if (pk->timestamp > latest_date || (!pk->timestamp && !latest_date))
2511             {
2512               latest_date = pk->timestamp;
2513               latest_key = k;
2514             }
2515         }
2516     }
2517
2518   /* Check if the primary key is ok (valid, not revoke, not expire,
2519      matches requested usage) if:
2520
2521        - we didn't find an appropriate subkey and we're not doing an
2522          exact search,
2523
2524        - we're doing an exact match and the exact match was the
2525          primary key, or,
2526
2527        - we're just considering the primary key.  */
2528   if ((!latest_key && !ctx->exact) || foundk == keyblock || req_prim)
2529     {
2530       PKT_public_key *pk;
2531       if (DBG_LOOKUP && !foundk && !req_prim)
2532         log_debug ("\tno suitable subkeys found - trying primary\n");
2533       pk = keyblock->pkt->pkt.public_key;
2534       if (!pk->flags.valid)
2535         {
2536           if (DBG_LOOKUP)
2537             log_debug ("\tprimary key not valid\n");
2538         }
2539       else if (pk->flags.revoked)
2540         {
2541           if (DBG_LOOKUP)
2542             log_debug ("\tprimary key has been revoked\n");
2543         }
2544       else if (pk->has_expired)
2545         {
2546           if (DBG_LOOKUP)
2547             log_debug ("\tprimary key has expired\n");
2548         }
2549       else if (!((pk->pubkey_usage & USAGE_MASK) & req_usage))
2550         {
2551           if (DBG_LOOKUP)
2552             log_debug ("\tprimary key usage does not match: "
2553                        "want=%x have=%x\n", req_usage, pk->pubkey_usage);
2554         }
2555       else /* Okay.  */
2556         {
2557           if (DBG_LOOKUP)
2558             log_debug ("\tprimary key may be used\n");
2559           latest_key = keyblock;
2560           latest_date = pk->timestamp;
2561         }
2562     }
2563
2564   if (!latest_key)
2565     {
2566       if (DBG_LOOKUP)
2567         log_debug ("\tno suitable key found -  giving up\n");
2568       return NULL; /* Not found.  */
2569     }
2570
2571 found:
2572   if (DBG_LOOKUP)
2573     log_debug ("\tusing key %08lX\n",
2574                (ulong) keyid_from_pk (latest_key->pkt->pkt.public_key, NULL));
2575
2576   if (latest_key)
2577     {
2578       PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2579       if (pk->user_id)
2580         free_user_id (pk->user_id);
2581       pk->user_id = scopy_user_id (foundu);
2582     }
2583
2584   if (latest_key != keyblock && opt.verbose)
2585     {
2586       char *tempkeystr =
2587         xstrdup (keystr_from_pk (latest_key->pkt->pkt.public_key));
2588       log_info (_("using subkey %s instead of primary key %s\n"),
2589                 tempkeystr, keystr_from_pk (keyblock->pkt->pkt.public_key));
2590       xfree (tempkeystr);
2591     }
2592
2593   cache_user_id (keyblock);
2594
2595   return latest_key ? latest_key : keyblock; /* Found.  */
2596 }
2597
2598
2599 /* Return true if all the search modes are fingerprints.  */
2600 static int
2601 search_modes_are_fingerprint (getkey_ctx_t ctx)
2602 {
2603   size_t n, found;
2604
2605   for (n=found=0; n < ctx->nitems; n++)
2606     {
2607       switch (ctx->items[n].mode)
2608         {
2609         case KEYDB_SEARCH_MODE_FPR16:
2610         case KEYDB_SEARCH_MODE_FPR20:
2611         case KEYDB_SEARCH_MODE_FPR:
2612           found++;
2613           break;
2614         default:
2615           break;
2616         }
2617     }
2618   return found && found == ctx->nitems;
2619 }
2620
2621
2622 /* A high-level function to lookup keys.
2623
2624    This function builds on top of the low-level keydb API.  It first
2625    searches the database using the description stored in CTX->ITEMS,
2626    then it filters the results using CTX and, finally, if WANT_SECRET
2627    is set, it ignores any keys for which no secret key is available.
2628
2629    Note: this function skips any legacy keys unless the search mode is
2630    KEYDB_SEARCH_MODE_FIRST or KEYDB_SEARCH_MODE_NEXT or we are
2631    searching by fingerprint.
2632
2633    Unlike the low-level search functions, this function also merges
2634    all of the self-signed data into the keys, subkeys and user id
2635    packets (see the merge_selfsigs for details).
2636
2637    On success the key's keyblock is stored at *RET_KEYBLOCK.  */
2638 static int
2639 lookup (getkey_ctx_t ctx, kbnode_t *ret_keyblock, kbnode_t *ret_found_key,
2640         int want_secret)
2641 {
2642   int rc;
2643   int no_suitable_key = 0;
2644   KBNODE keyblock = NULL;
2645   KBNODE found_key = NULL;
2646
2647   for (;;)
2648     {
2649       rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems, NULL);
2650
2651       /* Skip over all legacy keys unless we are iterating over all
2652          keys in the DB or the key was requested by its fingerprint.
2653
2654          Fixme: The lower level keydb code should actually do that but
2655          then it would be harder to report the number of skipped
2656          legacy keys during import. */
2657       if (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
2658           && !(ctx->nitems && (ctx->items->mode == KEYDB_SEARCH_MODE_FIRST
2659                                || ctx->items->mode == KEYDB_SEARCH_MODE_NEXT))
2660           && !search_modes_are_fingerprint (ctx))
2661         continue;
2662       if (rc)
2663         break;
2664
2665       /* If we are iterating over the entire database, then we need to
2666          change from KEYDB_SEARCH_MODE_FIRST, which does an implicit
2667          reset, to KEYDB_SEARCH_MODE_NEXT, which gets the next
2668          record.  */
2669       if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2670         ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2671
2672       rc = keydb_get_keyblock (ctx->kr_handle, &keyblock);
2673       if (rc)
2674         {
2675           log_error ("keydb_get_keyblock failed: %s\n", gpg_strerror (rc));
2676           rc = 0;
2677           goto skip;
2678         }
2679
2680       if (want_secret && agent_probe_any_secret_key (NULL, keyblock))
2681         goto skip; /* No secret key available.  */
2682
2683       /* Warning: node flag bits 0 and 1 should be preserved by
2684        * merge_selfsigs.  For secret keys, premerge transferred the
2685        * keys to the keyblock.  */
2686       merge_selfsigs (keyblock);
2687       found_key = finish_lookup (ctx, keyblock);
2688       if (found_key)
2689         {
2690           no_suitable_key = 0;
2691           goto found;
2692         }
2693       else
2694         no_suitable_key = 1;
2695
2696     skip:
2697       /* Release resources and continue search. */
2698       release_kbnode (keyblock);
2699       keyblock = NULL;
2700       /* The keyblock cache ignores the current "file position".
2701          Thus, if we request the next result and the cache matches
2702          (and it will since it is what we just looked for), we'll get
2703          the same entry back!  We can avoid this infinite loop by
2704          disabling the cache.  */
2705       keydb_disable_caching (ctx->kr_handle);
2706     }
2707
2708 found:
2709   if (rc && gpg_err_code (rc) != GPG_ERR_NOT_FOUND
2710       && gpg_err_code (rc) != GPG_ERR_LEGACY_KEY)
2711     log_error ("keydb_search failed: %s\n", gpg_strerror (rc));
2712
2713   if (!rc)
2714     {
2715       *ret_keyblock = keyblock; /* Return the keyblock.  */
2716       keyblock = NULL;
2717     }
2718   else if ((gpg_err_code (rc) == GPG_ERR_NOT_FOUND
2719             || gpg_err_code (rc) == GPG_ERR_LEGACY_KEY) && no_suitable_key)
2720     rc = want_secret? GPG_ERR_UNUSABLE_SECKEY : GPG_ERR_UNUSABLE_PUBKEY;
2721   else if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2722     rc = want_secret? GPG_ERR_NO_SECKEY : GPG_ERR_NO_PUBKEY;
2723
2724   release_kbnode (keyblock);
2725
2726   if (ret_found_key)
2727     {
2728       if (! rc)
2729         *ret_found_key = found_key;
2730       else
2731         *ret_found_key = NULL;
2732     }
2733
2734   return rc;
2735 }
2736
2737
2738 /* For documentation see keydb.h.  */
2739 gpg_error_t
2740 enum_secret_keys (void **context, PKT_public_key *sk)
2741 {
2742   gpg_error_t err = 0;
2743   const char *name;
2744   struct
2745   {
2746     int eof;
2747     int state;
2748     strlist_t sl;
2749     kbnode_t keyblock;
2750     kbnode_t node;
2751   } *c = *context;
2752
2753   if (!c)
2754     {
2755       /* Make a new context.  */
2756       c = xtrycalloc (1, sizeof *c);
2757       if (!c)
2758         return gpg_error_from_syserror ();
2759       *context = c;
2760     }
2761
2762   if (!sk)
2763     {
2764       /* Free the context.  */
2765       release_kbnode (c->keyblock);
2766       xfree (c);
2767       *context = NULL;
2768       return 0;
2769     }
2770
2771   if (c->eof)
2772     return gpg_error (GPG_ERR_EOF);
2773
2774   for (;;)
2775     {
2776       /* Loop until we have a keyblock.  */
2777       while (!c->keyblock)
2778         {
2779           /* Loop over the list of secret keys.  */
2780           do
2781             {
2782               name = NULL;
2783               switch (c->state)
2784                 {
2785                 case 0: /* First try to use the --default-key.  */
2786                   if (opt.def_secret_key && *opt.def_secret_key)
2787                     name = opt.def_secret_key;
2788                   c->state = 1;
2789                   break;
2790
2791                 case 1: /* Init list of keys to try.  */
2792                   c->sl = opt.secret_keys_to_try;
2793                   c->state++;
2794                   break;
2795
2796                 case 2: /* Get next item from list.  */
2797                   if (c->sl)
2798                     {
2799                       name = c->sl->d;
2800                       c->sl = c->sl->next;
2801                     }
2802                   else
2803                     c->state++;
2804                   break;
2805
2806                 default: /* No more names to check - stop.  */
2807                   c->eof = 1;
2808                   return gpg_error (GPG_ERR_EOF);
2809                 }
2810             }
2811           while (!name || !*name);
2812
2813           err = getkey_byname (NULL, NULL, name, 1, &c->keyblock);
2814           if (err)
2815             {
2816               /* getkey_byname might return a keyblock even in the
2817                  error case - I have not checked.  Thus better release
2818                  it.  */
2819               release_kbnode (c->keyblock);
2820               c->keyblock = NULL;
2821             }
2822           else
2823             c->node = c->keyblock;
2824         }
2825
2826       /* Get the next key from the current keyblock.  */
2827       for (; c->node; c->node = c->node->next)
2828         {
2829           if (c->node->pkt->pkttype == PKT_PUBLIC_KEY
2830               || c->node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
2831             {
2832               copy_public_key (sk, c->node->pkt->pkt.public_key);
2833               c->node = c->node->next;
2834               return 0; /* Found.  */
2835             }
2836         }
2837
2838       /* Dispose the keyblock and continue.  */
2839       release_kbnode (c->keyblock);
2840       c->keyblock = NULL;
2841     }
2842 }
2843
2844 \f
2845 /*********************************************
2846  ***********  User ID printing helpers *******
2847  *********************************************/
2848
2849 /* Return a string with a printable representation of the user_id.
2850  * this string must be freed by xfree.   */
2851 static char *
2852 get_user_id_string (u32 * keyid, int mode, size_t *r_len)
2853 {
2854   user_id_db_t r;
2855   keyid_list_t a;
2856   int pass = 0;
2857   char *p;
2858
2859   /* Try it two times; second pass reads from the database.  */
2860   do
2861     {
2862       for (r = user_id_db; r; r = r->next)
2863         {
2864           for (a = r->keyids; a; a = a->next)
2865             {
2866               if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
2867                 {
2868                   if (mode == 2)
2869                     {
2870                       /* An empty string as user id is possible.  Make
2871                          sure that the malloc allocates one byte and
2872                          does not bail out.  */
2873                       p = xmalloc (r->len? r->len : 1);
2874                       memcpy (p, r->name, r->len);
2875                       if (r_len)
2876                         *r_len = r->len;
2877                     }
2878                   else
2879                     {
2880                       if (mode)
2881                         p = xasprintf ("%08lX%08lX %.*s",
2882                                        (ulong) keyid[0], (ulong) keyid[1],
2883                                        r->len, r->name);
2884                       else
2885                         p = xasprintf ("%s %.*s", keystr (keyid),
2886                                        r->len, r->name);
2887                       if (r_len)
2888                         *r_len = strlen (p);
2889                     }
2890
2891                   return p;
2892                 }
2893             }
2894         }
2895     }
2896   while (++pass < 2 && !get_pubkey (NULL, keyid));
2897
2898   if (mode == 2)
2899     p = xstrdup (user_id_not_found_utf8 ());
2900   else if (mode)
2901     p = xasprintf ("%08lX%08lX [?]", (ulong) keyid[0], (ulong) keyid[1]);
2902   else
2903     p = xasprintf ("%s [?]", keystr (keyid));
2904
2905   if (r_len)
2906     *r_len = strlen (p);
2907   return p;
2908 }
2909
2910
2911 char *
2912 get_user_id_string_native (u32 * keyid)
2913 {
2914   char *p = get_user_id_string (keyid, 0, NULL);
2915   char *p2 = utf8_to_native (p, strlen (p), 0);
2916   xfree (p);
2917   return p2;
2918 }
2919
2920
2921 char *
2922 get_long_user_id_string (u32 * keyid)
2923 {
2924   return get_user_id_string (keyid, 1, NULL);
2925 }
2926
2927
2928 /* Please try to use get_user_byfpr instead of this one.  */
2929 char *
2930 get_user_id (u32 * keyid, size_t * rn)
2931 {
2932   return get_user_id_string (keyid, 2, rn);
2933 }
2934
2935
2936 /* Please try to use get_user_id_byfpr_native instead of this one.  */
2937 char *
2938 get_user_id_native (u32 * keyid)
2939 {
2940   size_t rn;
2941   char *p = get_user_id (keyid, &rn);
2942   char *p2 = utf8_to_native (p, rn, 0);
2943   xfree (p);
2944   return p2;
2945 }
2946
2947
2948 /* Return the user id for a key designated by its fingerprint, FPR,
2949    which must be MAX_FINGERPRINT_LEN bytes in size.  Note: the
2950    returned string, which must be freed using xfree, may not be NUL
2951    terminated.  To determine the length of the string, you must use
2952    *RN.  */
2953 char *
2954 get_user_id_byfpr (const byte *fpr, size_t *rn)
2955 {
2956   user_id_db_t r;
2957   char *p;
2958   int pass = 0;
2959
2960   /* Try it two times; second pass reads from the database.  */
2961   do
2962     {
2963       for (r = user_id_db; r; r = r->next)
2964         {
2965           keyid_list_t a;
2966           for (a = r->keyids; a; a = a->next)
2967             {
2968               if (!memcmp (a->fpr, fpr, MAX_FINGERPRINT_LEN))
2969                 {
2970                   /* An empty string as user id is possible.  Make
2971                      sure that the malloc allocates one byte and does
2972                      not bail out.  */
2973                   p = xmalloc (r->len? r->len : 1);
2974                   memcpy (p, r->name, r->len);
2975                   *rn = r->len;
2976                   return p;
2977                 }
2978             }
2979         }
2980     }
2981   while (++pass < 2
2982          && !get_pubkey_byfprint (NULL, NULL, fpr, MAX_FINGERPRINT_LEN));
2983   p = xstrdup (user_id_not_found_utf8 ());
2984   *rn = strlen (p);
2985   return p;
2986 }
2987
2988 /* Like get_user_id_byfpr, but convert the string to the native
2989    encoding.  The returned string needs to be freed.  Unlike
2990    get_user_id_byfpr, the returned string is NUL terminated.  */
2991 char *
2992 get_user_id_byfpr_native (const byte *fpr)
2993 {
2994   size_t rn;
2995   char *p = get_user_id_byfpr (fpr, &rn);
2996   char *p2 = utf8_to_native (p, rn, 0);
2997   xfree (p);
2998   return p2;
2999 }
3000
3001
3002
3003 /* For documentation see keydb.h.  */
3004 KEYDB_HANDLE
3005 get_ctx_handle (GETKEY_CTX ctx)
3006 {
3007   return ctx->kr_handle;
3008 }
3009
3010 static void
3011 free_akl (struct akl *akl)
3012 {
3013   if (! akl)
3014     return;
3015
3016   if (akl->spec)
3017     free_keyserver_spec (akl->spec);
3018
3019   xfree (akl);
3020 }
3021
3022 void
3023 release_akl (void)
3024 {
3025   while (opt.auto_key_locate)
3026     {
3027       struct akl *akl2 = opt.auto_key_locate;
3028       opt.auto_key_locate = opt.auto_key_locate->next;
3029       free_akl (akl2);
3030     }
3031 }
3032
3033 /* Returns false on error. */
3034 int
3035 parse_auto_key_locate (char *options)
3036 {
3037   char *tok;
3038
3039   while ((tok = optsep (&options)))
3040     {
3041       struct akl *akl, *check, *last = NULL;
3042       int dupe = 0;
3043
3044       if (tok[0] == '\0')
3045         continue;
3046
3047       akl = xmalloc_clear (sizeof (*akl));
3048
3049       if (ascii_strcasecmp (tok, "clear") == 0)
3050         {
3051           xfree (akl);
3052           free_akl (opt.auto_key_locate);
3053           opt.auto_key_locate = NULL;
3054           continue;
3055         }
3056       else if (ascii_strcasecmp (tok, "nodefault") == 0)
3057         akl->type = AKL_NODEFAULT;
3058       else if (ascii_strcasecmp (tok, "local") == 0)
3059         akl->type = AKL_LOCAL;
3060       else if (ascii_strcasecmp (tok, "ldap") == 0)
3061         akl->type = AKL_LDAP;
3062       else if (ascii_strcasecmp (tok, "keyserver") == 0)
3063         akl->type = AKL_KEYSERVER;
3064 #ifdef USE_DNS_CERT
3065       else if (ascii_strcasecmp (tok, "cert") == 0)
3066         akl->type = AKL_CERT;
3067 #endif
3068       else if (ascii_strcasecmp (tok, "pka") == 0)
3069         akl->type = AKL_PKA;
3070       else if (ascii_strcasecmp (tok, "dane") == 0)
3071         akl->type = AKL_DANE;
3072       else if ((akl->spec = parse_keyserver_uri (tok, 1)))
3073         akl->type = AKL_SPEC;
3074       else
3075         {
3076           free_akl (akl);
3077           return 0;
3078         }
3079
3080       /* We must maintain the order the user gave us */
3081       for (check = opt.auto_key_locate; check;
3082            last = check, check = check->next)
3083         {
3084           /* Check for duplicates */
3085           if (check->type == akl->type
3086               && (akl->type != AKL_SPEC
3087                   || (akl->type == AKL_SPEC
3088                       && strcmp (check->spec->uri, akl->spec->uri) == 0)))
3089             {
3090               dupe = 1;
3091               free_akl (akl);
3092               break;
3093             }
3094         }
3095
3096       if (!dupe)
3097         {
3098           if (last)
3099             last->next = akl;
3100           else
3101             opt.auto_key_locate = akl;
3102         }
3103     }
3104
3105   return 1;
3106 }
3107
3108
3109 /* For documentation see keydb.h.  */
3110 int
3111 have_secret_key_with_kid (u32 *keyid)
3112 {
3113   gpg_error_t err;
3114   KEYDB_HANDLE kdbhd;
3115   KEYDB_SEARCH_DESC desc;
3116   kbnode_t keyblock;
3117   kbnode_t node;
3118   int result = 0;
3119
3120   kdbhd = keydb_new ();
3121   memset (&desc, 0, sizeof desc);
3122   desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
3123   desc.u.kid[0] = keyid[0];
3124   desc.u.kid[1] = keyid[1];
3125   while (!result)
3126     {
3127       err = keydb_search (kdbhd, &desc, 1, NULL);
3128       if (gpg_err_code (err) == GPG_ERR_LEGACY_KEY)
3129         continue;
3130       if (err)
3131         break;
3132
3133       err = keydb_get_keyblock (kdbhd, &keyblock);
3134       if (err)
3135         {
3136           log_error (_("error reading keyblock: %s\n"), gpg_strerror (err));
3137           break;
3138         }
3139
3140       for (node = keyblock; node; node = node->next)
3141         {
3142           /* Bit 0 of the flags is set if the search found the key
3143              using that key or subkey.  Note: a search will only ever
3144              match a single key or subkey.  */
3145           if ((node->flag & 1))
3146             {
3147               assert (node->pkt->pkttype == PKT_PUBLIC_KEY
3148                       || node->pkt->pkttype == PKT_PUBLIC_SUBKEY);
3149
3150               if (agent_probe_secret_key (NULL, node->pkt->pkt.public_key) == 0)
3151                 /* Not available.  */
3152                 result = 1;
3153               else
3154                 result = 0;
3155
3156               break;
3157             }
3158         }
3159       release_kbnode (keyblock);
3160     }
3161
3162   keydb_release (kdbhd);
3163   return result;
3164 }