LCOV - code coverage report
Current view: top level - g10 - getkey.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 934 1523 61.3 %
Date: 2016-09-12 12:29:17 Functions: 41 51 80.4 %

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

Generated by: LCOV version 1.11