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