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