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