LCOV - code coverage report
Current view: top level - g10 - getkey.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 783 1314 59.6 %
Date: 2015-11-05 17:10:59 Functions: 34 47 72.3 %

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

Generated by: LCOV version 1.11