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