LCOV - code coverage report
Current view: top level - g10 - keydb.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 538 820 65.6 %
Date: 2016-11-29 15:00:56 Functions: 30 32 93.8 %

          Line data    Source code
       1             : /* keydb.c - key database dispatcher
       2             :  * Copyright (C) 2001-2013 Free Software Foundation, Inc.
       3             :  * Coyrright (C) 2001-2015 Werner Koch
       4             :  *
       5             :  * This file is part of GnuPG.
       6             :  *
       7             :  * GnuPG is free software; you can redistribute it and/or modify
       8             :  * it under the terms of the GNU General Public License as published by
       9             :  * the Free Software Foundation; either version 3 of the License, or
      10             :  * (at your option) any later version.
      11             :  *
      12             :  * GnuPG is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15             :  * GNU General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU General Public License
      18             :  * along with this program; if not, see <https://www.gnu.org/licenses/>.
      19             :  */
      20             : 
      21             : #include <config.h>
      22             : #include <stdio.h>
      23             : #include <stdlib.h>
      24             : #include <string.h>
      25             : #include <errno.h>
      26             : #include <sys/types.h>
      27             : #include <sys/stat.h>
      28             : #include <unistd.h>
      29             : 
      30             : #include "gpg.h"
      31             : #include "util.h"
      32             : #include "options.h"
      33             : #include "main.h" /*try_make_homedir ()*/
      34             : #include "packet.h"
      35             : #include "keyring.h"
      36             : #include "../kbx/keybox.h"
      37             : #include "keydb.h"
      38             : #include "i18n.h"
      39             : 
      40             : static int active_handles;
      41             : 
      42             : typedef enum
      43             :   {
      44             :     KEYDB_RESOURCE_TYPE_NONE = 0,
      45             :     KEYDB_RESOURCE_TYPE_KEYRING,
      46             :     KEYDB_RESOURCE_TYPE_KEYBOX
      47             :   } KeydbResourceType;
      48             : #define MAX_KEYDB_RESOURCES 40
      49             : 
      50             : struct resource_item
      51             : {
      52             :   KeydbResourceType type;
      53             :   union {
      54             :     KEYRING_HANDLE kr;
      55             :     KEYBOX_HANDLE kb;
      56             :   } u;
      57             :   void *token;
      58             : };
      59             : 
      60             : static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
      61             : static int used_resources;
      62             : 
      63             : /* A pointer used to check for the primary key database by comparing
      64             :    to the struct resource_item's TOKEN.  */
      65             : static void *primary_keydb;
      66             : 
      67             : /* Whether we have successfully registered any resource.  */
      68             : static int any_registered;
      69             : 
      70             : /* This is a simple cache used to return the last result of a
      71             :    successful fingerprint search.  This works only for keybox resources
      72             :    because (due to lack of a copy_keyblock function) we need to store
      73             :    an image of the keyblock which is fortunately instantly available
      74             :    for keyboxes.  */
      75             : enum keyblock_cache_states {
      76             :   KEYBLOCK_CACHE_EMPTY,
      77             :   KEYBLOCK_CACHE_PREPARED,
      78             :   KEYBLOCK_CACHE_FILLED
      79             : };
      80             : 
      81             : struct keyblock_cache {
      82             :   enum keyblock_cache_states state;
      83             :   byte fpr[MAX_FINGERPRINT_LEN];
      84             :   iobuf_t iobuf; /* Image of the keyblock.  */
      85             :   u32 *sigstatus;
      86             :   int pk_no;
      87             :   int uid_no;
      88             :   /* Offset of the record in the keybox.  */
      89             :   int resource;
      90             :   off_t offset;
      91             : };
      92             : 
      93             : 
      94             : struct keydb_handle
      95             : {
      96             :   /* When we locked all of the resources in ACTIVE (using keyring_lock
      97             :      / keybox_lock, as appropriate).  */
      98             :   int locked;
      99             : 
     100             :   /* The index into ACTIVE of the resources in which the last search
     101             :      result was found.  Initially -1.  */
     102             :   int found;
     103             : 
     104             :   /* Initially -1 (invalid).  This is used to save a search result and
     105             :      later restore it as the selected result.  */
     106             :   int saved_found;
     107             : 
     108             :   /* The number of skipped long blobs since the last search
     109             :      (keydb_search_reset).  */
     110             :   unsigned long skipped_long_blobs;
     111             : 
     112             :   /* If set, this disables the use of the keyblock cache.  */
     113             :   int no_caching;
     114             : 
     115             :   /* Whether the next search will be from the beginning of the
     116             :      database (and thus consider all records).  */
     117             :   int is_reset;
     118             : 
     119             :   /* The "file position."  In our case, this is index of the current
     120             :      resource in ACTIVE.  */
     121             :   int current;
     122             : 
     123             :   /* The number of resources in ACTIVE.  */
     124             :   int used;
     125             : 
     126             :   /* Cache of the last found and parsed key block (only used for
     127             :      keyboxes, not keyrings).  */
     128             :   struct keyblock_cache keyblock_cache;
     129             : 
     130             :   /* Copy of ALL_RESOURCES when keydb_new is called.  */
     131             :   struct resource_item active[MAX_KEYDB_RESOURCES];
     132             : };
     133             : 
     134             : /* Looking up keys is expensive.  To hide the cost, we cache whether
     135             :    keys exist in the key database.  Then, if we know a key does not
     136             :    exist, we don't have to spend time looking it up.  This
     137             :    particularly helps the --list-sigs and --check-sigs commands.
     138             : 
     139             :    The cache stores the results in a hash using separate chaining.
     140             :    Concretely: we use the LSB of the keyid to index the hash table and
     141             :    each bucket consists of a linked list of entries.  An entry
     142             :    consists of the 64-bit key id.  If a key id is not in the cache,
     143             :    then we don't know whether it is in the DB or not.
     144             : 
     145             :    To simplify the cache consistency protocol, we simply flush the
     146             :    whole cache whenever a key is inserted or updated.  */
     147             : 
     148             : #define KID_NOT_FOUND_CACHE_BUCKETS 256
     149             : static struct kid_not_found_cache_bucket *
     150             :   kid_not_found_cache[KID_NOT_FOUND_CACHE_BUCKETS];
     151             : 
     152             : /* The total number of entries in the hash table.  */
     153             : static unsigned int kid_not_found_cache_count;
     154             : 
     155             : struct kid_not_found_cache_bucket
     156             : {
     157             :   struct kid_not_found_cache_bucket *next;
     158             :   u32 kid[2];
     159             : };
     160             : 
     161             : 
     162             : static int lock_all (KEYDB_HANDLE hd);
     163             : static void unlock_all (KEYDB_HANDLE hd);
     164             : 
     165             : 
     166             : /* Check whether the keyid KID is in key id is definitely not in the
     167             :    database.
     168             : 
     169             :    Returns:
     170             : 
     171             :      0 - Indeterminate: the key id is not in the cache; we don't know
     172             :          whether the key is in the database or not.  If you want a
     173             :          definitive answer, you'll need to perform a lookup.
     174             : 
     175             :      1 - There is definitely no key with this key id in the database.
     176             :          We searched for a key with this key id previously, but we
     177             :          didn't find it in the database.  */
     178             : static int
     179        2463 : kid_not_found_p (u32 *kid)
     180             : {
     181             :   struct kid_not_found_cache_bucket *k;
     182             : 
     183        2463 :   for (k = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS]; k; k = k->next)
     184           4 :     if (k->kid[0] == kid[0] && k->kid[1] == kid[1])
     185             :       {
     186           4 :         if (DBG_CACHE)
     187           0 :           log_debug ("keydb: kid_not_found_p (%08lx%08lx) => not in DB\n",
     188           0 :                      (ulong)kid[0], (ulong)kid[1]);
     189           4 :         return 1;
     190             :       }
     191             : 
     192        2459 :   if (DBG_CACHE)
     193           0 :     log_debug ("keydb: kid_not_found_p (%08lx%08lx) => indeterminate\n",
     194           0 :                (ulong)kid[0], (ulong)kid[1]);
     195        2459 :   return 0;
     196             : }
     197             : 
     198             : 
     199             : /* Insert the keyid KID into the kid_not_found_cache.  FOUND is whether
     200             :    the key is in the key database or not.
     201             : 
     202             :    Note this function does not check whether the key id is already in
     203             :    the cache.  As such, kid_not_found_p() should be called first.  */
     204             : static void
     205           8 : kid_not_found_insert (u32 *kid)
     206             : {
     207             :   struct kid_not_found_cache_bucket *k;
     208             : 
     209           8 :   if (DBG_CACHE)
     210           0 :     log_debug ("keydb: kid_not_found_insert (%08lx%08lx)\n",
     211           0 :                (ulong)kid[0], (ulong)kid[1]);
     212           8 :   k = xmalloc (sizeof *k);
     213           8 :   k->kid[0] = kid[0];
     214           8 :   k->kid[1] = kid[1];
     215           8 :   k->next = kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS];
     216           8 :   kid_not_found_cache[kid[0] % KID_NOT_FOUND_CACHE_BUCKETS] = k;
     217           8 :   kid_not_found_cache_count++;
     218           8 : }
     219             : 
     220             : 
     221             : /* Flush the kid not found cache.  */
     222             : static void
     223         250 : kid_not_found_flush (void)
     224             : {
     225             :   struct kid_not_found_cache_bucket *k, *knext;
     226             :   int i;
     227             : 
     228         250 :   if (DBG_CACHE)
     229           0 :     log_debug ("keydb: kid_not_found_flush\n");
     230             : 
     231         250 :   if (!kid_not_found_cache_count)
     232         497 :     return;
     233             : 
     234         771 :   for (i=0; i < DIM(kid_not_found_cache); i++)
     235             :     {
     236         771 :       for (k = kid_not_found_cache[i]; k; k = knext)
     237             :         {
     238           3 :           knext = k->next;
     239           3 :           xfree (k);
     240             :         }
     241         768 :       kid_not_found_cache[i] = NULL;
     242             :     }
     243           3 :   kid_not_found_cache_count = 0;
     244             : }
     245             : 
     246             : 
     247             : static void
     248       10781 : keyblock_cache_clear (struct keydb_handle *hd)
     249             : {
     250       10781 :   hd->keyblock_cache.state = KEYBLOCK_CACHE_EMPTY;
     251       10781 :   xfree (hd->keyblock_cache.sigstatus);
     252       10781 :   hd->keyblock_cache.sigstatus = NULL;
     253       10781 :   iobuf_close (hd->keyblock_cache.iobuf);
     254       10781 :   hd->keyblock_cache.iobuf = NULL;
     255       10781 :   hd->keyblock_cache.resource = -1;
     256       10781 :   hd->keyblock_cache.offset = -1;
     257       10781 : }
     258             : 
     259             : 
     260             : /* Handle the creation of a keyring or a keybox if it does not yet
     261             :    exist.  Take into account that other processes might have the
     262             :    keyring/keybox already locked.  This lock check does not work if
     263             :    the directory itself is not yet available.  If IS_BOX is true the
     264             :    filename is expected to refer to a keybox.  If FORCE_CREATE is true
     265             :    the keyring or keybox will be created.
     266             : 
     267             :    Return 0 if it is okay to access the specified file.  */
     268             : static gpg_error_t
     269        1132 : maybe_create_keyring_or_box (char *filename, int is_box, int force_create)
     270             : {
     271        1132 :   dotlock_t lockhd = NULL;
     272             :   IOBUF iobuf;
     273             :   int rc;
     274             :   mode_t oldmask;
     275             :   char *last_slash_in_filename;
     276        1132 :   char *bak_fname = NULL;
     277        1132 :   char *tmp_fname = NULL;
     278             :   int save_slash;
     279             : 
     280             :   /* A quick test whether the filename already exists. */
     281        1132 :   if (!access (filename, F_OK))
     282        1122 :     return !access (filename, R_OK)? 0 : gpg_error (GPG_ERR_EACCES);
     283             : 
     284             :   /* If we don't want to create a new file at all, there is no need to
     285             :      go any further - bail out right here.  */
     286          10 :   if (!force_create)
     287           0 :     return gpg_error (GPG_ERR_ENOENT);
     288             : 
     289             :   /* First of all we try to create the home directory.  Note, that we
     290             :      don't do any locking here because any sane application of gpg
     291             :      would create the home directory by itself and not rely on gpg's
     292             :      tricky auto-creation which is anyway only done for certain home
     293             :      directory name pattern. */
     294          10 :   last_slash_in_filename = strrchr (filename, DIRSEP_C);
     295             : #if HAVE_W32_SYSTEM
     296             :   {
     297             :     /* Windows may either have a slash or a backslash.  Take care of it.  */
     298             :     char *p = strrchr (filename, '/');
     299             :     if (!last_slash_in_filename || p > last_slash_in_filename)
     300             :       last_slash_in_filename = p;
     301             :   }
     302             : #endif /*HAVE_W32_SYSTEM*/
     303          10 :   if (!last_slash_in_filename)
     304           0 :     return gpg_error (GPG_ERR_ENOENT);  /* No slash at all - should
     305             :                                            not happen though.  */
     306          10 :   save_slash = *last_slash_in_filename;
     307          10 :   *last_slash_in_filename = 0;
     308          10 :   if (access(filename, F_OK))
     309             :     {
     310             :       static int tried;
     311             : 
     312           0 :       if (!tried)
     313             :         {
     314           0 :           tried = 1;
     315           0 :           try_make_homedir (filename);
     316             :         }
     317           0 :       if (access (filename, F_OK))
     318             :         {
     319           0 :           rc = gpg_error_from_syserror ();
     320           0 :           *last_slash_in_filename = save_slash;
     321           0 :           goto leave;
     322             :         }
     323             :     }
     324          10 :   *last_slash_in_filename = save_slash;
     325             : 
     326             :   /* To avoid races with other instances of gpg trying to create or
     327             :      update the keyring (it is removed during an update for a short
     328             :      time), we do the next stuff in a locked state. */
     329          10 :   lockhd = dotlock_create (filename, 0);
     330          10 :   if (!lockhd)
     331             :     {
     332           0 :       rc = gpg_error_from_syserror ();
     333             :       /* A reason for this to fail is that the directory is not
     334             :          writable. However, this whole locking stuff does not make
     335             :          sense if this is the case. An empty non-writable directory
     336             :          with no keyring is not really useful at all. */
     337           0 :       if (opt.verbose)
     338           0 :         log_info ("can't allocate lock for '%s': %s\n",
     339             :                   filename, gpg_strerror (rc));
     340             : 
     341           0 :       if (!force_create)
     342           0 :         return gpg_error (GPG_ERR_ENOENT);  /* Won't happen.  */
     343             :       else
     344           0 :         return rc;
     345             :     }
     346             : 
     347          10 :   if ( dotlock_take (lockhd, -1) )
     348             :     {
     349           0 :       rc = gpg_error_from_syserror ();
     350             :       /* This is something bad.  Probably a stale lockfile.  */
     351           0 :       log_info ("can't lock '%s': %s\n", filename, gpg_strerror (rc));
     352           0 :       goto leave;
     353             :     }
     354             : 
     355             :   /* Now the real test while we are locked. */
     356             : 
     357             :   /* Gpg either uses pubring.gpg or pubring.kbx and thus different
     358             :    * lock files.  Now, when one gpg process is updating a pubring.gpg
     359             :    * and thus holding the corresponding lock, a second gpg process may
     360             :    * get to here at the time between the two rename operation used by
     361             :    * the first process to update pubring.gpg.  The lock taken above
     362             :    * may not protect the second process if it tries to create a
     363             :    * pubring.kbx file which would be protected by a different lock
     364             :    * file.
     365             :    *
     366             :    * We can detect this case by checking that the two temporary files
     367             :    * used by the update code exist at the same time.  In that case we
     368             :    * do not create a new file but act as if FORCE_CREATE has not been
     369             :    * given.  Obviously there is a race between our two checks but the
     370             :    * worst thing is that we won't create a new file, which is better
     371             :    * than to accidentally creating one.  */
     372          10 :   rc = keybox_tmp_names (filename, is_box, &bak_fname, &tmp_fname);
     373          10 :   if (rc)
     374           0 :     goto leave;
     375             : 
     376          10 :   if (!access (filename, F_OK))
     377             :     {
     378           0 :       rc = 0;  /* Okay, we may access the file now.  */
     379           0 :       goto leave;
     380             :     }
     381          10 :   if (!access (bak_fname, F_OK) && !access (tmp_fname, F_OK))
     382             :     {
     383             :       /* Very likely another process is updating a pubring.gpg and we
     384             :          should not create a pubring.kbx.  */
     385           0 :       rc = gpg_error (GPG_ERR_ENOENT);
     386           0 :       goto leave;
     387             :     }
     388             : 
     389             : 
     390             :   /* The file does not yet exist, create it now. */
     391          10 :   oldmask = umask (077);
     392          10 :   if (is_secured_filename (filename))
     393             :     {
     394           0 :       iobuf = NULL;
     395           0 :       gpg_err_set_errno (EPERM);
     396             :     }
     397             :   else
     398          10 :     iobuf = iobuf_create (filename, 0);
     399          10 :   umask (oldmask);
     400          10 :   if (!iobuf)
     401             :     {
     402           0 :       rc = gpg_error_from_syserror ();
     403           0 :       if (is_box)
     404           0 :         log_error (_("error creating keybox '%s': %s\n"),
     405             :                    filename, gpg_strerror (rc));
     406             :       else
     407           0 :         log_error (_("error creating keyring '%s': %s\n"),
     408             :                    filename, gpg_strerror (rc));
     409           0 :       goto leave;
     410             :     }
     411             : 
     412          10 :   iobuf_close (iobuf);
     413             :   /* Must invalidate that ugly cache */
     414          10 :   iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, filename);
     415             : 
     416             :   /* Make sure that at least one record is in a new keybox file, so
     417             :      that the detection magic will work the next time it is used.  */
     418          10 :   if (is_box)
     419             :     {
     420          10 :       FILE *fp = fopen (filename, "wb");
     421          10 :       if (!fp)
     422           0 :         rc = gpg_error_from_syserror ();
     423             :       else
     424             :         {
     425          10 :           rc = _keybox_write_header_blob (fp, 1);
     426          10 :           fclose (fp);
     427             :         }
     428          10 :       if (rc)
     429             :         {
     430           0 :           if (is_box)
     431           0 :             log_error (_("error creating keybox '%s': %s\n"),
     432             :                        filename, gpg_strerror (rc));
     433             :           else
     434           0 :             log_error (_("error creating keyring '%s': %s\n"),
     435             :                        filename, gpg_strerror (rc));
     436           0 :           goto leave;
     437             :         }
     438             :     }
     439             : 
     440          10 :   if (!opt.quiet)
     441             :     {
     442           9 :       if (is_box)
     443           9 :         log_info (_("keybox '%s' created\n"), filename);
     444             :       else
     445           0 :         log_info (_("keyring '%s' created\n"), filename);
     446             :     }
     447             : 
     448          10 :   rc = 0;
     449             : 
     450             :  leave:
     451          10 :   if (lockhd)
     452             :     {
     453          10 :       dotlock_release (lockhd);
     454          10 :       dotlock_destroy (lockhd);
     455             :     }
     456          10 :   xfree (bak_fname);
     457          10 :   xfree (tmp_fname);
     458          10 :   return rc;
     459             : }
     460             : 
     461             : 
     462             : /* Helper for keydb_add_resource.  Opens FILENAME to figure out the
     463             :    resource type.
     464             : 
     465             :    Returns the specified file's likely type.  If the file does not
     466             :    exist, returns KEYDB_RESOURCE_TYPE_NONE and sets *R_FOUND to 0.
     467             :    Otherwise, tries to figure out the file's type.  This is either
     468             :    KEYDB_RESOURCE_TYPE_KEYBOX, KEYDB_RESOURCE_TYPE_KEYRING or
     469             :    KEYDB_RESOURCE_TYPE_KEYNONE.  If the file is a keybox and it has
     470             :    the OpenPGP flag set, then R_OPENPGP is also set.  */
     471             : static KeydbResourceType
     472        2261 : rt_from_file (const char *filename, int *r_found, int *r_openpgp)
     473             : {
     474             :   u32 magic;
     475             :   unsigned char verbuf[4];
     476             :   FILE *fp;
     477        2261 :   KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
     478             : 
     479        2261 :   *r_found = *r_openpgp = 0;
     480        2261 :   fp = fopen (filename, "rb");
     481        2261 :   if (fp)
     482             :     {
     483        1123 :       *r_found = 1;
     484             : 
     485        1123 :       if (fread (&magic, 4, 1, fp) == 1 )
     486             :         {
     487        1121 :           if (magic == 0x13579ace || magic == 0xce9a5713)
     488             :             ; /* GDBM magic - not anymore supported. */
     489        1121 :           else if (fread (&verbuf, 4, 1, fp) == 1
     490        1121 :                    && verbuf[0] == 1
     491        1105 :                    && fread (&magic, 4, 1, fp) == 1
     492        1105 :                    && !memcmp (&magic, "KBXf", 4))
     493             :             {
     494        1105 :               if ((verbuf[3] & 0x02))
     495        1105 :                 *r_openpgp = 1;
     496        1105 :               rt = KEYDB_RESOURCE_TYPE_KEYBOX;
     497             :             }
     498             :           else
     499          16 :             rt = KEYDB_RESOURCE_TYPE_KEYRING;
     500             :         }
     501             :       else /* Maybe empty: assume keyring. */
     502           2 :         rt = KEYDB_RESOURCE_TYPE_KEYRING;
     503             : 
     504        1123 :       fclose (fp);
     505             :     }
     506             : 
     507        2261 :   return rt;
     508             : }
     509             : 
     510             : char *
     511           0 : keydb_search_desc_dump (struct keydb_search_desc *desc)
     512             : {
     513             :   char b[MAX_FORMATTED_FINGERPRINT_LEN + 1];
     514             :   char fpr[2 * MAX_FINGERPRINT_LEN + 1];
     515             : 
     516           0 :   switch (desc->mode)
     517             :     {
     518             :     case KEYDB_SEARCH_MODE_EXACT:
     519           0 :       return xasprintf ("EXACT: '%s'", desc->u.name);
     520             :     case KEYDB_SEARCH_MODE_SUBSTR:
     521           0 :       return xasprintf ("SUBSTR: '%s'", desc->u.name);
     522             :     case KEYDB_SEARCH_MODE_MAIL:
     523           0 :       return xasprintf ("MAIL: '%s'", desc->u.name);
     524             :     case KEYDB_SEARCH_MODE_MAILSUB:
     525           0 :       return xasprintf ("MAILSUB: '%s'", desc->u.name);
     526             :     case KEYDB_SEARCH_MODE_MAILEND:
     527           0 :       return xasprintf ("MAILEND: '%s'", desc->u.name);
     528             :     case KEYDB_SEARCH_MODE_WORDS:
     529           0 :       return xasprintf ("WORDS: '%s'", desc->u.name);
     530             :     case KEYDB_SEARCH_MODE_SHORT_KID:
     531           0 :       return xasprintf ("SHORT_KID: '%s'",
     532           0 :                         format_keyid (desc->u.kid, KF_SHORT, b, sizeof (b)));
     533             :     case KEYDB_SEARCH_MODE_LONG_KID:
     534           0 :       return xasprintf ("LONG_KID: '%s'",
     535           0 :                         format_keyid (desc->u.kid, KF_LONG, b, sizeof (b)));
     536             :     case KEYDB_SEARCH_MODE_FPR16:
     537           0 :       bin2hex (desc->u.fpr, 16, fpr);
     538           0 :       return xasprintf ("FPR16: '%s'",
     539             :                         format_hexfingerprint (fpr, b, sizeof (b)));
     540             :     case KEYDB_SEARCH_MODE_FPR20:
     541           0 :       bin2hex (desc->u.fpr, 20, fpr);
     542           0 :       return xasprintf ("FPR20: '%s'",
     543             :                         format_hexfingerprint (fpr, b, sizeof (b)));
     544             :     case KEYDB_SEARCH_MODE_FPR:
     545           0 :       bin2hex (desc->u.fpr, 20, fpr);
     546           0 :       return xasprintf ("FPR: '%s'",
     547             :                         format_hexfingerprint (fpr, b, sizeof (b)));
     548             :     case KEYDB_SEARCH_MODE_ISSUER:
     549           0 :       return xasprintf ("ISSUER: '%s'", desc->u.name);
     550             :     case KEYDB_SEARCH_MODE_ISSUER_SN:
     551           0 :       return xasprintf ("ISSUER_SN: '%*s'",
     552           0 :                         (int) (desc->snlen == -1
     553           0 :                                ? strlen (desc->sn) : desc->snlen),
     554             :                         desc->sn);
     555             :     case KEYDB_SEARCH_MODE_SN:
     556           0 :       return xasprintf ("SN: '%*s'",
     557           0 :                         (int) (desc->snlen == -1
     558           0 :                                ? strlen (desc->sn) : desc->snlen),
     559             :                         desc->sn);
     560             :     case KEYDB_SEARCH_MODE_SUBJECT:
     561           0 :       return xasprintf ("SUBJECT: '%s'", desc->u.name);
     562             :     case KEYDB_SEARCH_MODE_KEYGRIP:
     563           0 :       return xasprintf ("KEYGRIP: %s", desc->u.grip);
     564             :     case KEYDB_SEARCH_MODE_FIRST:
     565           0 :       return xasprintf ("FIRST");
     566             :     case KEYDB_SEARCH_MODE_NEXT:
     567           0 :       return xasprintf ("NEXT");
     568             :     default:
     569           0 :       return xasprintf ("Bad search mode (%d)", desc->mode);
     570             :     }
     571             : }
     572             : 
     573             : 
     574             : 
     575             : /* Register a resource (keyring or keybox).  The first keyring or
     576             :  * keybox that is added using this function is created if it does not
     577             :  * already exist and the KEYDB_RESOURCE_FLAG_READONLY is not set.
     578             :  *
     579             :  * FLAGS are a combination of the KEYDB_RESOURCE_FLAG_* constants.
     580             :  *
     581             :  * URL must have the following form:
     582             :  *
     583             :  *   gnupg-ring:filename  = plain keyring
     584             :  *   gnupg-kbx:filename   = keybox file
     585             :  *   filename             = check file's type (create as a plain keyring)
     586             :  *
     587             :  * Note: on systems with drive letters (Windows) invalid URLs (i.e.,
     588             :  * those with an unrecognized part before the ':' such as "c:\...")
     589             :  * will silently be treated as bare filenames.  On other systems, such
     590             :  * URLs will cause this function to return GPG_ERR_GENERAL.
     591             :  *
     592             :  * If KEYDB_RESOURCE_FLAG_DEFAULT is set, the resource is a keyring
     593             :  * and the file ends in ".gpg", then this function also checks if a
     594             :  * file with the same name, but the extension ".kbx" exists, is a
     595             :  * keybox and the OpenPGP flag is set.  If so, this function opens
     596             :  * that resource instead.
     597             :  *
     598             :  * If the file is not found, KEYDB_RESOURCE_FLAG_GPGVDEF is set and
     599             :  * the URL ends in ".kbx", then this function will try opening the
     600             :  * same URL, but with the extension ".gpg".  If that file is a keybox
     601             :  * with the OpenPGP flag set or it is a keyring, then we use that
     602             :  * instead.
     603             :  *
     604             :  * If the file is not found, KEYDB_RESOURCE_FLAG_DEFAULT is set, the
     605             :  * file should be created and the file's extension is ".gpg" then we
     606             :  * replace the extension with ".kbx".
     607             :  *
     608             :  * If the KEYDB_RESOURCE_FLAG_PRIMARY is set and the resource is a
     609             :  * keyring (not a keybox), then this resource is considered the
     610             :  * primary resource.  This is used by keydb_locate_writable().  If
     611             :  * another primary keyring is set, then that keyring is considered the
     612             :  * primary.
     613             :  *
     614             :  * If KEYDB_RESOURCE_FLAG_READONLY is set and the resource is a
     615             :  * keyring (not a keybox), then the keyring is marked as read only and
     616             :  * operations just as keyring_insert_keyblock will return
     617             :  * GPG_ERR_ACCESS.  */
     618             : gpg_error_t
     619        1132 : keydb_add_resource (const char *url, unsigned int flags)
     620             : {
     621             :   /* The file named by the URL (i.e., without the prototype).  */
     622        1132 :   const char *resname = url;
     623             : 
     624        1132 :   char *filename = NULL;
     625             :   int create;
     626        1132 :   int read_only = !!(flags&KEYDB_RESOURCE_FLAG_READONLY);
     627        1132 :   int is_default = !!(flags&KEYDB_RESOURCE_FLAG_DEFAULT);
     628        1132 :   int is_gpgvdef = !!(flags&KEYDB_RESOURCE_FLAG_GPGVDEF);
     629        1132 :   gpg_error_t err = 0;
     630        1132 :   KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
     631             :   void *token;
     632             : 
     633             :   /* Create the resource if it is the first registered one.  */
     634        1132 :   create = (!read_only && !any_registered);
     635             : 
     636        1132 :   if (strlen (resname) > 11 && !strncmp( resname, "gnupg-ring:", 11) )
     637             :     {
     638           0 :       rt = KEYDB_RESOURCE_TYPE_KEYRING;
     639           0 :       resname += 11;
     640             :     }
     641        1132 :   else if (strlen (resname) > 10 && !strncmp (resname, "gnupg-kbx:", 10) )
     642             :     {
     643           0 :       rt = KEYDB_RESOURCE_TYPE_KEYBOX;
     644           0 :       resname += 10;
     645             :     }
     646             : #if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
     647        1132 :   else if (strchr (resname, ':'))
     648             :     {
     649           0 :       log_error ("invalid key resource URL '%s'\n", url );
     650           0 :       err = gpg_error (GPG_ERR_GENERAL);
     651           0 :       goto leave;
     652             :     }
     653             : #endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
     654             : 
     655        1132 :   if (*resname != DIRSEP_C
     656             : #ifdef HAVE_W32_SYSTEM
     657             :       && *resname != '/'  /* Fixme: does not handle drive letters.  */
     658             : #endif
     659             :         )
     660             :     {
     661             :       /* Do tilde expansion etc. */
     662        1131 :       if (strchr (resname, DIRSEP_C)
     663             : #ifdef HAVE_W32_SYSTEM
     664             :           || strchr (resname, '/')  /* Windows also accepts this.  */
     665             : #endif
     666             :           )
     667           2 :         filename = make_filename (resname, NULL);
     668             :       else
     669        1129 :         filename = make_filename (gnupg_homedir (), resname, NULL);
     670             :     }
     671             :   else
     672           1 :     filename = xstrdup (resname);
     673             : 
     674             :   /* See whether we can determine the filetype.  */
     675        1132 :   if (rt == KEYDB_RESOURCE_TYPE_NONE)
     676             :     {
     677             :       int found, openpgp_flag;
     678        1132 :       int pass = 0;
     679             :       size_t filenamelen;
     680             : 
     681             :     check_again:
     682        2246 :       filenamelen = strlen (filename);
     683        2246 :       rt = rt_from_file (filename, &found, &openpgp_flag);
     684        2246 :       if (found)
     685             :         {
     686             :           /* The file exists and we have the resource type in RT.
     687             : 
     688             :              Now let us check whether in addition to the "pubring.gpg"
     689             :              a "pubring.kbx with openpgp keys exists.  This is so that
     690             :              GPG 2.1 will use an existing "pubring.kbx" by default iff
     691             :              that file has been created or used by 2.1.  This check is
     692             :              needed because after creation or use of the kbx file with
     693             :              2.1 an older version of gpg may have created a new
     694             :              pubring.gpg for its own use.  */
     695        1122 :           if (!pass && is_default && rt == KEYDB_RESOURCE_TYPE_KEYRING
     696          15 :               && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg"))
     697             :             {
     698          15 :               strcpy (filename+filenamelen-4, ".kbx");
     699          15 :               if ((rt_from_file (filename, &found, &openpgp_flag)
     700           0 :                    == KEYDB_RESOURCE_TYPE_KEYBOX) && found && openpgp_flag)
     701           0 :                 rt = KEYDB_RESOURCE_TYPE_KEYBOX;
     702             :               else /* Restore filename */
     703          15 :                 strcpy (filename+filenamelen-4, ".gpg");
     704             :             }
     705             :         }
     706        1124 :       else if (!pass && is_gpgvdef
     707           0 :                && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".kbx"))
     708           0 :         {
     709             :           /* Not found but gpgv's default "trustedkeys.kbx" file has
     710             :              been requested.  We did not found it so now check whether
     711             :              a "trustedkeys.gpg" file exists and use that instead.  */
     712             :           KeydbResourceType rttmp;
     713             : 
     714           0 :           strcpy (filename+filenamelen-4, ".gpg");
     715           0 :           rttmp = rt_from_file (filename, &found, &openpgp_flag);
     716           0 :           if (found
     717           0 :               && ((rttmp == KEYDB_RESOURCE_TYPE_KEYBOX && openpgp_flag)
     718           0 :                   || (rttmp == KEYDB_RESOURCE_TYPE_KEYRING)))
     719           0 :             rt = rttmp;
     720             :           else /* Restore filename */
     721           0 :             strcpy (filename+filenamelen-4, ".kbx");
     722             :         }
     723        1124 :       else if (!pass
     724        1114 :                && is_default && create
     725        1114 :                && filenamelen > 4 && !strcmp (filename+filenamelen-4, ".gpg"))
     726             :         {
     727             :           /* The file does not exist, the default resource has been
     728             :              requested, the file shall be created, and the file has a
     729             :              ".gpg" suffix.  Change the suffix to ".kbx" and try once
     730             :              more.  This way we achieve that we open an existing
     731             :              ".gpg" keyring, but create a new keybox file with an
     732             :              ".kbx" suffix.  */
     733        1114 :           strcpy (filename+filenamelen-4, ".kbx");
     734        1114 :           pass++;
     735        1114 :           goto check_again;
     736             :         }
     737             :       else /* No file yet: create keybox. */
     738          10 :         rt = KEYDB_RESOURCE_TYPE_KEYBOX;
     739             :     }
     740             : 
     741        1132 :   switch (rt)
     742             :     {
     743             :     case KEYDB_RESOURCE_TYPE_NONE:
     744           0 :       log_error ("unknown type of key resource '%s'\n", url );
     745           0 :       err = gpg_error (GPG_ERR_GENERAL);
     746           0 :       goto leave;
     747             : 
     748             :     case KEYDB_RESOURCE_TYPE_KEYRING:
     749          17 :       err = maybe_create_keyring_or_box (filename, 0, create);
     750          17 :       if (err)
     751           0 :         goto leave;
     752             : 
     753          17 :       if (keyring_register_filename (filename, read_only, &token))
     754             :         {
     755          17 :           if (used_resources >= MAX_KEYDB_RESOURCES)
     756           0 :             err = gpg_error (GPG_ERR_RESOURCE_LIMIT);
     757             :           else
     758             :             {
     759          17 :               if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
     760           0 :                 primary_keydb = token;
     761          17 :               all_resources[used_resources].type = rt;
     762          17 :               all_resources[used_resources].u.kr = NULL; /* Not used here */
     763          17 :               all_resources[used_resources].token = token;
     764          17 :               used_resources++;
     765             :             }
     766             :         }
     767             :       else
     768             :         {
     769             :           /* This keyring was already registered, so ignore it.
     770             :              However, we can still mark it as primary even if it was
     771             :              already registered.  */
     772           0 :           if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
     773           0 :             primary_keydb = token;
     774             :         }
     775          17 :       break;
     776             : 
     777             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
     778             :       {
     779        1115 :         err = maybe_create_keyring_or_box (filename, 1, create);
     780        1115 :         if (err)
     781           0 :           goto leave;
     782             : 
     783        1115 :         err = keybox_register_file (filename, 0, &token);
     784        1115 :         if (!err)
     785             :           {
     786        1115 :             if (used_resources >= MAX_KEYDB_RESOURCES)
     787           0 :               err = gpg_error (GPG_ERR_RESOURCE_LIMIT);
     788             :             else
     789             :               {
     790        1115 :                 if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
     791           0 :                   primary_keydb = token;
     792        1115 :                 all_resources[used_resources].type = rt;
     793        1115 :                 all_resources[used_resources].u.kb = NULL; /* Not used here */
     794        1115 :                 all_resources[used_resources].token = token;
     795             : 
     796             :                 /* FIXME: Do a compress run if needed and no other
     797             :                    user is currently using the keybox. */
     798             : 
     799        1115 :                 used_resources++;
     800             :               }
     801             :           }
     802           0 :         else if (gpg_err_code (err) == GPG_ERR_EEXIST)
     803             :           {
     804             :             /* Already registered.  We will mark it as the primary key
     805             :                if requested.  */
     806           0 :             if ((flags & KEYDB_RESOURCE_FLAG_PRIMARY))
     807           0 :               primary_keydb = token;
     808             :           }
     809             :       }
     810        1115 :       break;
     811             : 
     812             :       default:
     813           0 :         log_error ("resource type of '%s' not supported\n", url);
     814           0 :         err = gpg_error (GPG_ERR_GENERAL);
     815           0 :         goto leave;
     816             :     }
     817             : 
     818             :   /* fixme: check directory permissions and print a warning */
     819             : 
     820             :  leave:
     821        1132 :   if (err)
     822             :     {
     823           0 :       log_error (_("keyblock resource '%s': %s\n"),
     824             :                  filename, gpg_strerror (err));
     825           0 :       write_status_error ("add_keyblock_resource", err);
     826             :     }
     827             :   else
     828        1132 :     any_registered = 1;
     829        1132 :   xfree (filename);
     830        1132 :   return err;
     831             : }
     832             : 
     833             : 
     834             : void
     835           0 : keydb_dump_stats (void)
     836             : {
     837           0 :   if (kid_not_found_cache_count)
     838           0 :     log_info ("keydb: kid_not_found_cache: total: %u\n",
     839             :               kid_not_found_cache_count);
     840           0 : }
     841             : 
     842             : 
     843             : /* Create a new database handle.  A database handle is similar to a
     844             :    file handle: it contains a local file position.  This is used when
     845             :    searching: subsequent searches resume where the previous search
     846             :    left off.  To rewind the position, use keydb_search_reset().  This
     847             :    function returns NULL on error, sets ERRNO, and prints an error
     848             :    diagnostic. */
     849             : KEYDB_HANDLE
     850        3496 : keydb_new (void)
     851             : {
     852             :   KEYDB_HANDLE hd;
     853             :   int i, j;
     854        3496 :   int die = 0;
     855             :   int reterrno;
     856             : 
     857        3496 :   if (DBG_CLOCK)
     858           0 :     log_clock ("keydb_new");
     859             : 
     860        3496 :   hd = xtrycalloc (1, sizeof *hd);
     861        3496 :   if (!hd)
     862           0 :     goto leave;
     863        3496 :   hd->found = -1;
     864        3496 :   hd->saved_found = -1;
     865        3496 :   hd->is_reset = 1;
     866             : 
     867        3496 :   log_assert (used_resources <= MAX_KEYDB_RESOURCES);
     868        6992 :   for (i=j=0; ! die && i < used_resources; i++)
     869             :     {
     870        3496 :       switch (all_resources[i].type)
     871             :         {
     872             :         case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
     873           0 :           break;
     874             :         case KEYDB_RESOURCE_TYPE_KEYRING:
     875          50 :           hd->active[j].type   = all_resources[i].type;
     876          50 :           hd->active[j].token  = all_resources[i].token;
     877          50 :           hd->active[j].u.kr = keyring_new (all_resources[i].token);
     878          50 :           if (!hd->active[j].u.kr)
     879             :             {
     880           0 :               reterrno = errno;
     881           0 :               die = 1;
     882             :             }
     883          50 :           j++;
     884          50 :           break;
     885             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
     886        3446 :           hd->active[j].type   = all_resources[i].type;
     887        3446 :           hd->active[j].token  = all_resources[i].token;
     888        3446 :           hd->active[j].u.kb   = keybox_new_openpgp (all_resources[i].token, 0);
     889        3446 :           if (!hd->active[j].u.kb)
     890             :             {
     891           0 :               reterrno = errno;
     892           0 :               die = 1;
     893             :             }
     894        3446 :           j++;
     895        3446 :           break;
     896             :         }
     897             :     }
     898        3496 :   hd->used = j;
     899             : 
     900        3496 :   active_handles++;
     901             : 
     902        3496 :   if (die)
     903             :     {
     904           0 :       keydb_release (hd);
     905           0 :       gpg_err_set_errno (reterrno);
     906           0 :       hd = NULL;
     907             :     }
     908             : 
     909             :  leave:
     910        3496 :   if (!hd)
     911           0 :     log_error (_("error opening key DB: %s\n"),
     912             :                gpg_strerror (gpg_error_from_syserror()));
     913             : 
     914        3496 :   return hd;
     915             : }
     916             : 
     917             : 
     918             : void
     919        3496 : keydb_release (KEYDB_HANDLE hd)
     920             : {
     921             :   int i;
     922             : 
     923        3496 :   if (!hd)
     924        3496 :     return;
     925        3496 :   log_assert (active_handles > 0);
     926        3496 :   active_handles--;
     927             : 
     928        3496 :   unlock_all (hd);
     929        6992 :   for (i=0; i < hd->used; i++)
     930             :     {
     931        3496 :       switch (hd->active[i].type)
     932             :         {
     933             :         case KEYDB_RESOURCE_TYPE_NONE:
     934           0 :           break;
     935             :         case KEYDB_RESOURCE_TYPE_KEYRING:
     936          50 :           keyring_release (hd->active[i].u.kr);
     937          50 :           break;
     938             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
     939        3446 :           keybox_release (hd->active[i].u.kb);
     940        3446 :           break;
     941             :         }
     942             :     }
     943             : 
     944        3496 :   keyblock_cache_clear (hd);
     945        3496 :   xfree (hd);
     946             : }
     947             : 
     948             : 
     949             : /* Set a flag on the handle to suppress use of cached results.  This
     950             :  * is required for updating a keyring and for key listings.  Fixme:
     951             :  * Using a new parameter for keydb_new might be a better solution.  */
     952             : void
     953         396 : keydb_disable_caching (KEYDB_HANDLE hd)
     954             : {
     955         396 :   if (hd)
     956         396 :     hd->no_caching = 1;
     957         396 : }
     958             : 
     959             : 
     960             : /* Return the file name of the resource in which the current search
     961             :  * result was found or, if there is no search result, the filename of
     962             :  * the current resource (i.e., the resource that the file position
     963             :  * points to).  Note: the filename is not necessarily the URL used to
     964             :  * open it!
     965             :  *
     966             :  * This function only returns NULL if no handle is specified, in all
     967             :  * other error cases an empty string is returned.  */
     968             : const char *
     969           9 : keydb_get_resource_name (KEYDB_HANDLE hd)
     970             : {
     971             :   int idx;
     972           9 :   const char *s = NULL;
     973             : 
     974           9 :   if (!hd)
     975           0 :     return NULL;
     976             : 
     977           9 :   if ( hd->found >= 0 && hd->found < hd->used)
     978           9 :     idx = hd->found;
     979           0 :   else if ( hd->current >= 0 && hd->current < hd->used)
     980           0 :     idx = hd->current;
     981             :   else
     982           0 :     idx = 0;
     983             : 
     984           9 :   switch (hd->active[idx].type)
     985             :     {
     986             :     case KEYDB_RESOURCE_TYPE_NONE:
     987           0 :       s = NULL;
     988           0 :       break;
     989             :     case KEYDB_RESOURCE_TYPE_KEYRING:
     990           9 :       s = keyring_get_resource_name (hd->active[idx].u.kr);
     991           9 :       break;
     992             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
     993           0 :       s = keybox_get_resource_name (hd->active[idx].u.kb);
     994           0 :       break;
     995             :     }
     996             : 
     997           9 :   return s? s: "";
     998             : }
     999             : 
    1000             : 
    1001             : 
    1002             : static int
    1003         250 : lock_all (KEYDB_HANDLE hd)
    1004             : {
    1005         250 :   int i, rc = 0;
    1006             : 
    1007             :   /* Fixme: This locking scheme may lead to a deadlock if the resources
    1008             :      are not added in the same order by all processes.  We are
    1009             :      currently only allowing one resource so it is not a problem.
    1010             :      [Oops: Who claimed the latter]
    1011             : 
    1012             :      To fix this we need to use a lock file to protect lock_all.  */
    1013             : 
    1014         500 :   for (i=0; !rc && i < hd->used; i++)
    1015             :     {
    1016         250 :       switch (hd->active[i].type)
    1017             :         {
    1018             :         case KEYDB_RESOURCE_TYPE_NONE:
    1019           0 :           break;
    1020             :         case KEYDB_RESOURCE_TYPE_KEYRING:
    1021           1 :           rc = keyring_lock (hd->active[i].u.kr, 1);
    1022           1 :           break;
    1023             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
    1024         249 :           rc = keybox_lock (hd->active[i].u.kb, 1);
    1025         249 :           break;
    1026             :         }
    1027             :     }
    1028             : 
    1029         250 :   if (rc)
    1030             :     {
    1031             :       /* Revert the already taken locks.  */
    1032           0 :       for (i--; i >= 0; i--)
    1033             :         {
    1034           0 :           switch (hd->active[i].type)
    1035             :             {
    1036             :             case KEYDB_RESOURCE_TYPE_NONE:
    1037           0 :               break;
    1038             :             case KEYDB_RESOURCE_TYPE_KEYRING:
    1039           0 :               keyring_lock (hd->active[i].u.kr, 0);
    1040           0 :               break;
    1041             :             case KEYDB_RESOURCE_TYPE_KEYBOX:
    1042           0 :               keybox_lock (hd->active[i].u.kb, 0);
    1043           0 :               break;
    1044             :             }
    1045             :         }
    1046             :     }
    1047             :   else
    1048         250 :     hd->locked = 1;
    1049             : 
    1050         250 :   return rc;
    1051             : }
    1052             : 
    1053             : 
    1054             : static void
    1055        3746 : unlock_all (KEYDB_HANDLE hd)
    1056             : {
    1057             :   int i;
    1058             : 
    1059        3746 :   if (!hd->locked)
    1060        7242 :     return;
    1061             : 
    1062         500 :   for (i=hd->used-1; i >= 0; i--)
    1063             :     {
    1064         250 :       switch (hd->active[i].type)
    1065             :         {
    1066             :         case KEYDB_RESOURCE_TYPE_NONE:
    1067           0 :           break;
    1068             :         case KEYDB_RESOURCE_TYPE_KEYRING:
    1069           1 :           keyring_lock (hd->active[i].u.kr, 0);
    1070           1 :           break;
    1071             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
    1072         249 :           keybox_lock (hd->active[i].u.kb, 0);
    1073         249 :           break;
    1074             :         }
    1075             :     }
    1076         250 :   hd->locked = 0;
    1077             : }
    1078             : 
    1079             : 
    1080             : 
    1081             : /* Save the last found state and invalidate the current selection
    1082             :  * (i.e., the entry selected by keydb_search() is invalidated and
    1083             :  * something like keydb_get_keyblock() will return an error).  This
    1084             :  * does not change the file position.  This makes it possible to do
    1085             :  * something like:
    1086             :  *
    1087             :  *   keydb_search (hd, ...);  // Result 1.
    1088             :  *   keydb_push_found_state (hd);
    1089             :  *     keydb_search_reset (hd);
    1090             :  *     keydb_search (hd, ...);  // Result 2.
    1091             :  *   keydb_pop_found_state (hd);
    1092             :  *   keydb_get_keyblock (hd, ...);  // -> Result 1.
    1093             :  *
    1094             :  * Note: it is only possible to save a single save state at a time.
    1095             :  * In other words, the the save stack only has room for a single
    1096             :  * instance of the state.  */
    1097             : void
    1098           2 : keydb_push_found_state (KEYDB_HANDLE hd)
    1099             : {
    1100           2 :   if (!hd)
    1101           0 :     return;
    1102             : 
    1103           2 :   if (hd->found < 0 || hd->found >= hd->used)
    1104             :     {
    1105           0 :       hd->saved_found = -1;
    1106           0 :       return;
    1107             :     }
    1108             : 
    1109           2 :   switch (hd->active[hd->found].type)
    1110             :     {
    1111             :     case KEYDB_RESOURCE_TYPE_NONE:
    1112           0 :       break;
    1113             :     case KEYDB_RESOURCE_TYPE_KEYRING:
    1114           0 :       keyring_push_found_state (hd->active[hd->found].u.kr);
    1115           0 :       break;
    1116             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
    1117           2 :       keybox_push_found_state (hd->active[hd->found].u.kb);
    1118           2 :       break;
    1119             :     }
    1120             : 
    1121           2 :   hd->saved_found = hd->found;
    1122           2 :   hd->found = -1;
    1123             : }
    1124             : 
    1125             : 
    1126             : /* Restore the previous save state.  If the saved state is NULL or
    1127             :    invalid, this is a NOP.  */
    1128             : void
    1129           2 : keydb_pop_found_state (KEYDB_HANDLE hd)
    1130             : {
    1131           2 :   if (!hd)
    1132           0 :     return;
    1133             : 
    1134           2 :   hd->found = hd->saved_found;
    1135           2 :   hd->saved_found = -1;
    1136           2 :   if (hd->found < 0 || hd->found >= hd->used)
    1137           0 :     return;
    1138             : 
    1139           2 :   switch (hd->active[hd->found].type)
    1140             :     {
    1141             :     case KEYDB_RESOURCE_TYPE_NONE:
    1142           0 :       break;
    1143             :     case KEYDB_RESOURCE_TYPE_KEYRING:
    1144           0 :       keyring_pop_found_state (hd->active[hd->found].u.kr);
    1145           0 :       break;
    1146             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
    1147           2 :       keybox_pop_found_state (hd->active[hd->found].u.kb);
    1148           2 :       break;
    1149             :     }
    1150             : }
    1151             : 
    1152             : 
    1153             : 
    1154             : static gpg_error_t
    1155        3230 : parse_keyblock_image (iobuf_t iobuf, int pk_no, int uid_no,
    1156             :                       const u32 *sigstatus, kbnode_t *r_keyblock)
    1157             : {
    1158             :   gpg_error_t err;
    1159             :   PACKET *pkt;
    1160        3230 :   kbnode_t keyblock = NULL;
    1161             :   kbnode_t node, *tail;
    1162             :   int in_cert, save_mode;
    1163             :   u32 n_sigs;
    1164             :   int pk_count, uid_count;
    1165             : 
    1166        3230 :   *r_keyblock = NULL;
    1167             : 
    1168        3230 :   pkt = xtrymalloc (sizeof *pkt);
    1169        3230 :   if (!pkt)
    1170           0 :     return gpg_error_from_syserror ();
    1171        3230 :   init_packet (pkt);
    1172        3230 :   save_mode = set_packet_list_mode (0);
    1173        3230 :   in_cert = 0;
    1174        3230 :   n_sigs = 0;
    1175        3230 :   tail = NULL;
    1176        3230 :   pk_count = uid_count = 0;
    1177       25213 :   while ((err = parse_packet (iobuf, pkt)) != -1)
    1178             :     {
    1179       18753 :       if (gpg_err_code (err) == GPG_ERR_UNKNOWN_PACKET)
    1180             :         {
    1181           0 :           free_packet (pkt);
    1182           0 :           init_packet (pkt);
    1183           0 :           continue;
    1184             :         }
    1185       18753 :       if (err)
    1186             :         {
    1187           0 :           log_error ("parse_keyblock_image: read error: %s\n",
    1188             :                      gpg_strerror (err));
    1189           0 :           err = gpg_error (GPG_ERR_INV_KEYRING);
    1190           0 :           break;
    1191             :         }
    1192             : 
    1193             :       /* Filter allowed packets.  */
    1194       18753 :       switch (pkt->pkttype)
    1195             :         {
    1196             :         case PKT_PUBLIC_KEY:
    1197             :         case PKT_PUBLIC_SUBKEY:
    1198             :         case PKT_SECRET_KEY:
    1199             :         case PKT_SECRET_SUBKEY:
    1200             :         case PKT_USER_ID:
    1201             :         case PKT_ATTRIBUTE:
    1202             :         case PKT_SIGNATURE:
    1203       18753 :           break; /* Allowed per RFC.  */
    1204             : 
    1205             :         default:
    1206             :           /* Note that can't allow ring trust packets here and some of
    1207             :              the other GPG specific packets don't make sense either.  */
    1208           0 :           log_error ("skipped packet of type %d in keybox\n",
    1209           0 :                      (int)pkt->pkttype);
    1210           0 :           free_packet(pkt);
    1211           0 :           init_packet(pkt);
    1212           0 :           continue;
    1213             :         }
    1214             : 
    1215             :       /* Other sanity checks.  */
    1216       18753 :       if (!in_cert && pkt->pkttype != PKT_PUBLIC_KEY)
    1217             :         {
    1218           0 :           log_error ("parse_keyblock_image: first packet in a keybox blob "
    1219             :                      "is not a public key packet\n");
    1220           0 :           err = gpg_error (GPG_ERR_INV_KEYRING);
    1221           0 :           break;
    1222             :         }
    1223       18753 :       if (in_cert && (pkt->pkttype == PKT_PUBLIC_KEY
    1224       15523 :                       || pkt->pkttype == PKT_SECRET_KEY))
    1225             :         {
    1226           0 :           log_error ("parse_keyblock_image: "
    1227             :                      "multiple keyblocks in a keybox blob\n");
    1228           0 :           err = gpg_error (GPG_ERR_INV_KEYRING);
    1229           0 :           break;
    1230             :         }
    1231       18753 :       in_cert = 1;
    1232             : 
    1233       18753 :       if (pkt->pkttype == PKT_SIGNATURE && sigstatus)
    1234             :         {
    1235        8028 :           PKT_signature *sig = pkt->pkt.signature;
    1236             : 
    1237        8028 :           n_sigs++;
    1238        8028 :           if (n_sigs > sigstatus[0])
    1239             :             {
    1240           0 :               log_error ("parse_keyblock_image: "
    1241             :                          "more signatures than found in the meta data\n");
    1242           0 :               err = gpg_error (GPG_ERR_INV_KEYRING);
    1243           0 :               break;
    1244             : 
    1245             :             }
    1246        8028 :           if (sigstatus[n_sigs])
    1247             :             {
    1248        7030 :               sig->flags.checked = 1;
    1249        7030 :               if (sigstatus[n_sigs] == 1 )
    1250             :                 ; /* missing key */
    1251        7030 :               else if (sigstatus[n_sigs] == 2 )
    1252             :                 ; /* bad signature */
    1253        7030 :               else if (sigstatus[n_sigs] < 0x10000000)
    1254             :                 ; /* bad flag */
    1255             :               else
    1256             :                 {
    1257        7030 :                   sig->flags.valid = 1;
    1258             :                   /* Fixme: Shall we set the expired flag here?  */
    1259             :                 }
    1260             :             }
    1261             :         }
    1262             : 
    1263       18753 :       node = new_kbnode (pkt);
    1264             : 
    1265       18753 :       switch (pkt->pkttype)
    1266             :         {
    1267             :         case PKT_PUBLIC_KEY:
    1268             :         case PKT_PUBLIC_SUBKEY:
    1269             :         case PKT_SECRET_KEY:
    1270             :         case PKT_SECRET_SUBKEY:
    1271        6615 :           if (++pk_count == pk_no)
    1272        2920 :             node->flag |= 1;
    1273        6615 :           break;
    1274             : 
    1275             :         case PKT_USER_ID:
    1276        4110 :           if (++uid_count == uid_no)
    1277         225 :             node->flag |= 2;
    1278        4110 :           break;
    1279             : 
    1280             :         default:
    1281        8028 :           break;
    1282             :         }
    1283             : 
    1284       18753 :       if (!keyblock)
    1285        3230 :         keyblock = node;
    1286             :       else
    1287       15523 :         *tail = node;
    1288       18753 :       tail = &node->next;
    1289       18753 :       pkt = xtrymalloc (sizeof *pkt);
    1290       18753 :       if (!pkt)
    1291             :         {
    1292           0 :           err = gpg_error_from_syserror ();
    1293           0 :           break;
    1294             :         }
    1295       18753 :       init_packet (pkt);
    1296             :     }
    1297        3230 :   set_packet_list_mode (save_mode);
    1298             : 
    1299        3230 :   if (err == -1 && keyblock)
    1300        3230 :     err = 0; /* Got the entire keyblock.  */
    1301             : 
    1302        3230 :   if (!err && sigstatus && n_sigs != sigstatus[0])
    1303             :     {
    1304           0 :       log_error ("parse_keyblock_image: signature count does not match\n");
    1305           0 :       err = gpg_error (GPG_ERR_INV_KEYRING);
    1306             :     }
    1307             : 
    1308        3230 :   if (err)
    1309           0 :     release_kbnode (keyblock);
    1310             :   else
    1311        3230 :     *r_keyblock = keyblock;
    1312        3230 :   free_packet (pkt);
    1313        3230 :   xfree (pkt);
    1314        3230 :   return err;
    1315             : }
    1316             : 
    1317             : 
    1318             : /* Return the keyblock last found by keydb_search() in *RET_KB.
    1319             :  *
    1320             :  * On success, the function returns 0 and the caller must free *RET_KB
    1321             :  * using release_kbnode().  Otherwise, the function returns an error
    1322             :  * code.
    1323             :  *
    1324             :  * The returned keyblock has the kbnode flag bit 0 set for the node
    1325             :  * with the public key used to locate the keyblock or flag bit 1 set
    1326             :  * for the user ID node.  */
    1327             : gpg_error_t
    1328        3280 : keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
    1329             : {
    1330        3280 :   gpg_error_t err = 0;
    1331             : 
    1332        3280 :   *ret_kb = NULL;
    1333             : 
    1334        3280 :   if (!hd)
    1335           0 :     return gpg_error (GPG_ERR_INV_ARG);
    1336             : 
    1337        3280 :   if (DBG_CLOCK)
    1338           0 :     log_clock ("keydb_get_keybock enter");
    1339             : 
    1340        3280 :   if (hd->keyblock_cache.state == KEYBLOCK_CACHE_FILLED)
    1341             :     {
    1342           0 :       err = iobuf_seek (hd->keyblock_cache.iobuf, 0);
    1343           0 :       if (err)
    1344             :         {
    1345           0 :           log_error ("keydb_get_keyblock: failed to rewind iobuf for cache\n");
    1346           0 :           keyblock_cache_clear (hd);
    1347             :         }
    1348             :       else
    1349             :         {
    1350           0 :           err = parse_keyblock_image (hd->keyblock_cache.iobuf,
    1351             :                                       hd->keyblock_cache.pk_no,
    1352             :                                       hd->keyblock_cache.uid_no,
    1353           0 :                                       hd->keyblock_cache.sigstatus,
    1354             :                                       ret_kb);
    1355           0 :           if (err)
    1356           0 :             keyblock_cache_clear (hd);
    1357           0 :           if (DBG_CLOCK)
    1358           0 :             log_clock (err? "keydb_get_keyblock leave (cached, failed)"
    1359             :                        : "keydb_get_keyblock leave (cached)");
    1360           0 :           return err;
    1361             :         }
    1362             :     }
    1363             : 
    1364        3280 :   if (hd->found < 0 || hd->found >= hd->used)
    1365           0 :     return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
    1366             : 
    1367        3280 :   switch (hd->active[hd->found].type)
    1368             :     {
    1369             :     case KEYDB_RESOURCE_TYPE_NONE:
    1370           0 :       err = gpg_error (GPG_ERR_GENERAL); /* oops */
    1371           0 :       break;
    1372             :     case KEYDB_RESOURCE_TYPE_KEYRING:
    1373          50 :       err = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
    1374          50 :       break;
    1375             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
    1376             :       {
    1377             :         iobuf_t iobuf;
    1378             :         u32 *sigstatus;
    1379             :         int pk_no, uid_no;
    1380             : 
    1381        3230 :         err = keybox_get_keyblock (hd->active[hd->found].u.kb,
    1382             :                                    &iobuf, &pk_no, &uid_no, &sigstatus);
    1383        3230 :         if (!err)
    1384             :           {
    1385        3230 :             err = parse_keyblock_image (iobuf, pk_no, uid_no, sigstatus,
    1386             :                                         ret_kb);
    1387        3230 :             if (!err && hd->keyblock_cache.state == KEYBLOCK_CACHE_PREPARED)
    1388             :               {
    1389         465 :                 hd->keyblock_cache.state     = KEYBLOCK_CACHE_FILLED;
    1390         465 :                 hd->keyblock_cache.sigstatus = sigstatus;
    1391         465 :                 hd->keyblock_cache.iobuf     = iobuf;
    1392         465 :                 hd->keyblock_cache.pk_no     = pk_no;
    1393         465 :                 hd->keyblock_cache.uid_no    = uid_no;
    1394             :               }
    1395             :             else
    1396             :               {
    1397        2765 :                 xfree (sigstatus);
    1398        2765 :                 iobuf_close (iobuf);
    1399             :               }
    1400             :           }
    1401             :       }
    1402        3230 :       break;
    1403             :     }
    1404             : 
    1405        3280 :   if (hd->keyblock_cache.state != KEYBLOCK_CACHE_FILLED)
    1406        2815 :     keyblock_cache_clear (hd);
    1407             : 
    1408        3280 :   if (DBG_CLOCK)
    1409           0 :     log_clock (err? "keydb_get_keyblock leave (failed)"
    1410             :                : "keydb_get_keyblock leave");
    1411        3280 :   return err;
    1412             : }
    1413             : 
    1414             : 
    1415             : /* Build a keyblock image from KEYBLOCK.  Returns 0 on success and
    1416             :    only then stores a new iobuf object at R_IOBUF and a signature
    1417             :    status vecotor at R_SIGSTATUS.  */
    1418             : static gpg_error_t
    1419         162 : build_keyblock_image (kbnode_t keyblock, iobuf_t *r_iobuf, u32 **r_sigstatus)
    1420             : {
    1421             :   gpg_error_t err;
    1422             :   iobuf_t iobuf;
    1423             :   kbnode_t kbctx, node;
    1424             :   u32 n_sigs;
    1425             :   u32 *sigstatus;
    1426             : 
    1427         162 :   *r_iobuf = NULL;
    1428         162 :   if (r_sigstatus)
    1429         150 :     *r_sigstatus = NULL;
    1430             : 
    1431             :   /* Allocate a vector for the signature cache.  This is an array of
    1432             :      u32 values with the first value giving the number of elements to
    1433             :      follow and each element descriping the cache status of the
    1434             :      signature.  */
    1435         162 :   if (r_sigstatus)
    1436             :     {
    1437        1202 :       for (kbctx=NULL, n_sigs=0; (node = walk_kbnode (keyblock, &kbctx, 0));)
    1438         902 :         if (node->pkt->pkttype == PKT_SIGNATURE)
    1439         447 :           n_sigs++;
    1440         150 :       sigstatus = xtrycalloc (1+n_sigs, sizeof *sigstatus);
    1441         150 :       if (!sigstatus)
    1442           0 :         return gpg_error_from_syserror ();
    1443             :     }
    1444             :   else
    1445          12 :     sigstatus = NULL;
    1446             : 
    1447         162 :   iobuf = iobuf_temp ();
    1448        1313 :   for (kbctx = NULL, n_sigs = 0; (node = walk_kbnode (keyblock, &kbctx, 0));)
    1449             :     {
    1450             :       /* Make sure to use only packets valid on a keyblock.  */
    1451         989 :       switch (node->pkt->pkttype)
    1452             :         {
    1453             :         case PKT_PUBLIC_KEY:
    1454             :         case PKT_PUBLIC_SUBKEY:
    1455             :         case PKT_SIGNATURE:
    1456             :         case PKT_USER_ID:
    1457             :         case PKT_ATTRIBUTE:
    1458             :           /* Note that we don't want the ring trust packets.  They are
    1459             :              not useful. */
    1460         989 :           break;
    1461             :         default:
    1462           0 :           continue;
    1463             :         }
    1464             : 
    1465         989 :       err = build_packet (iobuf, node->pkt);
    1466         989 :       if (err)
    1467             :         {
    1468           0 :           iobuf_close (iobuf);
    1469           0 :           return err;
    1470             :         }
    1471             : 
    1472             :       /* Build signature status vector.  */
    1473         989 :       if (node->pkt->pkttype == PKT_SIGNATURE)
    1474             :         {
    1475         491 :           PKT_signature *sig = node->pkt->pkt.signature;
    1476             : 
    1477         491 :           n_sigs++;
    1478             :           /* Fixme: Detect the "missing key" status.  */
    1479         491 :           if (sig->flags.checked && sigstatus)
    1480             :             {
    1481         306 :               if (sig->flags.valid)
    1482             :                 {
    1483         306 :                   if (!sig->expiredate)
    1484         306 :                     sigstatus[n_sigs] = 0xffffffff;
    1485           0 :                   else if (sig->expiredate < 0x1000000)
    1486           0 :                     sigstatus[n_sigs] = 0x10000000;
    1487             :                   else
    1488           0 :                     sigstatus[n_sigs] = sig->expiredate;
    1489             :                 }
    1490             :               else
    1491           0 :                 sigstatus[n_sigs] = 0x00000002; /* Bad signature.  */
    1492             :             }
    1493             :         }
    1494             :     }
    1495         162 :   if (sigstatus)
    1496         150 :     sigstatus[0] = n_sigs;
    1497             : 
    1498         162 :   *r_iobuf = iobuf;
    1499         162 :   if (r_sigstatus)
    1500         150 :     *r_sigstatus = sigstatus;
    1501         162 :   return 0;
    1502             : }
    1503             : 
    1504             : 
    1505             : /* Update the keyblock KB (i.e., extract the fingerprint and find the
    1506             :  * corresponding keyblock in the keyring).
    1507             :  *
    1508             :  * This doesn't do anything if --dry-run was specified.
    1509             :  *
    1510             :  * Returns 0 on success.  Otherwise, it returns an error code.  Note:
    1511             :  * if there isn't a keyblock in the keyring corresponding to KB, then
    1512             :  * this function returns GPG_ERR_VALUE_NOT_FOUND.
    1513             :  *
    1514             :  * This function selects the matching record and modifies the current
    1515             :  * file position to point to the record just after the selected entry.
    1516             :  * Thus, if you do a subsequent search using HD, you should first do a
    1517             :  * keydb_search_reset.  Further, if the selected record is important,
    1518             :  * you should use keydb_push_found_state and keydb_pop_found_state to
    1519             :  * save and restore it.  */
    1520             : gpg_error_t
    1521          12 : keydb_update_keyblock (ctrl_t ctrl, KEYDB_HANDLE hd, kbnode_t kb)
    1522             : {
    1523             :   gpg_error_t err;
    1524             :   PKT_public_key *pk;
    1525             :   KEYDB_SEARCH_DESC desc;
    1526             :   size_t len;
    1527             : 
    1528          12 :   log_assert (kb);
    1529          12 :   log_assert (kb->pkt->pkttype == PKT_PUBLIC_KEY);
    1530          12 :   pk = kb->pkt->pkt.public_key;
    1531             : 
    1532          12 :   if (!hd)
    1533           0 :     return gpg_error (GPG_ERR_INV_ARG);
    1534             : 
    1535          12 :   kid_not_found_flush ();
    1536          12 :   keyblock_cache_clear (hd);
    1537             : 
    1538          12 :   if (opt.dry_run)
    1539           0 :     return 0;
    1540             : 
    1541          12 :   err = lock_all (hd);
    1542          12 :   if (err)
    1543           0 :     return err;
    1544             : 
    1545             : #ifdef USE_TOFU
    1546          12 :   tofu_notice_key_changed (ctrl, kb);
    1547             : #endif
    1548             : 
    1549          12 :   memset (&desc, 0, sizeof (desc));
    1550          12 :   fingerprint_from_pk (pk, desc.u.fpr, &len);
    1551          12 :   if (len == 20)
    1552          12 :     desc.mode = KEYDB_SEARCH_MODE_FPR20;
    1553             :   else
    1554           0 :     log_bug ("%s: Unsupported key length: %zu\n", __func__, len);
    1555             : 
    1556          12 :   keydb_search_reset (hd);
    1557          12 :   err = keydb_search (hd, &desc, 1, NULL);
    1558          12 :   if (err)
    1559           0 :     return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
    1560          12 :   log_assert (hd->found >= 0 && hd->found < hd->used);
    1561             : 
    1562          12 :   switch (hd->active[hd->found].type)
    1563             :     {
    1564             :     case KEYDB_RESOURCE_TYPE_NONE:
    1565           0 :       err = gpg_error (GPG_ERR_GENERAL); /* oops */
    1566           0 :       break;
    1567             :     case KEYDB_RESOURCE_TYPE_KEYRING:
    1568           0 :       err = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
    1569           0 :       break;
    1570             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
    1571             :       {
    1572             :         iobuf_t iobuf;
    1573             : 
    1574          12 :         err = build_keyblock_image (kb, &iobuf, NULL);
    1575          12 :         if (!err)
    1576             :           {
    1577          24 :             err = keybox_update_keyblock (hd->active[hd->found].u.kb,
    1578          12 :                                           iobuf_get_temp_buffer (iobuf),
    1579          12 :                                           iobuf_get_temp_length (iobuf));
    1580          12 :             iobuf_close (iobuf);
    1581             :           }
    1582             :       }
    1583          12 :       break;
    1584             :     }
    1585             : 
    1586          12 :   unlock_all (hd);
    1587          12 :   return err;
    1588             : }
    1589             : 
    1590             : 
    1591             : /* Insert a keyblock into one of the underlying keyrings or keyboxes.
    1592             :  *
    1593             :  * Be default, the keyring / keybox from which the last search result
    1594             :  * came is used.  If there was no previous search result (or
    1595             :  * keydb_search_reset was called), then the keyring / keybox where the
    1596             :  * next search would start is used (i.e., the current file position).
    1597             :  *
    1598             :  * Note: this doesn't do anything if --dry-run was specified.
    1599             :  *
    1600             :  * Returns 0 on success.  Otherwise, it returns an error code.  */
    1601             : gpg_error_t
    1602         151 : keydb_insert_keyblock (KEYDB_HANDLE hd, kbnode_t kb)
    1603             : {
    1604             :   gpg_error_t err;
    1605             :   int idx;
    1606             : 
    1607         151 :   if (!hd)
    1608           0 :     return gpg_error (GPG_ERR_INV_ARG);
    1609             : 
    1610         151 :   kid_not_found_flush ();
    1611         151 :   keyblock_cache_clear (hd);
    1612             : 
    1613         151 :   if (opt.dry_run)
    1614           0 :     return 0;
    1615             : 
    1616         151 :   if (hd->found >= 0 && hd->found < hd->used)
    1617           0 :     idx = hd->found;
    1618         151 :   else if (hd->current >= 0 && hd->current < hd->used)
    1619         151 :     idx = hd->current;
    1620             :   else
    1621           0 :     return gpg_error (GPG_ERR_GENERAL);
    1622             : 
    1623         151 :   err = lock_all (hd);
    1624         151 :   if (err)
    1625           0 :     return err;
    1626             : 
    1627         151 :   switch (hd->active[idx].type)
    1628             :     {
    1629             :     case KEYDB_RESOURCE_TYPE_NONE:
    1630           0 :       err = gpg_error (GPG_ERR_GENERAL); /* oops */
    1631           0 :       break;
    1632             :     case KEYDB_RESOURCE_TYPE_KEYRING:
    1633           1 :       err = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
    1634           1 :       break;
    1635             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
    1636             :       { /* We need to turn our kbnode_t list of packets into a proper
    1637             :            keyblock first.  This is required by the OpenPGP key parser
    1638             :            included in the keybox code.  Eventually we can change this
    1639             :            kludge to have the caller pass the image.  */
    1640             :         iobuf_t iobuf;
    1641             :         u32 *sigstatus;
    1642             : 
    1643         150 :         err = build_keyblock_image (kb, &iobuf, &sigstatus);
    1644         150 :         if (!err)
    1645             :           {
    1646         450 :             err = keybox_insert_keyblock (hd->active[idx].u.kb,
    1647         150 :                                           iobuf_get_temp_buffer (iobuf),
    1648         150 :                                           iobuf_get_temp_length (iobuf),
    1649             :                                           sigstatus);
    1650         150 :             xfree (sigstatus);
    1651         150 :             iobuf_close (iobuf);
    1652             :           }
    1653             :       }
    1654         150 :       break;
    1655             :     }
    1656             : 
    1657         151 :   unlock_all (hd);
    1658         151 :   return err;
    1659             : }
    1660             : 
    1661             : 
    1662             : /* Delete the currently selected keyblock.  If you haven't done a
    1663             :  * search yet on this database handle (or called keydb_search_reset),
    1664             :  * then this will return an error.
    1665             :  *
    1666             :  * Returns 0 on success or an error code, if an error occurs.  */
    1667             : gpg_error_t
    1668          87 : keydb_delete_keyblock (KEYDB_HANDLE hd)
    1669             : {
    1670             :   gpg_error_t rc;
    1671             : 
    1672          87 :   if (!hd)
    1673           0 :     return gpg_error (GPG_ERR_INV_ARG);
    1674             : 
    1675          87 :   kid_not_found_flush ();
    1676          87 :   keyblock_cache_clear (hd);
    1677             : 
    1678          87 :   if (hd->found < 0 || hd->found >= hd->used)
    1679           0 :     return gpg_error (GPG_ERR_VALUE_NOT_FOUND);
    1680             : 
    1681          87 :   if (opt.dry_run)
    1682           0 :     return 0;
    1683             : 
    1684          87 :   rc = lock_all (hd);
    1685          87 :   if (rc)
    1686           0 :     return rc;
    1687             : 
    1688          87 :   switch (hd->active[hd->found].type)
    1689             :     {
    1690             :     case KEYDB_RESOURCE_TYPE_NONE:
    1691           0 :       rc = gpg_error (GPG_ERR_GENERAL);
    1692           0 :       break;
    1693             :     case KEYDB_RESOURCE_TYPE_KEYRING:
    1694           0 :       rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
    1695           0 :       break;
    1696             :     case KEYDB_RESOURCE_TYPE_KEYBOX:
    1697          87 :       rc = keybox_delete (hd->active[hd->found].u.kb);
    1698          87 :       break;
    1699             :     }
    1700             : 
    1701          87 :   unlock_all (hd);
    1702          87 :   return rc;
    1703             : }
    1704             : 
    1705             : 
    1706             : 
    1707             : /* A database may consists of multiple keyrings / key boxes.  This
    1708             :  * sets the "file position" to the start of the first keyring / key
    1709             :  * box that is writable (i.e., doesn't have the read-only flag set).
    1710             :  *
    1711             :  * This first tries the primary keyring (the last keyring (not
    1712             :  * keybox!) added using keydb_add_resource() and with
    1713             :  * KEYDB_RESOURCE_FLAG_PRIMARY set).  If that is not writable, then it
    1714             :  * tries the keyrings / keyboxes in the order in which they were
    1715             :  * added.  */
    1716             : gpg_error_t
    1717         151 : keydb_locate_writable (KEYDB_HANDLE hd)
    1718             : {
    1719             :   gpg_error_t rc;
    1720             : 
    1721         151 :   if (!hd)
    1722           0 :     return GPG_ERR_INV_ARG;
    1723             : 
    1724         151 :   rc = keydb_search_reset (hd); /* this does reset hd->current */
    1725         151 :   if (rc)
    1726           0 :     return rc;
    1727             : 
    1728             :   /* If we have a primary set, try that one first */
    1729         151 :   if (primary_keydb)
    1730             :     {
    1731           0 :       for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
    1732             :         {
    1733           0 :           if(hd->active[hd->current].token == primary_keydb)
    1734             :             {
    1735           0 :               if(keyring_is_writable (hd->active[hd->current].token))
    1736           0 :                 return 0;
    1737             :               else
    1738           0 :                 break;
    1739             :             }
    1740             :         }
    1741             : 
    1742           0 :       rc = keydb_search_reset (hd); /* this does reset hd->current */
    1743           0 :       if (rc)
    1744           0 :         return rc;
    1745             :     }
    1746             : 
    1747         151 :   for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
    1748             :     {
    1749         151 :       switch (hd->active[hd->current].type)
    1750             :         {
    1751             :         case KEYDB_RESOURCE_TYPE_NONE:
    1752           0 :           BUG();
    1753             :           break;
    1754             :         case KEYDB_RESOURCE_TYPE_KEYRING:
    1755           1 :           if (keyring_is_writable (hd->active[hd->current].token))
    1756           1 :             return 0; /* found (hd->current is set to it) */
    1757           0 :           break;
    1758             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
    1759         150 :           if (keybox_is_writable (hd->active[hd->current].token))
    1760         150 :             return 0; /* found (hd->current is set to it) */
    1761           0 :           break;
    1762             :         }
    1763             :     }
    1764             : 
    1765           0 :   return gpg_error (GPG_ERR_NOT_FOUND);
    1766             : }
    1767             : 
    1768             : 
    1769             : /* Rebuild the on-disk caches of all key resources.  */
    1770             : void
    1771           3 : keydb_rebuild_caches (int noisy)
    1772             : {
    1773             :   int i, rc;
    1774             : 
    1775           6 :   for (i=0; i < used_resources; i++)
    1776             :     {
    1777           3 :       if (!keyring_is_writable (all_resources[i].token))
    1778           2 :         continue;
    1779           1 :       switch (all_resources[i].type)
    1780             :         {
    1781             :         case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
    1782           0 :           break;
    1783             :         case KEYDB_RESOURCE_TYPE_KEYRING:
    1784           1 :           rc = keyring_rebuild_cache (all_resources[i].token,noisy);
    1785           1 :           if (rc)
    1786           0 :             log_error (_("failed to rebuild keyring cache: %s\n"),
    1787             :                        gpg_strerror (rc));
    1788           1 :           break;
    1789             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
    1790             :           /* N/A.  */
    1791           0 :           break;
    1792             :         }
    1793             :     }
    1794           3 : }
    1795             : 
    1796             : 
    1797             : /* Return the number of skipped blocks (because they were to large to
    1798             :    read from a keybox) since the last search reset.  */
    1799             : unsigned long
    1800           3 : keydb_get_skipped_counter (KEYDB_HANDLE hd)
    1801             : {
    1802           3 :   return hd ? hd->skipped_long_blobs : 0;
    1803             : }
    1804             : 
    1805             : 
    1806             : /* Clears the current search result and resets the handle's position
    1807             :  * so that the next search starts at the beginning of the database
    1808             :  * (the start of the first resource).
    1809             :  *
    1810             :  * Returns 0 on success and an error code if an error occurred.
    1811             :  * (Currently, this function always returns 0 if HD is valid.)  */
    1812             : gpg_error_t
    1813         257 : keydb_search_reset (KEYDB_HANDLE hd)
    1814             : {
    1815         257 :   gpg_error_t rc = 0;
    1816             :   int i;
    1817             : 
    1818         257 :   if (!hd)
    1819           0 :     return gpg_error (GPG_ERR_INV_ARG);
    1820             : 
    1821         257 :   keyblock_cache_clear (hd);
    1822             : 
    1823         257 :   if (DBG_CLOCK)
    1824           0 :     log_clock ("keydb_search_reset");
    1825             : 
    1826         257 :   if (DBG_CACHE)
    1827           0 :     log_debug ("keydb_search: reset  (hd=%p)", hd);
    1828             : 
    1829         257 :   hd->skipped_long_blobs = 0;
    1830         257 :   hd->current = 0;
    1831         257 :   hd->found = -1;
    1832             :   /* Now reset all resources.  */
    1833         514 :   for (i=0; !rc && i < hd->used; i++)
    1834             :     {
    1835         257 :       switch (hd->active[i].type)
    1836             :         {
    1837             :         case KEYDB_RESOURCE_TYPE_NONE:
    1838           0 :           break;
    1839             :         case KEYDB_RESOURCE_TYPE_KEYRING:
    1840           4 :           rc = keyring_search_reset (hd->active[i].u.kr);
    1841           4 :           break;
    1842             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
    1843         253 :           rc = keybox_search_reset (hd->active[i].u.kb);
    1844         253 :           break;
    1845             :         }
    1846             :     }
    1847         257 :   hd->is_reset = 1;
    1848         257 :   return rc;
    1849             : }
    1850             : 
    1851             : 
    1852             : /* Search the database for keys matching the search description.  If
    1853             :  * the DB contains any legacy keys, these are silently ignored.
    1854             :  *
    1855             :  * DESC is an array of search terms with NDESC entries.  The search
    1856             :  * terms are or'd together.  That is, the next entry in the DB that
    1857             :  * matches any of the descriptions will be returned.
    1858             :  *
    1859             :  * Note: this function resumes searching where the last search left
    1860             :  * off (i.e., at the current file position).  If you want to search
    1861             :  * from the start of the database, then you need to first call
    1862             :  * keydb_search_reset().
    1863             :  *
    1864             :  * If no key matches the search description, returns
    1865             :  * GPG_ERR_NOT_FOUND.  If there was a match, returns 0.  If an error
    1866             :  * occurred, returns an error code.
    1867             :  *
    1868             :  * The returned key is considered to be selected and the raw data can,
    1869             :  * for instance, be returned by calling keydb_get_keyblock().  */
    1870             : gpg_error_t
    1871        3967 : keydb_search (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
    1872             :               size_t ndesc, size_t *descindex)
    1873             : {
    1874             :   int i;
    1875             :   gpg_error_t rc;
    1876        3967 :   int was_reset = hd->is_reset;
    1877             :   /* If an entry is already in the cache, then don't add it again.  */
    1878        3967 :   int already_in_cache = 0;
    1879             : 
    1880        3967 :   if (descindex)
    1881          12 :     *descindex = 0; /* Make sure it is always set on return.  */
    1882             : 
    1883        3967 :   if (!hd)
    1884           0 :     return gpg_error (GPG_ERR_INV_ARG);
    1885             : 
    1886        3967 :   if (!any_registered)
    1887             :     {
    1888           0 :       write_status_error ("keydb_search", gpg_error (GPG_ERR_KEYRING_OPEN));
    1889           0 :       return gpg_error (GPG_ERR_NOT_FOUND);
    1890             :     }
    1891             : 
    1892        3967 :   if (DBG_CLOCK)
    1893           0 :     log_clock ("keydb_search enter");
    1894             : 
    1895        3967 :   if (DBG_LOOKUP)
    1896             :     {
    1897           0 :       log_debug ("%s: %zd search descriptions:\n", __func__, ndesc);
    1898           0 :       for (i = 0; i < ndesc; i ++)
    1899             :         {
    1900           0 :           char *t = keydb_search_desc_dump (&desc[i]);
    1901           0 :           log_debug ("%s   %d: %s\n", __func__, i, t);
    1902           0 :           xfree (t);
    1903             :         }
    1904             :     }
    1905             : 
    1906             : 
    1907        3967 :   if (ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID
    1908        2463 :       && (already_in_cache = kid_not_found_p (desc[0].u.kid)) == 1 )
    1909             :     {
    1910           4 :       if (DBG_CLOCK)
    1911           0 :         log_clock ("keydb_search leave (not found, cached)");
    1912           4 :       return gpg_error (GPG_ERR_NOT_FOUND);
    1913             :     }
    1914             : 
    1915             :   /* NB: If one of the exact search modes below is used in a loop to
    1916             :      walk over all keys (with the same fingerprint) the caching must
    1917             :      have been disabled for the handle.  */
    1918        3963 :   if (!hd->no_caching
    1919        3551 :       && ndesc == 1
    1920        3549 :       && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
    1921        3118 :           || desc[0].mode == KEYDB_SEARCH_MODE_FPR)
    1922         627 :       && hd->keyblock_cache.state  == KEYBLOCK_CACHE_FILLED
    1923           0 :       && !memcmp (hd->keyblock_cache.fpr, desc[0].u.fpr, 20)
    1924             :       /* Make sure the current file position occurs before the cached
    1925             :          result to avoid an infinite loop.  */
    1926           0 :       && (hd->current < hd->keyblock_cache.resource
    1927           0 :           || (hd->current == hd->keyblock_cache.resource
    1928           0 :               && (keybox_offset (hd->active[hd->current].u.kb)
    1929           0 :                   <= hd->keyblock_cache.offset))))
    1930             :     {
    1931             :       /* (DESCINDEX is already set).  */
    1932           0 :       if (DBG_CLOCK)
    1933           0 :         log_clock ("keydb_search leave (cached)");
    1934             : 
    1935           0 :       hd->current = hd->keyblock_cache.resource;
    1936             :       /* HD->KEYBLOCK_CACHE.OFFSET is the last byte in the record.
    1937             :          Seek just beyond that.  */
    1938           0 :       keybox_seek (hd->active[hd->current].u.kb,
    1939           0 :                    hd->keyblock_cache.offset + 1);
    1940           0 :       return 0;
    1941             :     }
    1942             : 
    1943        3963 :   rc = -1;
    1944       11889 :   while ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
    1945        4634 :          && hd->current >= 0 && hd->current < hd->used)
    1946             :     {
    1947        3963 :       if (DBG_LOOKUP)
    1948           0 :         log_debug ("%s: searching %s (resource %d of %d)\n",
    1949             :                    __func__,
    1950           0 :                    hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING
    1951             :                    ? "keyring"
    1952           0 :                    : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX
    1953           0 :                       ? "keybox" : "unknown type"),
    1954             :                    hd->current, hd->used);
    1955             : 
    1956        3963 :        switch (hd->active[hd->current].type)
    1957             :         {
    1958             :         case KEYDB_RESOURCE_TYPE_NONE:
    1959           0 :           BUG(); /* we should never see it here */
    1960             :           break;
    1961             :         case KEYDB_RESOURCE_TYPE_KEYRING:
    1962          66 :           rc = keyring_search (hd->active[hd->current].u.kr, desc,
    1963             :                                ndesc, descindex, 1);
    1964          66 :           break;
    1965             :         case KEYDB_RESOURCE_TYPE_KEYBOX:
    1966             :           do
    1967        3897 :             rc = keybox_search (hd->active[hd->current].u.kb, desc,
    1968             :                                 ndesc, KEYBOX_BLOBTYPE_PGP,
    1969             :                                 descindex, &hd->skipped_long_blobs);
    1970        3897 :           while (rc == GPG_ERR_LEGACY_KEY);
    1971        3897 :           break;
    1972             :         }
    1973             : 
    1974        3963 :       if (DBG_LOOKUP)
    1975           0 :         log_debug ("%s: searched %s (resource %d of %d) => %s\n",
    1976             :                    __func__,
    1977           0 :                    hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYRING
    1978             :                    ? "keyring"
    1979           0 :                    : (hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX
    1980           0 :                       ? "keybox" : "unknown type"),
    1981             :                    hd->current, hd->used,
    1982             :                    rc == -1 ? "EOF" : gpg_strerror (rc));
    1983             : 
    1984        3963 :       if (rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
    1985             :         {
    1986             :           /* EOF -> switch to next resource */
    1987         671 :           hd->current++;
    1988             :         }
    1989        3292 :       else if (!rc)
    1990        3292 :         hd->found = hd->current;
    1991             :     }
    1992        3963 :   hd->is_reset = 0;
    1993             : 
    1994        7255 :   rc = ((rc == -1 || gpg_err_code (rc) == GPG_ERR_EOF)
    1995             :         ? gpg_error (GPG_ERR_NOT_FOUND)
    1996        4634 :         : rc);
    1997             : 
    1998        3963 :   keyblock_cache_clear (hd);
    1999        3963 :   if (!hd->no_caching
    2000        3551 :       && !rc
    2001        3152 :       && ndesc == 1 && (desc[0].mode == KEYDB_SEARCH_MODE_FPR20
    2002        2720 :                         || desc[0].mode == KEYDB_SEARCH_MODE_FPR)
    2003         478 :       && hd->active[hd->current].type == KEYDB_RESOURCE_TYPE_KEYBOX)
    2004             :     {
    2005         467 :       hd->keyblock_cache.state = KEYBLOCK_CACHE_PREPARED;
    2006         467 :       hd->keyblock_cache.resource = hd->current;
    2007             :       /* The current offset is at the start of the next record.  Since
    2008             :          a record is at least 1 byte, we just use offset - 1, which is
    2009             :          within the record.  */
    2010             :       hd->keyblock_cache.offset
    2011         467 :         = keybox_offset (hd->active[hd->current].u.kb) - 1;
    2012         467 :       memcpy (hd->keyblock_cache.fpr, desc[0].u.fpr, 20);
    2013             :     }
    2014             : 
    2015        3963 :   if (gpg_err_code (rc) == GPG_ERR_NOT_FOUND
    2016         671 :       && ndesc == 1 && desc[0].mode == KEYDB_SEARCH_MODE_LONG_KID && was_reset
    2017           8 :       && !already_in_cache)
    2018           8 :     kid_not_found_insert (desc[0].u.kid);
    2019             : 
    2020        3963 :   if (DBG_CLOCK)
    2021           0 :     log_clock (rc? "keydb_search leave (not found)"
    2022             :                  : "keydb_search leave (found)");
    2023        3963 :   return rc;
    2024             : }
    2025             : 
    2026             : 
    2027             : /* Return the first non-legacy key in the database.
    2028             :  *
    2029             :  * If you want the very first key in the database, you can directly
    2030             :  * call keydb_search with the search description
    2031             :  *  KEYDB_SEARCH_MODE_FIRST.  */
    2032             : gpg_error_t
    2033           3 : keydb_search_first (KEYDB_HANDLE hd)
    2034             : {
    2035             :   gpg_error_t err;
    2036             :   KEYDB_SEARCH_DESC desc;
    2037             : 
    2038           3 :   err = keydb_search_reset (hd);
    2039           3 :   if (err)
    2040           0 :     return err;
    2041             : 
    2042           3 :   memset (&desc, 0, sizeof desc);
    2043           3 :   desc.mode = KEYDB_SEARCH_MODE_FIRST;
    2044           3 :   return keydb_search (hd, &desc, 1, NULL);
    2045             : }
    2046             : 
    2047             : 
    2048             : /* Return the next key (not the next matching key!).
    2049             :  *
    2050             :  * Unlike calling keydb_search with KEYDB_SEARCH_MODE_NEXT, this
    2051             :  * function silently skips legacy keys.  */
    2052             : gpg_error_t
    2053           9 : keydb_search_next (KEYDB_HANDLE hd)
    2054             : {
    2055             :   KEYDB_SEARCH_DESC desc;
    2056             : 
    2057           9 :   memset (&desc, 0, sizeof desc);
    2058           9 :   desc.mode = KEYDB_SEARCH_MODE_NEXT;
    2059           9 :   return keydb_search (hd, &desc, 1, NULL);
    2060             : }
    2061             : 
    2062             : 
    2063             : /* This is a convenience function for searching for keys with a long
    2064             :  * key id.
    2065             :  *
    2066             :  * Note: this function resumes searching where the last search left
    2067             :  * off.  If you want to search the whole database, then you need to
    2068             :  * first call keydb_search_reset().  */
    2069             : gpg_error_t
    2070           3 : keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
    2071             : {
    2072             :   KEYDB_SEARCH_DESC desc;
    2073             : 
    2074           3 :   memset (&desc, 0, sizeof desc);
    2075           3 :   desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
    2076           3 :   desc.u.kid[0] = kid[0];
    2077           3 :   desc.u.kid[1] = kid[1];
    2078           3 :   return keydb_search (hd, &desc, 1, NULL);
    2079             : }
    2080             : 
    2081             : 
    2082             : /* This is a convenience function for searching for keys with a long
    2083             :  * (20 byte) fingerprint.
    2084             :  *
    2085             :  * Note: this function resumes searching where the last search left
    2086             :  * off.  If you want to search the whole database, then you need to
    2087             :  * first call keydb_search_reset().  */
    2088             : gpg_error_t
    2089         244 : keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
    2090             : {
    2091             :   KEYDB_SEARCH_DESC desc;
    2092             : 
    2093         244 :   memset (&desc, 0, sizeof desc);
    2094         244 :   desc.mode = KEYDB_SEARCH_MODE_FPR;
    2095         244 :   memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
    2096         244 :   return keydb_search (hd, &desc, 1, NULL);
    2097             : }

Generated by: LCOV version 1.11