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