LCOV - code coverage report
Current view: top level - g10 - import.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 819 1504 54.5 %
Date: 2016-11-29 15:00:56 Functions: 25 42 59.5 %

          Line data    Source code
       1             : /* import.c - import a key into our key storage.
       2             :  * Copyright (C) 1998-2007, 2010-2011 Free Software Foundation, Inc.
       3             :  * Copyright (C) 2014, 2016  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             : 
      27             : #include "gpg.h"
      28             : #include "options.h"
      29             : #include "packet.h"
      30             : #include "status.h"
      31             : #include "keydb.h"
      32             : #include "util.h"
      33             : #include "trustdb.h"
      34             : #include "main.h"
      35             : #include "i18n.h"
      36             : #include "ttyio.h"
      37             : #include "status.h"
      38             : #include "recsel.h"
      39             : #include "keyserver-internal.h"
      40             : #include "call-agent.h"
      41             : #include "../common/membuf.h"
      42             : #include "../common/init.h"
      43             : #include "../common/mbox-util.h"
      44             : 
      45             : 
      46             : struct import_stats_s
      47             : {
      48             :   ulong count;
      49             :   ulong no_user_id;
      50             :   ulong imported;
      51             :   ulong n_uids;
      52             :   ulong n_sigs;
      53             :   ulong n_subk;
      54             :   ulong unchanged;
      55             :   ulong n_revoc;
      56             :   ulong secret_read;
      57             :   ulong secret_imported;
      58             :   ulong secret_dups;
      59             :   ulong skipped_new_keys;
      60             :   ulong not_imported;
      61             :   ulong n_sigs_cleaned;
      62             :   ulong n_uids_cleaned;
      63             :   ulong v3keys;   /* Number of V3 keys seen.  */
      64             : };
      65             : 
      66             : 
      67             : /* Node flag to indicate that a user ID or a subkey has a
      68             :  * valid self-signature.  */
      69             : #define NODE_GOOD_SELFSIG  1
      70             : /* Node flag to indicate that a user ID or subkey has
      71             :  * an invalid self-signature.  */
      72             : #define NODE_BAD_SELFSIG   2
      73             : /* Node flag to indicate that the node shall be deleted.  */
      74             : #define NODE_DELETION_MARK 4
      75             : /* A node flag used to temporary mark a node. */
      76             : #define NODE_FLAG_A  8
      77             : 
      78             : 
      79             : /* A an object and a global instance to store selectors created from
      80             :  * --import-filter keep-uid=EXPR.
      81             :  * --import-filter drop-sig=EXPR.
      82             :  *
      83             :  * FIXME: We should put this into the CTRL object but that requires a
      84             :  * lot more changes right now.  For now we use save and restore
      85             :  * function to temporary change them.
      86             :  */
      87             : /* Definition of the import filters.  */
      88             : struct import_filter_s
      89             : {
      90             :   recsel_expr_t keep_uid;
      91             :   recsel_expr_t drop_sig;
      92             : };
      93             : /* The current instance.  */
      94             : struct import_filter_s import_filter;
      95             : 
      96             : 
      97             : static int import (ctrl_t ctrl,
      98             :                    IOBUF inp, const char* fname, struct import_stats_s *stats,
      99             :                    unsigned char **fpr, size_t *fpr_len, unsigned int options,
     100             :                    import_screener_t screener, void *screener_arg);
     101             : static int read_block (IOBUF a, PACKET **pending_pkt, kbnode_t *ret_root,
     102             :                        int *r_v3keys);
     103             : static void revocation_present (ctrl_t ctrl, kbnode_t keyblock);
     104             : static int import_one (ctrl_t ctrl,
     105             :                        kbnode_t keyblock,
     106             :                        struct import_stats_s *stats,
     107             :                        unsigned char **fpr, size_t *fpr_len,
     108             :                        unsigned int options, int from_sk, int silent,
     109             :                        import_screener_t screener, void *screener_arg);
     110             : static int import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
     111             :                               struct import_stats_s *stats, int batch,
     112             :                               unsigned int options, int for_migration,
     113             :                               import_screener_t screener, void *screener_arg);
     114             : static int import_revoke_cert (ctrl_t ctrl,
     115             :                                kbnode_t node, struct import_stats_s *stats);
     116             : static int chk_self_sigs (kbnode_t keyblock, u32 *keyid, int *non_self);
     117             : static int delete_inv_parts (kbnode_t keyblock,
     118             :                              u32 *keyid, unsigned int options);
     119             : static int any_uid_left (kbnode_t keyblock);
     120             : static int merge_blocks (kbnode_t keyblock_orig,
     121             :                          kbnode_t keyblock, u32 *keyid,
     122             :                          int *n_uids, int *n_sigs, int *n_subk );
     123             : static int append_uid (kbnode_t keyblock, kbnode_t node, int *n_sigs);
     124             : static int append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs);
     125             : static int merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs);
     126             : static int merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs);
     127             : 
     128             : 
     129             : 
     130             : static void
     131           0 : release_import_filter (import_filter_t filt)
     132             : {
     133           0 :   recsel_release (filt->keep_uid);
     134           0 :   filt->keep_uid = NULL;
     135           0 :   recsel_release (filt->drop_sig);
     136           0 :   filt->drop_sig = NULL;
     137           0 : }
     138             : 
     139             : static void
     140           0 : cleanup_import_globals (void)
     141             : {
     142           0 :   release_import_filter (&import_filter);
     143           0 : }
     144             : 
     145             : 
     146             : int
     147           0 : parse_import_options(char *str,unsigned int *options,int noisy)
     148             : {
     149           0 :   struct parse_options import_opts[]=
     150             :     {
     151             :       {"import-local-sigs",IMPORT_LOCAL_SIGS,NULL,
     152             :        N_("import signatures that are marked as local-only")},
     153             : 
     154             :       {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,
     155             :        N_("repair damage from the pks keyserver during import")},
     156             : 
     157             :       {"keep-ownertrust", IMPORT_KEEP_OWNERTTRUST, NULL,
     158             :        N_("do not clear the ownertrust values during import")},
     159             : 
     160             :       {"fast-import",IMPORT_FAST,NULL,
     161             :        N_("do not update the trustdb after import")},
     162             : 
     163             :       {"import-show",IMPORT_SHOW,NULL,
     164             :        N_("show key during import")},
     165             : 
     166             :       {"merge-only",IMPORT_MERGE_ONLY,NULL,
     167             :        N_("only accept updates to existing keys")},
     168             : 
     169             :       {"import-clean",IMPORT_CLEAN,NULL,
     170             :        N_("remove unusable parts from key after import")},
     171             : 
     172             :       {"import-minimal",IMPORT_MINIMAL|IMPORT_CLEAN,NULL,
     173             :        N_("remove as much as possible from key after import")},
     174             : 
     175             :       {"import-export", IMPORT_EXPORT, NULL,
     176             :        N_("run import filters and export key immediately")},
     177             : 
     178             :       /* Aliases for backward compatibility */
     179             :       {"allow-local-sigs",IMPORT_LOCAL_SIGS,NULL,NULL},
     180             :       {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG,NULL,NULL},
     181             :       /* dummy */
     182             :       {"import-unusable-sigs",0,NULL,NULL},
     183             :       {"import-clean-sigs",0,NULL,NULL},
     184             :       {"import-clean-uids",0,NULL,NULL},
     185             :       {"convert-sk-to-pk",0, NULL,NULL}, /* Not anymore needed due to
     186             :                                             the new design.  */
     187             :       {NULL,0,NULL,NULL}
     188             :     };
     189             : 
     190           0 :   return parse_options(str,options,import_opts,noisy);
     191             : }
     192             : 
     193             : 
     194             : /* Parse and set an import filter from string.  STRING has the format
     195             :  * "NAME=EXPR" with NAME being the name of the filter.  Spaces before
     196             :  * and after NAME are not allowed.  If this function is all called
     197             :  * several times all expressions for the same NAME are concatenated.
     198             :  * Supported filter names are:
     199             :  *
     200             :  *  - keep-uid :: If the expression evaluates to true for a certain
     201             :  *                user ID packet, that packet and all it dependencies
     202             :  *                will be imported.  The expression may use these
     203             :  *                variables:
     204             :  *
     205             :  *                - uid  :: The entire user ID.
     206             :  *                - mbox :: The mail box part of the user ID.
     207             :  *                - primary :: Evaluate to true for the primary user ID.
     208             :  */
     209             : gpg_error_t
     210           0 : parse_and_set_import_filter (const char *string)
     211             : {
     212             :   gpg_error_t err;
     213             : 
     214             :   /* Auto register the cleanup function.  */
     215           0 :   register_mem_cleanup_func (cleanup_import_globals);
     216             : 
     217           0 :   if (!strncmp (string, "keep-uid=", 9))
     218           0 :     err = recsel_parse_expr (&import_filter.keep_uid, string+9);
     219           0 :   else if (!strncmp (string, "drop-sig=", 9))
     220           0 :     err = recsel_parse_expr (&import_filter.drop_sig, string+9);
     221             :   else
     222           0 :     err = gpg_error (GPG_ERR_INV_NAME);
     223             : 
     224           0 :   return err;
     225             : }
     226             : 
     227             : 
     228             : /* Save the current import filters, return them, and clear the current
     229             :  * filters.  Returns NULL on error and sets ERRNO.  */
     230             : import_filter_t
     231           0 : save_and_clear_import_filter (void)
     232             : {
     233             :   import_filter_t filt;
     234             : 
     235           0 :   filt = xtrycalloc (1, sizeof *filt);
     236           0 :   if (!filt)
     237           0 :     return NULL;
     238           0 :   *filt = import_filter;
     239           0 :   memset (&import_filter, 0, sizeof import_filter);
     240             : 
     241           0 :   return filt;
     242             : }
     243             : 
     244             : 
     245             : /* Release the current import filters and restore them from NEWFILT.
     246             :  * Ownership of NEWFILT is moved to this function.  */
     247             : void
     248           0 : restore_import_filter (import_filter_t filt)
     249             : {
     250           0 :   if (filt)
     251             :     {
     252           0 :       release_import_filter (&import_filter);
     253           0 :       import_filter = *filt;
     254           0 :       xfree (filt);
     255             :     }
     256           0 : }
     257             : 
     258             : 
     259             : import_stats_t
     260          73 : import_new_stats_handle (void)
     261             : {
     262          73 :   return xmalloc_clear ( sizeof (struct import_stats_s) );
     263             : }
     264             : 
     265             : 
     266             : void
     267          73 : import_release_stats_handle (import_stats_t p)
     268             : {
     269          73 :   xfree (p);
     270          73 : }
     271             : 
     272             : 
     273             : /* Read a key from a file.  Only the first key in the file is
     274             :  * considered and stored at R_KEYBLOCK.  FNAME is the name of the
     275             :  * file.
     276             :  */
     277             : gpg_error_t
     278           6 : read_key_from_file (ctrl_t ctrl, const char *fname, kbnode_t *r_keyblock)
     279             : {
     280             :   gpg_error_t err;
     281             :   iobuf_t inp;
     282           6 :   PACKET *pending_pkt = NULL;
     283           6 :   kbnode_t keyblock = NULL;
     284             :   u32 keyid[2];
     285             :   int v3keys;   /* Dummy */
     286             :   int non_self; /* Dummy */
     287             : 
     288             :   (void)ctrl;
     289             : 
     290           6 :   *r_keyblock = NULL;
     291             : 
     292           6 :   inp = iobuf_open (fname);
     293           6 :   if (!inp)
     294           0 :     err = gpg_error_from_syserror ();
     295           6 :   else if (is_secured_file (iobuf_get_fd (inp)))
     296             :     {
     297           0 :       iobuf_close (inp);
     298           0 :       inp = NULL;
     299           0 :       err = gpg_error (GPG_ERR_EPERM);
     300             :     }
     301             :   else
     302           6 :     err = 0;
     303           6 :   if (err)
     304             :     {
     305           0 :       log_error (_("can't open '%s': %s\n"),
     306           0 :                  iobuf_is_pipe_filename (fname)? "[stdin]": fname,
     307             :                  gpg_strerror (err));
     308           0 :       if (gpg_err_code (err) == GPG_ERR_ENOENT)
     309           0 :         err = gpg_error (GPG_ERR_NO_PUBKEY);
     310           0 :       goto leave;
     311             :     }
     312             : 
     313             :   /* Push the armor filter.  */
     314             :   {
     315             :     armor_filter_context_t *afx;
     316           6 :     afx = new_armor_context ();
     317           6 :     afx->only_keyblocks = 1;
     318           6 :     push_armor_filter (afx, inp);
     319           6 :     release_armor_context (afx);
     320             :   }
     321             : 
     322             :   /* Read the first non-v3 keyblock.  */
     323          12 :   while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
     324             :     {
     325           6 :       if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
     326           6 :         break;
     327           0 :       log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
     328           0 :       release_kbnode (keyblock);
     329           0 :       keyblock = NULL;
     330             :     }
     331           6 :   if (err)
     332             :     {
     333           0 :       if (gpg_err_code (err) != GPG_ERR_INV_KEYRING)
     334           0 :         log_error (_("error reading '%s': %s\n"),
     335           0 :                    iobuf_is_pipe_filename (fname)? "[stdin]": fname,
     336             :                    gpg_strerror (err));
     337           0 :       goto leave;
     338             :     }
     339             : 
     340           6 :   keyid_from_pk (keyblock->pkt->pkt.public_key, keyid);
     341             : 
     342           6 :   if (!find_next_kbnode (keyblock, PKT_USER_ID))
     343             :     {
     344           0 :       err = gpg_error (GPG_ERR_NO_USER_ID);
     345           0 :       goto leave;
     346             :     }
     347             : 
     348           6 :   collapse_uids (&keyblock);
     349             : 
     350           6 :   clear_kbnode_flags (keyblock);
     351           6 :   if (chk_self_sigs (keyblock, keyid, &non_self))
     352             :     {
     353           0 :       err = gpg_error (GPG_ERR_INV_KEYRING);
     354           0 :       goto leave;
     355             :     }
     356             : 
     357           6 :   if (!delete_inv_parts (keyblock, keyid, 0) )
     358             :     {
     359           0 :       err = gpg_error (GPG_ERR_NO_USER_ID);
     360           0 :       goto leave;
     361             :     }
     362             : 
     363           6 :   *r_keyblock = keyblock;
     364           6 :   keyblock = NULL;
     365             : 
     366             :  leave:
     367           6 :   if (inp)
     368             :     {
     369           6 :       iobuf_close (inp);
     370             :       /* Must invalidate that ugly cache to actually close the file. */
     371           6 :       iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
     372             :     }
     373           6 :   release_kbnode (keyblock);
     374             :   /* FIXME: Do we need to free PENDING_PKT ? */
     375           6 :   return err;
     376             : }
     377             : 
     378             : 
     379             : 
     380             : /*
     381             :  * Import the public keys from the given filename. Input may be armored.
     382             :  * This function rejects all keys which are not validly self signed on at
     383             :  * least one userid. Only user ids which are self signed will be imported.
     384             :  * Other signatures are not checked.
     385             :  *
     386             :  * Actually this function does a merge. It works like this:
     387             :  *
     388             :  *  - get the keyblock
     389             :  *  - check self-signatures and remove all userids and their signatures
     390             :  *    without/invalid self-signatures.
     391             :  *  - reject the keyblock, if we have no valid userid.
     392             :  *  - See whether we have this key already in one of our pubrings.
     393             :  *    If not, simply add it to the default keyring.
     394             :  *  - Compare the key and the self-signatures of the new and the one in
     395             :  *    our keyring.  If they are different something weird is going on;
     396             :  *    ask what to do.
     397             :  *  - See whether we have only non-self-signature on one user id; if not
     398             :  *    ask the user what to do.
     399             :  *  - compare the signatures: If we already have this signature, check
     400             :  *    that they compare okay; if not, issue a warning and ask the user.
     401             :  *    (consider looking at the timestamp and use the newest?)
     402             :  *  - Simply add the signature.  Can't verify here because we may not have
     403             :  *    the signature's public key yet; verification is done when putting it
     404             :  *    into the trustdb, which is done automagically as soon as this pubkey
     405             :  *    is used.
     406             :  *  - Proceed with next signature.
     407             :  *
     408             :  *  Key revocation certificates have special handling.
     409             :  */
     410             : static int
     411          70 : import_keys_internal (ctrl_t ctrl, iobuf_t inp, char **fnames, int nnames,
     412             :                       import_stats_t stats_handle,
     413             :                       unsigned char **fpr, size_t *fpr_len,
     414             :                       unsigned int options,
     415             :                       import_screener_t screener, void *screener_arg)
     416             : {
     417             :   int i;
     418          70 :   int rc = 0;
     419          70 :   struct import_stats_s *stats = stats_handle;
     420             : 
     421          70 :   if (!stats)
     422          70 :     stats = import_new_stats_handle ();
     423             : 
     424          70 :   if (inp)
     425             :     {
     426           0 :       rc = import (ctrl, inp, "[stream]", stats, fpr, fpr_len, options,
     427             :                    screener, screener_arg);
     428             :     }
     429             :   else
     430             :     {
     431          70 :       if (!fnames && !nnames)
     432           1 :         nnames = 1;  /* Ohh what a ugly hack to jump into the loop */
     433             : 
     434         189 :       for (i=0; i < nnames; i++)
     435             :         {
     436         119 :           const char *fname = fnames? fnames[i] : NULL;
     437         119 :           IOBUF inp2 = iobuf_open(fname);
     438             : 
     439         119 :           if (!fname)
     440           1 :             fname = "[stdin]";
     441         119 :           if (inp2 && is_secured_file (iobuf_get_fd (inp2)))
     442             :             {
     443           0 :               iobuf_close (inp2);
     444           0 :               inp2 = NULL;
     445           0 :               gpg_err_set_errno (EPERM);
     446             :             }
     447         119 :           if (!inp2)
     448           0 :             log_error (_("can't open '%s': %s\n"), fname, strerror (errno));
     449             :           else
     450             :             {
     451         119 :               rc = import (ctrl, inp2, fname, stats, fpr, fpr_len, options,
     452             :                            screener, screener_arg);
     453         119 :               iobuf_close (inp2);
     454             :               /* Must invalidate that ugly cache to actually close it. */
     455         119 :               iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
     456         119 :               if (rc)
     457           0 :                 log_error ("import from '%s' failed: %s\n",
     458             :                            fname, gpg_strerror (rc) );
     459             :             }
     460         119 :           if (!fname)
     461           0 :             break;
     462             :         }
     463             :     }
     464             : 
     465          70 :   if (!stats_handle)
     466             :     {
     467          70 :       import_print_stats (stats);
     468          70 :       import_release_stats_handle (stats);
     469             :     }
     470             : 
     471             :   /* If no fast import and the trustdb is dirty (i.e. we added a key
     472             :      or userID that had something other than a selfsig, a signature
     473             :      that was other than a selfsig, or any revocation), then
     474             :      update/check the trustdb if the user specified by setting
     475             :      interactive or by not setting no-auto-check-trustdb */
     476             : 
     477          70 :   if (!(options & IMPORT_FAST))
     478          70 :     check_or_update_trustdb (ctrl);
     479             : 
     480          70 :   return rc;
     481             : }
     482             : 
     483             : 
     484             : void
     485          70 : import_keys (ctrl_t ctrl, char **fnames, int nnames,
     486             :              import_stats_t stats_handle, unsigned int options )
     487             : {
     488          70 :   import_keys_internal (ctrl, NULL, fnames, nnames, stats_handle,
     489             :                         NULL, NULL, options, NULL, NULL);
     490          70 : }
     491             : 
     492             : int
     493           0 : import_keys_stream (ctrl_t ctrl, IOBUF inp, import_stats_t stats_handle,
     494             :                     unsigned char **fpr, size_t *fpr_len, unsigned int options)
     495             : {
     496           0 :   return import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
     497             :                                fpr, fpr_len, options, NULL, NULL);
     498             : }
     499             : 
     500             : 
     501             : /* Variant of import_keys_stream reading from an estream_t.  */
     502             : int
     503           0 : import_keys_es_stream (ctrl_t ctrl, estream_t fp,
     504             :                        import_stats_t stats_handle,
     505             :                        unsigned char **fpr, size_t *fpr_len,
     506             :                        unsigned int options,
     507             :                        import_screener_t screener, void *screener_arg)
     508             : {
     509             :   int rc;
     510             :   iobuf_t inp;
     511             : 
     512           0 :   inp = iobuf_esopen (fp, "rb", 1);
     513           0 :   if (!inp)
     514             :     {
     515           0 :       rc = gpg_error_from_syserror ();
     516           0 :       log_error ("iobuf_esopen failed: %s\n", gpg_strerror (rc));
     517           0 :       return rc;
     518             :     }
     519             : 
     520           0 :   rc = import_keys_internal (ctrl, inp, NULL, 0, stats_handle,
     521             :                              fpr, fpr_len, options,
     522             :                              screener, screener_arg);
     523             : 
     524           0 :   iobuf_close (inp);
     525           0 :   return rc;
     526             : }
     527             : 
     528             : 
     529             : static int
     530         119 : import (ctrl_t ctrl, IOBUF inp, const char* fname,struct import_stats_s *stats,
     531             :         unsigned char **fpr,size_t *fpr_len, unsigned int options,
     532             :         import_screener_t screener, void *screener_arg)
     533             : {
     534         119 :   PACKET *pending_pkt = NULL;
     535         119 :   kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
     536             :                                 grasp the return semantics of
     537             :                                 read_block. */
     538         119 :   int rc = 0;
     539             :   int v3keys;
     540             : 
     541         119 :   getkey_disable_caches ();
     542             : 
     543         119 :   if (!opt.no_armor) /* Armored reading is not disabled.  */
     544             :     {
     545             :       armor_filter_context_t *afx;
     546             : 
     547         119 :       afx = new_armor_context ();
     548         119 :       afx->only_keyblocks = 1;
     549         119 :       push_armor_filter (afx, inp);
     550         119 :       release_armor_context (afx);
     551             :     }
     552             : 
     553         425 :   while (!(rc = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
     554             :     {
     555         187 :       stats->v3keys += v3keys;
     556         187 :       if (keyblock->pkt->pkttype == PKT_PUBLIC_KEY)
     557         178 :         rc = import_one (ctrl, keyblock,
     558             :                          stats, fpr, fpr_len, options, 0, 0,
     559             :                          screener, screener_arg);
     560           9 :       else if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
     561           9 :         rc = import_secret_one (ctrl, keyblock, stats,
     562             :                                 opt.batch, options, 0,
     563             :                                 screener, screener_arg);
     564           0 :       else if (keyblock->pkt->pkttype == PKT_SIGNATURE
     565           0 :                && keyblock->pkt->pkt.signature->sig_class == 0x20 )
     566           0 :         rc = import_revoke_cert (ctrl, keyblock, stats);
     567             :       else
     568             :         {
     569           0 :           log_info (_("skipping block of type %d\n"), keyblock->pkt->pkttype);
     570             :         }
     571         187 :       release_kbnode (keyblock);
     572             : 
     573             :       /* fixme: we should increment the not imported counter but
     574             :          this does only make sense if we keep on going despite of
     575             :          errors.  For now we do this only if the imported key is too
     576             :          large. */
     577         187 :       if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
     578           0 :             && gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
     579             :         {
     580           0 :           stats->not_imported++;
     581             :         }
     582         187 :       else if (rc)
     583           0 :         break;
     584             : 
     585         187 :       if (!(++stats->count % 100) && !opt.quiet)
     586           0 :         log_info (_("%lu keys processed so far\n"), stats->count );
     587             :     }
     588         119 :   stats->v3keys += v3keys;
     589         119 :   if (rc == -1)
     590         119 :     rc = 0;
     591           0 :   else if (rc && gpg_err_code (rc) != GPG_ERR_INV_KEYRING)
     592           0 :     log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (rc));
     593             : 
     594         119 :   return rc;
     595             : }
     596             : 
     597             : 
     598             : /* Helper to migrate secring.gpg to GnuPG 2.1.  */
     599             : gpg_error_t
     600           3 : import_old_secring (ctrl_t ctrl, const char *fname)
     601             : {
     602             :   gpg_error_t err;
     603             :   iobuf_t inp;
     604           3 :   PACKET *pending_pkt = NULL;
     605           3 :   kbnode_t keyblock = NULL;  /* Need to initialize because gcc can't
     606             :                                 grasp the return semantics of
     607             :                                 read_block. */
     608             :   struct import_stats_s *stats;
     609             :   int v3keys;
     610             : 
     611           3 :   inp = iobuf_open (fname);
     612           3 :   if (inp && is_secured_file (iobuf_get_fd (inp)))
     613             :     {
     614           0 :       iobuf_close (inp);
     615           0 :       inp = NULL;
     616           0 :       gpg_err_set_errno (EPERM);
     617             :     }
     618           3 :   if (!inp)
     619             :     {
     620           0 :       err = gpg_error_from_syserror ();
     621           0 :       log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
     622           0 :       return err;
     623             :     }
     624             : 
     625           3 :   getkey_disable_caches();
     626           3 :   stats = import_new_stats_handle ();
     627           3 :   while (!(err = read_block (inp, &pending_pkt, &keyblock, &v3keys)))
     628             :     {
     629           9 :       if (keyblock->pkt->pkttype == PKT_SECRET_KEY)
     630           9 :         err = import_secret_one (ctrl, keyblock, stats, 1, 0, 1,
     631             :                                  NULL, NULL);
     632           9 :       release_kbnode (keyblock);
     633           9 :       if (err)
     634           0 :         break;
     635             :     }
     636           3 :   import_release_stats_handle (stats);
     637           3 :   if (err == -1)
     638           3 :     err = 0;
     639           0 :   else if (err && gpg_err_code (err) != GPG_ERR_INV_KEYRING)
     640           0 :     log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
     641           0 :   else if (err)
     642           0 :     log_error ("import from '%s' failed: %s\n", fname, gpg_strerror (err));
     643             : 
     644           3 :   iobuf_close (inp);
     645           3 :   iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
     646             : 
     647           3 :   return err;
     648             : }
     649             : 
     650             : 
     651             : void
     652          70 : import_print_stats (import_stats_t stats)
     653             : {
     654          70 :   if (!opt.quiet)
     655             :     {
     656          69 :       log_info(_("Total number processed: %lu\n"),
     657          69 :                stats->count + stats->v3keys);
     658          69 :       if (stats->v3keys)
     659           0 :         log_info(_("    skipped PGP-2 keys: %lu\n"), stats->v3keys);
     660          69 :       if (stats->skipped_new_keys )
     661           0 :         log_info(_("      skipped new keys: %lu\n"),
     662             :                  stats->skipped_new_keys );
     663          69 :       if (stats->no_user_id )
     664           0 :         log_info(_("          w/o user IDs: %lu\n"), stats->no_user_id );
     665          69 :       if (stats->imported)
     666             :         {
     667          56 :           log_info(_("              imported: %lu"), stats->imported );
     668          56 :           log_printf ("\n");
     669             :         }
     670          69 :       if (stats->unchanged )
     671           4 :         log_info(_("             unchanged: %lu\n"), stats->unchanged );
     672          69 :       if (stats->n_uids )
     673           2 :         log_info(_("          new user IDs: %lu\n"), stats->n_uids );
     674          69 :       if (stats->n_subk )
     675           0 :         log_info(_("           new subkeys: %lu\n"), stats->n_subk );
     676          69 :       if (stats->n_sigs )
     677          10 :         log_info(_("        new signatures: %lu\n"), stats->n_sigs );
     678          69 :       if (stats->n_revoc )
     679           0 :         log_info(_("   new key revocations: %lu\n"), stats->n_revoc );
     680          69 :       if (stats->secret_read )
     681           9 :         log_info(_("      secret keys read: %lu\n"), stats->secret_read );
     682          69 :       if (stats->secret_imported )
     683           8 :         log_info(_("  secret keys imported: %lu\n"), stats->secret_imported );
     684          69 :       if (stats->secret_dups )
     685           1 :         log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
     686          69 :       if (stats->not_imported )
     687           0 :         log_info(_("          not imported: %lu\n"), stats->not_imported );
     688          69 :       if (stats->n_sigs_cleaned)
     689           0 :         log_info(_("    signatures cleaned: %lu\n"),stats->n_sigs_cleaned);
     690          69 :       if (stats->n_uids_cleaned)
     691           0 :         log_info(_("      user IDs cleaned: %lu\n"),stats->n_uids_cleaned);
     692             :     }
     693             : 
     694          70 :   if (is_status_enabled ())
     695             :     {
     696             :       char buf[15*20];
     697             : 
     698           2 :       snprintf (buf, sizeof buf,
     699             :                 "%lu %lu %lu 0 %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
     700           1 :                 stats->count + stats->v3keys,
     701             :                 stats->no_user_id,
     702             :                 stats->imported,
     703             :                 stats->unchanged,
     704             :                 stats->n_uids,
     705             :                 stats->n_subk,
     706             :                 stats->n_sigs,
     707             :                 stats->n_revoc,
     708             :                 stats->secret_read,
     709             :                 stats->secret_imported,
     710             :                 stats->secret_dups,
     711             :                 stats->skipped_new_keys,
     712             :                 stats->not_imported,
     713             :                 stats->v3keys );
     714           1 :       write_status_text (STATUS_IMPORT_RES, buf);
     715             :     }
     716          70 : }
     717             : 
     718             : 
     719             : /* Return true if PKTTYPE is valid in a keyblock.  */
     720             : static int
     721        1178 : valid_keyblock_packet (int pkttype)
     722             : {
     723        1178 :   switch (pkttype)
     724             :     {
     725             :     case PKT_PUBLIC_KEY:
     726             :     case PKT_PUBLIC_SUBKEY:
     727             :     case PKT_SECRET_KEY:
     728             :     case PKT_SECRET_SUBKEY:
     729             :     case PKT_SIGNATURE:
     730             :     case PKT_USER_ID:
     731             :     case PKT_ATTRIBUTE:
     732             :     case PKT_RING_TRUST:
     733        1178 :       return 1;
     734             :     default:
     735           0 :       return 0;
     736             :     }
     737             : }
     738             : 
     739             : 
     740             : /****************
     741             :  * Read the next keyblock from stream A.
     742             :  * PENDING_PKT should be initialzed to NULL
     743             :  * and not changed by the caller.
     744             :  * Return: 0 = okay, -1 no more blocks or another errorcode.
     745             :  *         The int at at R_V3KEY counts the number of unsupported v3
     746             :  *         keyblocks.
     747             :  */
     748             : static int
     749         324 : read_block( IOBUF a, PACKET **pending_pkt, kbnode_t *ret_root, int *r_v3keys)
     750             : {
     751             :   int rc;
     752             :   PACKET *pkt;
     753         324 :   kbnode_t root = NULL;
     754             :   int in_cert, in_v3key;
     755             : 
     756         324 :   *r_v3keys = 0;
     757             : 
     758         324 :   if (*pending_pkt)
     759             :     {
     760          74 :       root = new_kbnode( *pending_pkt );
     761          74 :       *pending_pkt = NULL;
     762          74 :       in_cert = 1;
     763             :     }
     764             :   else
     765         250 :     in_cert = 0;
     766             : 
     767         324 :   pkt = xmalloc (sizeof *pkt);
     768         324 :   init_packet (pkt);
     769         324 :   in_v3key = 0;
     770        1849 :   while ((rc=parse_packet(a, pkt)) != -1)
     771             :     {
     772        1275 :       if (rc && (gpg_err_code (rc) == GPG_ERR_LEGACY_KEY
     773           0 :                  && (pkt->pkttype == PKT_PUBLIC_KEY
     774           0 :                      || pkt->pkttype == PKT_SECRET_KEY)))
     775             :         {
     776           0 :           in_v3key = 1;
     777           0 :           ++*r_v3keys;
     778           0 :           free_packet (pkt);
     779           0 :           init_packet (pkt);
     780           0 :           continue;
     781             :         }
     782        1275 :       else if (rc ) /* (ignore errors) */
     783             :         {
     784           0 :           if (gpg_err_code (rc) == GPG_ERR_UNKNOWN_PACKET)
     785             :             ; /* Do not show a diagnostic.  */
     786             :           else
     787             :             {
     788           0 :               log_error("read_block: read error: %s\n", gpg_strerror (rc) );
     789           0 :               rc = GPG_ERR_INV_KEYRING;
     790           0 :               goto ready;
     791             :             }
     792           0 :           free_packet( pkt );
     793           0 :           init_packet(pkt);
     794           0 :           continue;
     795             :         }
     796             : 
     797        1275 :         if (in_v3key && !(pkt->pkttype == PKT_PUBLIC_KEY
     798           0 :                           || pkt->pkttype == PKT_SECRET_KEY))
     799             :           {
     800           0 :             free_packet( pkt );
     801           0 :             init_packet(pkt);
     802           0 :             continue;
     803             :           }
     804        1275 :         in_v3key = 0;
     805             : 
     806        1275 :         if (!root && pkt->pkttype == PKT_SIGNATURE
     807           0 :                   && pkt->pkt.signature->sig_class == 0x20 )
     808             :           {
     809             :             /* This is a revocation certificate which is handled in a
     810             :              * special way.  */
     811           0 :             root = new_kbnode( pkt );
     812           0 :             pkt = NULL;
     813           0 :             goto ready;
     814             :           }
     815             : 
     816             :         /* Make a linked list of all packets.  */
     817        1275 :         switch (pkt->pkttype)
     818             :           {
     819             :           case PKT_COMPRESSED:
     820           0 :             if (check_compress_algo (pkt->pkt.compressed->algorithm))
     821             :               {
     822           0 :                 rc = GPG_ERR_COMPR_ALGO;
     823           0 :                 goto ready;
     824             :               }
     825             :             else
     826             :               {
     827           0 :                 compress_filter_context_t *cfx = xmalloc_clear( sizeof *cfx );
     828           0 :                 pkt->pkt.compressed->buf = NULL;
     829           0 :                 push_compress_filter2(a,cfx,pkt->pkt.compressed->algorithm,1);
     830             :               }
     831           0 :             free_packet( pkt );
     832           0 :             init_packet(pkt);
     833           0 :             break;
     834             : 
     835             :           case PKT_RING_TRUST:
     836             :             /* Skip those packets.  */
     837          23 :             free_packet( pkt );
     838          23 :             init_packet(pkt);
     839          23 :             break;
     840             : 
     841             :           case PKT_PUBLIC_KEY:
     842             :           case PKT_SECRET_KEY:
     843         202 :             if (in_cert ) /* Store this packet.  */
     844             :               {
     845          74 :                 *pending_pkt = pkt;
     846          74 :                 pkt = NULL;
     847          74 :                 goto ready;
     848             :               }
     849         128 :             in_cert = 1;
     850             :           default:
     851        1178 :             if (in_cert && valid_keyblock_packet (pkt->pkttype))
     852             :               {
     853        1178 :                 if (!root )
     854         128 :                   root = new_kbnode (pkt);
     855             :                 else
     856        1050 :                   add_kbnode (root, new_kbnode (pkt));
     857        1178 :                 pkt = xmalloc (sizeof *pkt);
     858             :               }
     859        1178 :             init_packet(pkt);
     860        1178 :             break;
     861             :           }
     862             :     }
     863             : 
     864             :  ready:
     865         324 :   if (rc == -1 && root )
     866         128 :     rc = 0;
     867             : 
     868         324 :   if (rc )
     869         122 :     release_kbnode( root );
     870             :   else
     871         202 :     *ret_root = root;
     872         324 :   free_packet( pkt );
     873         324 :   xfree( pkt );
     874         324 :   return rc;
     875             : }
     876             : 
     877             : 
     878             : /* Walk through the subkeys on a pk to find if we have the PKS
     879             :    disease: multiple subkeys with their binding sigs stripped, and the
     880             :    sig for the first subkey placed after the last subkey.  That is,
     881             :    instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
     882             :    "pk uid sig sub1 sub2 sub3 bind1".  We can't do anything about sub2
     883             :    and sub3, as they are already lost, but we can try and rescue sub1
     884             :    by reordering the keyblock so that it reads "pk uid sig sub1 bind1
     885             :    sub2 sub3".  Returns TRUE if the keyblock was modified. */
     886             : static int
     887           0 : fix_pks_corruption (kbnode_t keyblock)
     888             : {
     889           0 :   int changed = 0;
     890           0 :   int keycount = 0;
     891             :   kbnode_t node;
     892           0 :   kbnode_t last = NULL;
     893           0 :   kbnode_t sknode=NULL;
     894             : 
     895             :   /* First determine if we have the problem at all.  Look for 2 or
     896             :      more subkeys in a row, followed by a single binding sig. */
     897           0 :   for (node=keyblock; node; last=node, node=node->next)
     898             :     {
     899           0 :       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
     900             :         {
     901           0 :           keycount++;
     902           0 :           if(!sknode)
     903           0 :             sknode=node;
     904             :         }
     905           0 :       else if (node->pkt->pkttype == PKT_SIGNATURE
     906           0 :                && node->pkt->pkt.signature->sig_class == 0x18
     907           0 :                && keycount >= 2
     908           0 :                && !node->next)
     909             :         {
     910             :           /* We might have the problem, as this key has two subkeys in
     911             :              a row without any intervening packets. */
     912             : 
     913             :           /* Sanity check */
     914           0 :           if (!last)
     915           0 :             break;
     916             : 
     917             :           /* Temporarily attach node to sknode. */
     918           0 :           node->next = sknode->next;
     919           0 :           sknode->next = node;
     920           0 :           last->next = NULL;
     921             : 
     922             :           /* Note we aren't checking whether this binding sig is a
     923             :              selfsig.  This is not necessary here as the subkey and
     924             :              binding sig will be rejected later if that is the
     925             :              case. */
     926           0 :           if (check_key_signature (keyblock,node,NULL))
     927             :             {
     928             :               /* Not a match, so undo the changes. */
     929           0 :               sknode->next = node->next;
     930           0 :               last->next = node;
     931           0 :               node->next = NULL;
     932           0 :               break;
     933             :             }
     934             :           else
     935             :             {
     936             :               /* Mark it good so we don't need to check it again */
     937           0 :               sknode->flag |= NODE_GOOD_SELFSIG;
     938           0 :               changed = 1;
     939           0 :               break;
     940             :             }
     941             :         }
     942             :       else
     943           0 :         keycount = 0;
     944             :     }
     945             : 
     946           0 :   return changed;
     947             : }
     948             : 
     949             : 
     950             : /* Versions of GnuPG before 1.4.11 and 2.0.16 allowed to import bogus
     951             :    direct key signatures.  A side effect of this was that a later
     952             :    import of the same good direct key signatures was not possible
     953             :    because the cmp_signature check in merge_blocks considered them
     954             :    equal.  Although direct key signatures are now checked during
     955             :    import, there might still be bogus signatures sitting in a keyring.
     956             :    We need to detect and delete them before doing a merge.  This
     957             :    function returns the number of removed sigs.  */
     958             : static int
     959          48 : fix_bad_direct_key_sigs (kbnode_t keyblock, u32 *keyid)
     960             : {
     961             :   gpg_error_t err;
     962             :   kbnode_t node;
     963          48 :   int count = 0;
     964             : 
     965          48 :   for (node = keyblock->next; node; node=node->next)
     966             :     {
     967          48 :       if (node->pkt->pkttype == PKT_USER_ID)
     968          48 :         break;
     969           0 :       if (node->pkt->pkttype == PKT_SIGNATURE
     970           0 :           && IS_KEY_SIG (node->pkt->pkt.signature))
     971             :         {
     972           0 :           err = check_key_signature (keyblock, node, NULL);
     973           0 :           if (err && gpg_err_code (err) != GPG_ERR_PUBKEY_ALGO )
     974             :             {
     975             :               /* If we don't know the error, we can't decide; this is
     976             :                  not a problem because cmp_signature can't compare the
     977             :                  signature either.  */
     978           0 :               log_info ("key %s: invalid direct key signature removed\n",
     979             :                         keystr (keyid));
     980           0 :               delete_kbnode (node);
     981           0 :               count++;
     982             :             }
     983             :         }
     984             :     }
     985             : 
     986          48 :   return count;
     987             : }
     988             : 
     989             : 
     990             : static void
     991           2 : print_import_ok (PKT_public_key *pk, unsigned int reason)
     992             : {
     993             :   byte array[MAX_FINGERPRINT_LEN], *s;
     994             :   char buf[MAX_FINGERPRINT_LEN*2+30], *p;
     995             :   size_t i, n;
     996             : 
     997           2 :   snprintf (buf, sizeof buf, "%u ", reason);
     998           2 :   p = buf + strlen (buf);
     999             : 
    1000           2 :   fingerprint_from_pk (pk, array, &n);
    1001           2 :   s = array;
    1002          42 :   for (i=0; i < n ; i++, s++, p += 2)
    1003          40 :     sprintf (p, "%02X", *s);
    1004             : 
    1005           2 :   write_status_text (STATUS_IMPORT_OK, buf);
    1006           2 : }
    1007             : 
    1008             : 
    1009             : static void
    1010           0 : print_import_check (PKT_public_key * pk, PKT_user_id * id)
    1011             : {
    1012             :   char * buf;
    1013             :   byte fpr[24];
    1014             :   u32 keyid[2];
    1015             :   size_t i, n;
    1016           0 :   size_t pos = 0;
    1017             : 
    1018           0 :   buf = xmalloc (17+41+id->len+32);
    1019           0 :   keyid_from_pk (pk, keyid);
    1020           0 :   sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
    1021           0 :   pos = 17;
    1022           0 :   fingerprint_from_pk (pk, fpr, &n);
    1023           0 :   for (i = 0; i < n; i++, pos += 2)
    1024           0 :     sprintf (buf+pos, "%02X", fpr[i]);
    1025           0 :   strcat (buf, " ");
    1026           0 :   strcat (buf, id->name);
    1027           0 :   write_status_text (STATUS_IMPORT_CHECK, buf);
    1028           0 :   xfree (buf);
    1029           0 : }
    1030             : 
    1031             : 
    1032             : static void
    1033           0 : check_prefs_warning(PKT_public_key *pk)
    1034             : {
    1035           0 :   log_info(_("WARNING: key %s contains preferences for unavailable\n"
    1036             :              "algorithms on these user IDs:\n"), keystr_from_pk(pk));
    1037           0 : }
    1038             : 
    1039             : 
    1040             : static void
    1041          27 : check_prefs (ctrl_t ctrl, kbnode_t keyblock)
    1042             : {
    1043             :   kbnode_t node;
    1044             :   PKT_public_key *pk;
    1045          27 :   int problem=0;
    1046             : 
    1047          27 :   merge_keys_and_selfsig(keyblock);
    1048          27 :   pk=keyblock->pkt->pkt.public_key;
    1049             : 
    1050         173 :   for(node=keyblock;node;node=node->next)
    1051             :     {
    1052         146 :       if(node->pkt->pkttype==PKT_USER_ID
    1053          31 :          && node->pkt->pkt.user_id->created
    1054          29 :          && node->pkt->pkt.user_id->prefs)
    1055             :         {
    1056          29 :           PKT_user_id *uid = node->pkt->pkt.user_id;
    1057          29 :           prefitem_t *prefs = uid->prefs;
    1058          29 :           char *user = utf8_to_native(uid->name,strlen(uid->name),0);
    1059             : 
    1060         284 :           for(;prefs->type;prefs++)
    1061             :             {
    1062             :               char num[10]; /* prefs->value is a byte, so we're over
    1063             :                                safe here */
    1064             : 
    1065         255 :               sprintf(num,"%u",prefs->value);
    1066             : 
    1067         255 :               if(prefs->type==PREFTYPE_SYM)
    1068             :                 {
    1069         111 :                   if (openpgp_cipher_test_algo (prefs->value))
    1070             :                     {
    1071           0 :                       const char *algo =
    1072           0 :                         (openpgp_cipher_test_algo (prefs->value)
    1073             :                          ? num
    1074           0 :                          : openpgp_cipher_algo_name (prefs->value));
    1075           0 :                       if(!problem)
    1076           0 :                         check_prefs_warning(pk);
    1077           0 :                       log_info(_("         \"%s\": preference for cipher"
    1078             :                                  " algorithm %s\n"), user, algo);
    1079           0 :                       problem=1;
    1080             :                     }
    1081             :                 }
    1082         144 :               else if(prefs->type==PREFTYPE_HASH)
    1083             :                 {
    1084          82 :                   if(openpgp_md_test_algo(prefs->value))
    1085             :                     {
    1086           0 :                       const char *algo =
    1087           0 :                         (gcry_md_test_algo (prefs->value)
    1088             :                          ? num
    1089           0 :                          : gcry_md_algo_name (prefs->value));
    1090           0 :                       if(!problem)
    1091           0 :                         check_prefs_warning(pk);
    1092           0 :                       log_info(_("         \"%s\": preference for digest"
    1093             :                                  " algorithm %s\n"), user, algo);
    1094           0 :                       problem=1;
    1095             :                     }
    1096             :                 }
    1097          62 :               else if(prefs->type==PREFTYPE_ZIP)
    1098             :                 {
    1099          62 :                   if(check_compress_algo (prefs->value))
    1100             :                     {
    1101           0 :                       const char *algo=compress_algo_to_string(prefs->value);
    1102           0 :                       if(!problem)
    1103           0 :                         check_prefs_warning(pk);
    1104           0 :                       log_info(_("         \"%s\": preference for compression"
    1105             :                                  " algorithm %s\n"),user,algo?algo:num);
    1106           0 :                       problem=1;
    1107             :                     }
    1108             :                 }
    1109             :             }
    1110             : 
    1111          29 :           xfree(user);
    1112             :         }
    1113             :     }
    1114             : 
    1115          27 :   if(problem)
    1116             :     {
    1117           0 :       log_info(_("it is strongly suggested that you update"
    1118             :                  " your preferences and\n"));
    1119           0 :       log_info(_("re-distribute this key to avoid potential algorithm"
    1120             :                  " mismatch problems\n"));
    1121             : 
    1122           0 :       if(!opt.batch)
    1123             :         {
    1124           0 :           strlist_t sl = NULL;
    1125           0 :           strlist_t locusr = NULL;
    1126           0 :           size_t fprlen=0;
    1127             :           byte fpr[MAX_FINGERPRINT_LEN], *p;
    1128             :           char username[(MAX_FINGERPRINT_LEN*2)+1];
    1129             :           unsigned int i;
    1130             : 
    1131           0 :           p = fingerprint_from_pk (pk,fpr,&fprlen);
    1132           0 :           for(i=0;i<fprlen;i++,p++)
    1133           0 :             sprintf(username+2*i,"%02X",*p);
    1134           0 :           add_to_strlist(&locusr,username);
    1135             : 
    1136           0 :           append_to_strlist(&sl,"updpref");
    1137           0 :           append_to_strlist(&sl,"save");
    1138             : 
    1139           0 :           keyedit_menu (ctrl, username, locusr, sl, 1, 1 );
    1140           0 :           free_strlist(sl);
    1141           0 :           free_strlist(locusr);
    1142             :         }
    1143           0 :       else if(!opt.quiet)
    1144           0 :         log_info(_("you can update your preferences with:"
    1145             :                    " gpg --edit-key %s updpref save\n"),keystr_from_pk(pk));
    1146             :     }
    1147          27 : }
    1148             : 
    1149             : 
    1150             : /* Helper for apply_*_filter in im,port.c and export.c.  */
    1151             : const char *
    1152           0 : impex_filter_getval (void *cookie, const char *propname)
    1153             : {
    1154             :   /* FIXME: Malloc our static buffers and access them via the cookie.  */
    1155           0 :   kbnode_t node = cookie;
    1156             :   static char numbuf[20];
    1157             :   const char *result;
    1158             : 
    1159           0 :   if (node->pkt->pkttype == PKT_USER_ID)
    1160             :     {
    1161           0 :       if (!strcmp (propname, "uid"))
    1162           0 :         result = node->pkt->pkt.user_id->name;
    1163           0 :       else if (!strcmp (propname, "mbox"))
    1164             :         {
    1165           0 :           if (!node->pkt->pkt.user_id->mbox)
    1166             :             {
    1167           0 :               node->pkt->pkt.user_id->mbox
    1168           0 :                 = mailbox_from_userid (node->pkt->pkt.user_id->name);
    1169             :             }
    1170           0 :           result = node->pkt->pkt.user_id->mbox;
    1171             :         }
    1172           0 :       else if (!strcmp (propname, "primary"))
    1173           0 :         result = node->pkt->pkt.user_id->is_primary? "1":"0";
    1174             :       else
    1175           0 :         result = NULL;
    1176             :     }
    1177           0 :   else if (node->pkt->pkttype == PKT_SIGNATURE
    1178           0 :            || node->pkt->pkttype == PKT_ATTRIBUTE)
    1179           0 :     {
    1180           0 :       PKT_signature *sig = node->pkt->pkt.signature;
    1181             : 
    1182           0 :       if (!strcmp (propname, "sig_created"))
    1183             :         {
    1184           0 :           snprintf (numbuf, sizeof numbuf, "%lu", (ulong)sig->timestamp);
    1185           0 :           result = numbuf;
    1186             :         }
    1187           0 :       else if (!strcmp (propname, "sig_created_d"))
    1188             :         {
    1189           0 :           result = datestr_from_sig (sig);
    1190             :         }
    1191           0 :       else if (!strcmp (propname, "sig_algo"))
    1192             :         {
    1193           0 :           snprintf (numbuf, sizeof numbuf, "%d", sig->pubkey_algo);
    1194           0 :           result = numbuf;
    1195             :         }
    1196           0 :       else if (!strcmp (propname, "sig_digest_algo"))
    1197             :         {
    1198           0 :           snprintf (numbuf, sizeof numbuf, "%d", sig->digest_algo);
    1199           0 :           result = numbuf;
    1200             :         }
    1201             :       else
    1202           0 :         result = NULL;
    1203             :     }
    1204           0 :   else if (node->pkt->pkttype == PKT_PUBLIC_KEY
    1205           0 :            || node->pkt->pkttype == PKT_SECRET_KEY
    1206           0 :            || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
    1207           0 :            || node->pkt->pkttype == PKT_SECRET_SUBKEY)
    1208           0 :     {
    1209           0 :       PKT_public_key *pk = node->pkt->pkt.public_key;
    1210             : 
    1211           0 :       if (!strcmp (propname, "secret"))
    1212             :         {
    1213           0 :           result = (node->pkt->pkttype == PKT_SECRET_KEY
    1214           0 :                     || node->pkt->pkttype == PKT_SECRET_SUBKEY)? "1":"0";
    1215             :         }
    1216           0 :       else if (!strcmp (propname, "key_algo"))
    1217             :         {
    1218           0 :           snprintf (numbuf, sizeof numbuf, "%d", pk->pubkey_algo);
    1219           0 :           result = numbuf;
    1220             :         }
    1221           0 :       if (!strcmp (propname, "key_created"))
    1222             :         {
    1223           0 :           snprintf (numbuf, sizeof numbuf, "%lu", (ulong)pk->timestamp);
    1224           0 :           result = numbuf;
    1225             :         }
    1226           0 :       else if (!strcmp (propname, "key_created_d"))
    1227             :         {
    1228           0 :           result = datestr_from_pk (pk);
    1229             :         }
    1230             :       else
    1231           0 :         result = NULL;
    1232             :     }
    1233             :   else
    1234           0 :     result = NULL;
    1235             : 
    1236           0 :   return result;
    1237             : }
    1238             : 
    1239             : 
    1240             : /*
    1241             :  * Apply the keep-uid filter to the keyblock.  The deleted nodes are
    1242             :  * marked and thus the caller should call commit_kbnode afterwards.
    1243             :  * KEYBLOCK must not have any blocks marked as deleted.
    1244             :  */
    1245             : static void
    1246           0 : apply_keep_uid_filter (kbnode_t keyblock, recsel_expr_t selector)
    1247             : {
    1248             :   kbnode_t node;
    1249             : 
    1250           0 :   for (node = keyblock->next; node; node = node->next )
    1251             :     {
    1252           0 :       if (node->pkt->pkttype == PKT_USER_ID)
    1253             :         {
    1254           0 :           if (!recsel_select (selector, impex_filter_getval, node))
    1255             :             {
    1256             : 
    1257             :               /* log_debug ("keep-uid: deleting '%s'\n", */
    1258             :               /*            node->pkt->pkt.user_id->name); */
    1259             :               /* The UID packet and all following packets up to the
    1260             :                * next UID or a subkey.  */
    1261           0 :               delete_kbnode (node);
    1262           0 :               for (; node->next
    1263           0 :                      && node->next->pkt->pkttype != PKT_USER_ID
    1264           0 :                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
    1265           0 :                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ;
    1266           0 :                    node = node->next)
    1267           0 :                 delete_kbnode (node->next);
    1268             :             }
    1269             :           /* else */
    1270             :           /*   log_debug ("keep-uid: keeping '%s'\n", */
    1271             :           /*              node->pkt->pkt.user_id->name); */
    1272             :         }
    1273             :     }
    1274           0 : }
    1275             : 
    1276             : 
    1277             : /*
    1278             :  * Apply the drop-sig filter to the keyblock.  The deleted nodes are
    1279             :  * marked and thus the caller should call commit_kbnode afterwards.
    1280             :  * KEYBLOCK must not have any blocks marked as deleted.
    1281             :  */
    1282             : static void
    1283           0 : apply_drop_sig_filter (kbnode_t keyblock, recsel_expr_t selector)
    1284             : {
    1285             :   kbnode_t node;
    1286           0 :   int active = 0;
    1287             :   u32 main_keyid[2];
    1288             :   PKT_signature *sig;
    1289             : 
    1290           0 :   keyid_from_pk (keyblock->pkt->pkt.public_key, main_keyid);
    1291             : 
    1292             :   /* Loop over all signatures for user id and attribute packets which
    1293             :    * are not self signatures.  */
    1294           0 :   for (node = keyblock->next; node; node = node->next )
    1295             :     {
    1296           0 :       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
    1297           0 :           || node->pkt->pkttype == PKT_SECRET_SUBKEY)
    1298             :         break; /* ready.  */
    1299           0 :       if (node->pkt->pkttype == PKT_USER_ID)
    1300           0 :         active = 1;
    1301           0 :       if (!active)
    1302           0 :         continue;
    1303           0 :       if (node->pkt->pkttype != PKT_SIGNATURE
    1304           0 :           && node->pkt->pkttype != PKT_ATTRIBUTE)
    1305           0 :         continue;
    1306             : 
    1307           0 :       sig = node->pkt->pkt.signature;
    1308           0 :       if (main_keyid[0] == sig->keyid[0] || main_keyid[1] == sig->keyid[1])
    1309           0 :         continue;  /* Skip self-signatures.  */
    1310             : 
    1311           0 :       if (IS_UID_SIG(sig) || IS_UID_REV(sig))
    1312             :         {
    1313           0 :           if (recsel_select (selector, impex_filter_getval, node))
    1314           0 :             delete_kbnode (node);
    1315             :         }
    1316             :     }
    1317           0 : }
    1318             : 
    1319             : 
    1320             : /*
    1321             :  * Try to import one keyblock. Return an error only in serious cases,
    1322             :  * but never for an invalid keyblock.  It uses log_error to increase
    1323             :  * the internal errorcount, so that invalid input can be detected by
    1324             :  * programs which called gpg.  If SILENT is no messages are printed -
    1325             :  * even most error messages are suppressed.
    1326             :  */
    1327             : static int
    1328         196 : import_one (ctrl_t ctrl,
    1329             :             kbnode_t keyblock, struct import_stats_s *stats,
    1330             :             unsigned char **fpr, size_t *fpr_len, unsigned int options,
    1331             :             int from_sk, int silent,
    1332             :             import_screener_t screener, void *screener_arg)
    1333             : {
    1334             :   PKT_public_key *pk;
    1335         196 :   PKT_public_key *pk_orig = NULL;
    1336             :   kbnode_t node, uidnode;
    1337         196 :   kbnode_t keyblock_orig = NULL;
    1338             :   byte fpr2[MAX_FINGERPRINT_LEN];
    1339             :   size_t fpr2len;
    1340             :   u32 keyid[2];
    1341         196 :   int rc = 0;
    1342         196 :   int new_key = 0;
    1343         196 :   int mod_key = 0;
    1344         196 :   int same_key = 0;
    1345         196 :   int non_self = 0;
    1346             :   size_t an;
    1347             :   char pkstrbuf[PUBKEY_STRING_SIZE];
    1348         196 :   int merge_keys_done = 0;
    1349         196 :   int any_filter = 0;
    1350             : 
    1351             :   /* Get the key and print some info about it. */
    1352         196 :   node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
    1353         196 :   if (!node )
    1354           0 :     BUG();
    1355             : 
    1356         196 :   pk = node->pkt->pkt.public_key;
    1357             : 
    1358         196 :   fingerprint_from_pk (pk, fpr2, &fpr2len);
    1359         196 :   for (an = fpr2len; an < MAX_FINGERPRINT_LEN; an++)
    1360           0 :     fpr2[an] = 0;
    1361         196 :   keyid_from_pk( pk, keyid );
    1362         196 :   uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
    1363             : 
    1364         196 :   if (opt.verbose && !opt.interactive && !silent)
    1365             :     {
    1366           0 :       log_info( "pub  %s/%s %s  ",
    1367             :                 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
    1368             :                 keystr_from_pk(pk), datestr_from_pk(pk) );
    1369           0 :       if (uidnode)
    1370           0 :         print_utf8_buffer (log_get_stream (),
    1371           0 :                            uidnode->pkt->pkt.user_id->name,
    1372           0 :                            uidnode->pkt->pkt.user_id->len );
    1373           0 :       log_printf ("\n");
    1374             :     }
    1375             : 
    1376             : 
    1377         196 :   if (!uidnode )
    1378             :     {
    1379           0 :       if (!silent)
    1380           0 :         log_error( _("key %s: no user ID\n"), keystr_from_pk(pk));
    1381           0 :       return 0;
    1382             :     }
    1383             : 
    1384         196 :   if (screener && screener (keyblock, screener_arg))
    1385             :     {
    1386           0 :       log_error (_("key %s: %s\n"), keystr_from_pk (pk),
    1387             :                  _("rejected by import screener"));
    1388           0 :       return 0;
    1389             :     }
    1390             : 
    1391         196 :   if (opt.interactive && !silent)
    1392             :     {
    1393           0 :       if (is_status_enabled())
    1394           0 :         print_import_check (pk, uidnode->pkt->pkt.user_id);
    1395           0 :       merge_keys_and_selfsig (keyblock);
    1396           0 :       tty_printf ("\n");
    1397           0 :       show_basic_key_info (keyblock);
    1398           0 :       tty_printf ("\n");
    1399           0 :       if (!cpr_get_answer_is_yes ("import.okay",
    1400             :                                   "Do you want to import this key? (y/N) "))
    1401           0 :         return 0;
    1402             :     }
    1403             : 
    1404         196 :   collapse_uids(&keyblock);
    1405             : 
    1406             :   /* Clean the key that we're about to import, to cut down on things
    1407             :      that we have to clean later.  This has no practical impact on the
    1408             :      end result, but does result in less logging which might confuse
    1409             :      the user. */
    1410         196 :   if (options&IMPORT_CLEAN)
    1411           0 :     clean_key (keyblock,opt.verbose,options&IMPORT_MINIMAL,NULL,NULL);
    1412             : 
    1413         196 :   clear_kbnode_flags( keyblock );
    1414             : 
    1415         196 :   if ((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
    1416           0 :       && opt.verbose)
    1417           0 :     log_info (_("key %s: PKS subkey corruption repaired\n"),
    1418             :               keystr_from_pk(pk));
    1419             : 
    1420         196 :   if (chk_self_sigs (keyblock, keyid, &non_self))
    1421           0 :     return 0;  /* Invalid keyblock - error already printed.  */
    1422             : 
    1423             :   /* If we allow such a thing, mark unsigned uids as valid */
    1424         196 :   if (opt.allow_non_selfsigned_uid)
    1425             :     {
    1426          16 :       for (node=keyblock; node; node = node->next )
    1427          12 :         if (node->pkt->pkttype == PKT_USER_ID
    1428           4 :             && !(node->flag & NODE_GOOD_SELFSIG)
    1429           4 :             && !(node->flag & NODE_BAD_SELFSIG) )
    1430             :           {
    1431           4 :             char *user=utf8_to_native(node->pkt->pkt.user_id->name,
    1432           4 :                                       node->pkt->pkt.user_id->len,0);
    1433             :             /* Fake a good signature status for the user id.  */
    1434           4 :             node->flag |= NODE_GOOD_SELFSIG;
    1435           4 :             log_info( _("key %s: accepted non self-signed user ID \"%s\"\n"),
    1436             :                       keystr_from_pk(pk),user);
    1437           4 :             xfree(user);
    1438             :           }
    1439             :     }
    1440             : 
    1441         196 :   if (!delete_inv_parts (keyblock, keyid, options ) )
    1442             :     {
    1443           0 :       if (!silent)
    1444             :         {
    1445           0 :           log_error( _("key %s: no valid user IDs\n"), keystr_from_pk(pk));
    1446           0 :           if (!opt.quiet )
    1447           0 :             log_info(_("this may be caused by a missing self-signature\n"));
    1448             :         }
    1449           0 :       stats->no_user_id++;
    1450           0 :       return 0;
    1451             :     }
    1452             : 
    1453             :   /* Get rid of deleted nodes.  */
    1454         196 :   commit_kbnode (&keyblock);
    1455             : 
    1456             :   /* Apply import filter.  */
    1457         196 :   if (import_filter.keep_uid)
    1458             :     {
    1459           0 :       apply_keep_uid_filter (keyblock, import_filter.keep_uid);
    1460           0 :       commit_kbnode (&keyblock);
    1461           0 :       any_filter = 1;
    1462             :     }
    1463         196 :   if (import_filter.drop_sig)
    1464             :     {
    1465           0 :       apply_drop_sig_filter (keyblock, import_filter.drop_sig);
    1466           0 :       commit_kbnode (&keyblock);
    1467           0 :       any_filter = 1;
    1468             :     }
    1469             : 
    1470             :   /* If we ran any filter we need to check that at least one user id
    1471             :    * is left in the keyring.  Note that we do not use log_error in
    1472             :    * this case. */
    1473         196 :   if (any_filter && !any_uid_left (keyblock))
    1474             :     {
    1475           0 :       if (!opt.quiet )
    1476           0 :         log_info ( _("key %s: no valid user IDs\n"), keystr_from_pk (pk));
    1477           0 :       stats->no_user_id++;
    1478           0 :       return 0;
    1479             :     }
    1480             : 
    1481             :   /* Show the key in the form it is merged or inserted.  We skip this
    1482             :    * if "import-export" is also active without --armor or the output
    1483             :    * file has explicily been given. */
    1484         196 :   if ((options & IMPORT_SHOW)
    1485           0 :       && !((options & IMPORT_EXPORT) && !opt.armor && !opt.outfile))
    1486             :     {
    1487           0 :       merge_keys_and_selfsig (keyblock);
    1488           0 :       merge_keys_done = 1;
    1489             :       /* Note that we do not want to show the validity because the key
    1490             :        * has not yet imported.  */
    1491           0 :       list_keyblock_direct (ctrl, keyblock, 0, 0, 1, 1);
    1492           0 :       es_fflush (es_stdout);
    1493             :     }
    1494             : 
    1495             :   /* Write the keyblock to the output and do not actually import.  */
    1496         196 :   if ((options & IMPORT_EXPORT))
    1497             :     {
    1498           0 :       if (!merge_keys_done)
    1499             :         {
    1500           0 :           merge_keys_and_selfsig (keyblock);
    1501           0 :           merge_keys_done = 1;
    1502             :         }
    1503           0 :       rc = write_keyblock_to_output (keyblock, opt.armor, opt.export_options);
    1504           0 :       goto leave;
    1505             :     }
    1506             : 
    1507         196 :   if (opt.dry_run)
    1508           0 :     goto leave;
    1509             : 
    1510             :   /* Do we have this key already in one of our pubrings ? */
    1511         196 :   pk_orig = xmalloc_clear( sizeof *pk_orig );
    1512         196 :   rc = get_pubkey_byfprint_fast (pk_orig, fpr2, fpr2len);
    1513         196 :   if (rc && gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
    1514           0 :       && gpg_err_code (rc) != GPG_ERR_UNUSABLE_PUBKEY )
    1515             :     {
    1516           0 :       if (!silent)
    1517           0 :         log_error (_("key %s: public key not found: %s\n"),
    1518             :                    keystr(keyid), gpg_strerror (rc));
    1519             :     }
    1520         196 :   else if ( rc && (opt.import_options&IMPORT_MERGE_ONLY) )
    1521             :     {
    1522           0 :       if (opt.verbose && !silent )
    1523           0 :         log_info( _("key %s: new key - skipped\n"), keystr(keyid));
    1524           0 :       rc = 0;
    1525           0 :       stats->skipped_new_keys++;
    1526             :     }
    1527         196 :   else if (rc )  /* Insert this key. */
    1528             :     {
    1529             :       KEYDB_HANDLE hd;
    1530             : 
    1531         148 :       hd = keydb_new ();
    1532         148 :       if (!hd)
    1533           0 :         return gpg_error_from_syserror ();
    1534             : 
    1535         148 :       rc = keydb_locate_writable (hd);
    1536         148 :       if (rc)
    1537             :         {
    1538           0 :           log_error (_("no writable keyring found: %s\n"), gpg_strerror (rc));
    1539           0 :           keydb_release (hd);
    1540           0 :           return GPG_ERR_GENERAL;
    1541             :         }
    1542         148 :       if (opt.verbose > 1 )
    1543           0 :         log_info (_("writing to '%s'\n"), keydb_get_resource_name (hd) );
    1544             : 
    1545         148 :       rc = keydb_insert_keyblock (hd, keyblock );
    1546         148 :       if (rc)
    1547           0 :         log_error (_("error writing keyring '%s': %s\n"),
    1548             :                    keydb_get_resource_name (hd), gpg_strerror (rc));
    1549         148 :       else if (!(opt.import_options & IMPORT_KEEP_OWNERTTRUST))
    1550             :         {
    1551             :           /* This should not be possible since we delete the
    1552             :              ownertrust when a key is deleted, but it can happen if
    1553             :              the keyring and trustdb are out of sync.  It can also
    1554             :              be made to happen with the trusted-key command and by
    1555             :              importing and locally exported key. */
    1556             : 
    1557         148 :           clear_ownertrusts (pk);
    1558         148 :           if (non_self)
    1559           3 :             revalidation_mark ();
    1560             :         }
    1561         148 :       keydb_release (hd);
    1562             : 
    1563             :       /* We are ready.  */
    1564         148 :       if (!opt.quiet && !silent)
    1565             :         {
    1566         147 :           char *p = get_user_id_byfpr_native (fpr2);
    1567         147 :           log_info (_("key %s: public key \"%s\" imported\n"),
    1568             :                     keystr(keyid), p);
    1569         147 :           xfree(p);
    1570             :         }
    1571         148 :       if (is_status_enabled())
    1572             :         {
    1573           1 :           char *us = get_long_user_id_string( keyid );
    1574           1 :           write_status_text( STATUS_IMPORTED, us );
    1575           1 :           xfree(us);
    1576           1 :           print_import_ok (pk, 1);
    1577             :         }
    1578         148 :       stats->imported++;
    1579         148 :       new_key = 1;
    1580             :     }
    1581             :   else /* merge */
    1582             :     {
    1583             :       KEYDB_HANDLE hd;
    1584             :       int n_uids, n_sigs, n_subk, n_sigs_cleaned, n_uids_cleaned;
    1585             : 
    1586             :       /* Compare the original against the new key; just to be sure nothing
    1587             :        * weird is going on */
    1588          48 :       if (cmp_public_keys( pk_orig, pk ) )
    1589             :         {
    1590           0 :           if (!silent)
    1591           0 :             log_error( _("key %s: doesn't match our copy\n"),keystr(keyid));
    1592           0 :           goto leave;
    1593             :         }
    1594             : 
    1595             :       /* Now read the original keyblock again so that we can use
    1596             :          that handle for updating the keyblock.  */
    1597          48 :       hd = keydb_new ();
    1598          48 :       if (!hd)
    1599             :         {
    1600           0 :           rc = gpg_error_from_syserror ();
    1601           0 :           goto leave;
    1602             :         }
    1603          48 :       keydb_disable_caching (hd);
    1604          48 :       rc = keydb_search_fpr (hd, fpr2);
    1605          48 :       if (rc )
    1606             :         {
    1607           0 :           log_error (_("key %s: can't locate original keyblock: %s\n"),
    1608             :                      keystr(keyid), gpg_strerror (rc));
    1609           0 :           keydb_release (hd);
    1610           0 :           goto leave;
    1611             :         }
    1612          48 :       rc = keydb_get_keyblock (hd, &keyblock_orig);
    1613          48 :       if (rc)
    1614             :         {
    1615           0 :           log_error (_("key %s: can't read original keyblock: %s\n"),
    1616             :                      keystr(keyid), gpg_strerror (rc));
    1617           0 :           keydb_release (hd);
    1618           0 :           goto leave;
    1619             :         }
    1620             : 
    1621             :       /* Make sure the original direct key sigs are all sane.  */
    1622          48 :       n_sigs_cleaned = fix_bad_direct_key_sigs (keyblock_orig, keyid);
    1623          48 :       if (n_sigs_cleaned)
    1624           0 :         commit_kbnode (&keyblock_orig);
    1625             : 
    1626             :       /* and try to merge the block */
    1627          48 :       clear_kbnode_flags( keyblock_orig );
    1628          48 :       clear_kbnode_flags( keyblock );
    1629          48 :       n_uids = n_sigs = n_subk = n_uids_cleaned = 0;
    1630          48 :       rc = merge_blocks (keyblock_orig, keyblock,
    1631             :                          keyid, &n_uids, &n_sigs, &n_subk );
    1632          48 :       if (rc )
    1633             :         {
    1634           0 :           keydb_release (hd);
    1635           0 :           goto leave;
    1636             :         }
    1637             : 
    1638          48 :       if ((options & IMPORT_CLEAN))
    1639           0 :         clean_key (keyblock_orig,opt.verbose,options&IMPORT_MINIMAL,
    1640             :                    &n_uids_cleaned,&n_sigs_cleaned);
    1641             : 
    1642          48 :       if (n_uids || n_sigs || n_subk || n_sigs_cleaned || n_uids_cleaned)
    1643             :         {
    1644          10 :           mod_key = 1;
    1645             :           /* KEYBLOCK_ORIG has been updated; write */
    1646          10 :           rc = keydb_update_keyblock (ctrl, hd, keyblock_orig);
    1647          10 :           if (rc)
    1648           0 :             log_error (_("error writing keyring '%s': %s\n"),
    1649             :                        keydb_get_resource_name (hd), gpg_strerror (rc) );
    1650          10 :           else if (non_self)
    1651           8 :             revalidation_mark ();
    1652             : 
    1653             :           /* We are ready.  */
    1654          10 :           if (!opt.quiet && !silent)
    1655             :             {
    1656          10 :               char *p = get_user_id_byfpr_native (fpr2);
    1657          10 :               if (n_uids == 1 )
    1658           2 :                 log_info( _("key %s: \"%s\" 1 new user ID\n"),
    1659             :                           keystr(keyid),p);
    1660           8 :               else if (n_uids )
    1661           0 :                 log_info( _("key %s: \"%s\" %d new user IDs\n"),
    1662             :                           keystr(keyid),p,n_uids);
    1663          10 :               if (n_sigs == 1 )
    1664          10 :                 log_info( _("key %s: \"%s\" 1 new signature\n"),
    1665             :                           keystr(keyid), p);
    1666           0 :               else if (n_sigs )
    1667           0 :                 log_info( _("key %s: \"%s\" %d new signatures\n"),
    1668             :                           keystr(keyid), p, n_sigs );
    1669          10 :               if (n_subk == 1 )
    1670           0 :                 log_info( _("key %s: \"%s\" 1 new subkey\n"),
    1671             :                           keystr(keyid), p);
    1672          10 :               else if (n_subk )
    1673           0 :                 log_info( _("key %s: \"%s\" %d new subkeys\n"),
    1674             :                           keystr(keyid), p, n_subk );
    1675          10 :               if (n_sigs_cleaned==1)
    1676           0 :                 log_info(_("key %s: \"%s\" %d signature cleaned\n"),
    1677             :                          keystr(keyid),p,n_sigs_cleaned);
    1678          10 :               else if (n_sigs_cleaned)
    1679           0 :                 log_info(_("key %s: \"%s\" %d signatures cleaned\n"),
    1680             :                          keystr(keyid),p,n_sigs_cleaned);
    1681          10 :               if (n_uids_cleaned==1)
    1682           0 :                 log_info(_("key %s: \"%s\" %d user ID cleaned\n"),
    1683             :                          keystr(keyid),p,n_uids_cleaned);
    1684          10 :               else if (n_uids_cleaned)
    1685           0 :                 log_info(_("key %s: \"%s\" %d user IDs cleaned\n"),
    1686             :                          keystr(keyid),p,n_uids_cleaned);
    1687          10 :               xfree(p);
    1688             :             }
    1689             : 
    1690          10 :           stats->n_uids +=n_uids;
    1691          10 :           stats->n_sigs +=n_sigs;
    1692          10 :           stats->n_subk +=n_subk;
    1693          10 :           stats->n_sigs_cleaned +=n_sigs_cleaned;
    1694          10 :           stats->n_uids_cleaned +=n_uids_cleaned;
    1695             : 
    1696          20 :           if (is_status_enabled () && !silent)
    1697           0 :             print_import_ok (pk, ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
    1698             :         }
    1699             :       else
    1700             :         {
    1701          38 :           same_key = 1;
    1702          38 :           if (is_status_enabled ())
    1703           0 :             print_import_ok (pk, 0);
    1704             : 
    1705          38 :           if (!opt.quiet && !silent)
    1706             :             {
    1707          29 :               char *p = get_user_id_byfpr_native (fpr2);
    1708          29 :               log_info( _("key %s: \"%s\" not changed\n"),keystr(keyid),p);
    1709          29 :               xfree(p);
    1710             :             }
    1711             : 
    1712          38 :           stats->unchanged++;
    1713             :         }
    1714             : 
    1715          48 :       keydb_release (hd); hd = NULL;
    1716             :     }
    1717             : 
    1718             :  leave:
    1719         196 :   if (mod_key || new_key || same_key)
    1720             :     {
    1721             :       /* A little explanation for this: we fill in the fingerprint
    1722             :          when importing keys as it can be useful to know the
    1723             :          fingerprint in certain keyserver-related cases (a keyserver
    1724             :          asked for a particular name, but the key doesn't have that
    1725             :          name).  However, in cases where we're importing more than
    1726             :          one key at a time, we cannot know which key to fingerprint.
    1727             :          In these cases, rather than guessing, we do not
    1728             :          fingerprinting at all, and we must hope the user ID on the
    1729             :          keys are useful.  Note that we need to do this for new
    1730             :          keys, merged keys and even for unchanged keys.  This is
    1731             :          required because for example the --auto-key-locate feature
    1732             :          may import an already imported key and needs to know the
    1733             :          fingerprint of the key in all cases.  */
    1734         196 :       if (fpr)
    1735             :         {
    1736           0 :           xfree (*fpr);
    1737             :           /* Note that we need to compare against 0 here because
    1738             :              COUNT gets only incremented after returning from this
    1739             :              function.  */
    1740           0 :           if (!stats->count)
    1741           0 :             *fpr = fingerprint_from_pk (pk, NULL, fpr_len);
    1742             :           else
    1743           0 :             *fpr = NULL;
    1744             :         }
    1745             :     }
    1746             : 
    1747             :   /* Now that the key is definitely incorporated into the keydb, we
    1748             :      need to check if a designated revocation is present or if the
    1749             :      prefs are not rational so we can warn the user. */
    1750             : 
    1751         196 :   if (mod_key)
    1752             :     {
    1753          10 :       revocation_present (ctrl, keyblock_orig);
    1754          10 :       if (!from_sk && have_secret_key_with_kid (keyid))
    1755           0 :         check_prefs (ctrl, keyblock_orig);
    1756             :     }
    1757         186 :   else if (new_key)
    1758             :     {
    1759         148 :       revocation_present (ctrl, keyblock);
    1760         148 :       if (!from_sk && have_secret_key_with_kid (keyid))
    1761           9 :         check_prefs (ctrl, keyblock);
    1762             :     }
    1763             : 
    1764         196 :   release_kbnode( keyblock_orig );
    1765         196 :   free_public_key( pk_orig );
    1766             : 
    1767         196 :   return rc;
    1768             : }
    1769             : 
    1770             : 
    1771             : /* Transfer all the secret keys in SEC_KEYBLOCK to the gpg-agent.  The
    1772             :    function prints diagnostics and returns an error code.  If BATCH is
    1773             :    true the secret keys are stored by gpg-agent in the transfer format
    1774             :    (i.e. no re-protection and aksing for passphrases). */
    1775             : gpg_error_t
    1776          18 : transfer_secret_keys (ctrl_t ctrl, struct import_stats_s *stats,
    1777             :                       kbnode_t sec_keyblock, int batch, int force)
    1778             : {
    1779          18 :   gpg_error_t err = 0;
    1780          18 :   void *kek = NULL;
    1781             :   size_t keklen;
    1782          18 :   kbnode_t ctx = NULL;
    1783             :   kbnode_t node;
    1784             :   PKT_public_key *main_pk, *pk;
    1785             :   struct seckey_info *ski;
    1786             :   int nskey;
    1787             :   membuf_t mbuf;
    1788             :   int i, j;
    1789             :   void *format_args[2*PUBKEY_MAX_NSKEY];
    1790             :   gcry_sexp_t skey, prot, tmpsexp;
    1791          18 :   gcry_sexp_t curve = NULL;
    1792          18 :   unsigned char *transferkey = NULL;
    1793             :   size_t transferkeylen;
    1794          18 :   gcry_cipher_hd_t cipherhd = NULL;
    1795          18 :   unsigned char *wrappedkey = NULL;
    1796             :   size_t wrappedkeylen;
    1797          18 :   char *cache_nonce = NULL;
    1798          18 :   int stub_key_skipped = 0;
    1799             : 
    1800             :   /* Get the current KEK.  */
    1801          18 :   err = agent_keywrap_key (ctrl, 0, &kek, &keklen);
    1802          18 :   if (err)
    1803             :     {
    1804           0 :       log_error ("error getting the KEK: %s\n", gpg_strerror (err));
    1805           0 :       goto leave;
    1806             :     }
    1807             : 
    1808             :   /* Prepare a cipher context.  */
    1809          18 :   err = gcry_cipher_open (&cipherhd, GCRY_CIPHER_AES128,
    1810             :                           GCRY_CIPHER_MODE_AESWRAP, 0);
    1811          18 :   if (!err)
    1812          18 :     err = gcry_cipher_setkey (cipherhd, kek, keklen);
    1813          18 :   if (err)
    1814           0 :     goto leave;
    1815          18 :   xfree (kek);
    1816          18 :   kek = NULL;
    1817             : 
    1818          18 :   main_pk = NULL;
    1819         119 :   while ((node = walk_kbnode (sec_keyblock, &ctx, 0)))
    1820             :     {
    1821          83 :       if (node->pkt->pkttype != PKT_SECRET_KEY
    1822          65 :           && node->pkt->pkttype != PKT_SECRET_SUBKEY)
    1823          50 :         continue;
    1824          33 :       pk = node->pkt->pkt.public_key;
    1825          33 :       if (!main_pk)
    1826          18 :         main_pk = pk;
    1827             : 
    1828             :       /* Make sure the keyids are available.  */
    1829          33 :       keyid_from_pk (pk, NULL);
    1830          33 :       if (node->pkt->pkttype == PKT_SECRET_KEY)
    1831             :         {
    1832          18 :           pk->main_keyid[0] = pk->keyid[0];
    1833          18 :           pk->main_keyid[1] = pk->keyid[1];
    1834             :         }
    1835             :       else
    1836             :         {
    1837          15 :           pk->main_keyid[0] = main_pk->keyid[0];
    1838          15 :           pk->main_keyid[1] = main_pk->keyid[1];
    1839             :         }
    1840             : 
    1841             : 
    1842          33 :       ski = pk->seckey_info;
    1843          33 :       if (!ski)
    1844           0 :         BUG ();
    1845             : 
    1846          33 :       if (stats)
    1847             :         {
    1848          33 :           stats->count++;
    1849          33 :           stats->secret_read++;
    1850             :         }
    1851             : 
    1852             :       /* We ignore stub keys.  The way we handle them in other parts
    1853             :          of the code is by asking the agent whether any secret key is
    1854             :          available for a given keyblock and then concluding that we
    1855             :          have a secret key; all secret (sub)keys of the keyblock the
    1856             :          agent does not know of are then stub keys.  This works also
    1857             :          for card stub keys.  The learn command or the card-status
    1858             :          command may be used to check with the agent whether a card
    1859             :          has been inserted and a stub key is in turn generated by the
    1860             :          agent.  */
    1861          33 :       if (ski->s2k.mode == 1001 || ski->s2k.mode == 1002)
    1862             :         {
    1863           0 :           stub_key_skipped = 1;
    1864           0 :           continue;
    1865             :         }
    1866             : 
    1867             :       /* Convert our internal secret key object into an S-expression.  */
    1868          33 :       nskey = pubkey_get_nskey (pk->pubkey_algo);
    1869          33 :       if (!nskey || nskey > PUBKEY_MAX_NSKEY)
    1870             :         {
    1871           0 :           err = gpg_error (GPG_ERR_BAD_SECKEY);
    1872           0 :           log_error ("internal error: %s\n", gpg_strerror (err));
    1873           0 :           goto leave;
    1874             :         }
    1875             : 
    1876          33 :       init_membuf (&mbuf, 50);
    1877          33 :       put_membuf_str (&mbuf, "(skey");
    1878          33 :       if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA
    1879          27 :           || pk->pubkey_algo == PUBKEY_ALGO_EDDSA
    1880          27 :           || pk->pubkey_algo == PUBKEY_ALGO_ECDH)
    1881          12 :         {
    1882             :           /* The ECC case.  */
    1883          12 :           char *curvestr = openpgp_oid_to_str (pk->pkey[0]);
    1884          12 :           if (!curvestr)
    1885           0 :             err = gpg_error_from_syserror ();
    1886             :           else
    1887             :             {
    1888          12 :               const char *curvename = openpgp_oid_to_curve (curvestr, 1);
    1889          12 :               gcry_sexp_release (curve);
    1890          12 :               err = gcry_sexp_build (&curve, NULL, "(curve %s)",
    1891             :                                      curvename?curvename:curvestr);
    1892          12 :               xfree (curvestr);
    1893          12 :               if (!err)
    1894             :                 {
    1895          12 :                   j = 0;
    1896             :                   /* Append the public key element Q.  */
    1897          12 :                   put_membuf_str (&mbuf, " _ %m");
    1898          12 :                   format_args[j++] = pk->pkey + 1;
    1899             : 
    1900             :                   /* Append the secret key element D.  For ECDH we
    1901             :                      skip PKEY[2] because this holds the KEK which is
    1902             :                      not needed by gpg-agent.  */
    1903          12 :                   i = pk->pubkey_algo == PUBKEY_ALGO_ECDH? 3 : 2;
    1904          12 :                   if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
    1905          12 :                     put_membuf_str (&mbuf, " e %m");
    1906             :                   else
    1907           0 :                     put_membuf_str (&mbuf, " _ %m");
    1908          12 :                   format_args[j++] = pk->pkey + i;
    1909             :                 }
    1910             :             }
    1911             :         }
    1912             :       else
    1913             :         {
    1914             :           /* Standard case for the old (non-ECC) algorithms.  */
    1915         126 :           for (i=j=0; i < nskey; i++)
    1916             :             {
    1917         105 :               if (!pk->pkey[i])
    1918          15 :                 continue; /* Protected keys only have NPKEY+1 elements.  */
    1919             : 
    1920          90 :               if (gcry_mpi_get_flag (pk->pkey[i], GCRYMPI_FLAG_USER1))
    1921          19 :                 put_membuf_str (&mbuf, " e %m");
    1922             :               else
    1923          71 :                 put_membuf_str (&mbuf, " _ %m");
    1924          90 :               format_args[j++] = pk->pkey + i;
    1925             :             }
    1926             :         }
    1927          33 :       put_membuf_str (&mbuf, ")");
    1928          33 :       put_membuf (&mbuf, "", 1);
    1929          33 :       if (err)
    1930           0 :         xfree (get_membuf (&mbuf, NULL));
    1931             :       else
    1932             :         {
    1933          33 :           char *format = get_membuf (&mbuf, NULL);
    1934          33 :           if (!format)
    1935           0 :             err = gpg_error_from_syserror ();
    1936             :           else
    1937          33 :             err = gcry_sexp_build_array (&skey, NULL, format, format_args);
    1938          33 :           xfree (format);
    1939             :         }
    1940          33 :       if (err)
    1941             :         {
    1942           0 :           log_error ("error building skey array: %s\n", gpg_strerror (err));
    1943           0 :           goto leave;
    1944             :         }
    1945             : 
    1946          33 :       if (ski->is_protected)
    1947             :         {
    1948             :           char countbuf[35];
    1949             : 
    1950             :           /* Note that the IVLEN may be zero if we are working on a
    1951             :              dummy key.  We can't express that in an S-expression and
    1952             :              thus we send dummy data for the IV.  */
    1953          31 :           snprintf (countbuf, sizeof countbuf, "%lu",
    1954          31 :                     (unsigned long)ski->s2k.count);
    1955         186 :           err = gcry_sexp_build
    1956             :             (&prot, NULL,
    1957             :              " (protection %s %s %b %d %s %b %s)\n",
    1958          31 :              ski->sha1chk? "sha1":"sum",
    1959          31 :              openpgp_cipher_algo_name (ski->algo),
    1960          62 :              ski->ivlen? (int)ski->ivlen:1,
    1961          31 :              ski->ivlen? ski->iv: (const unsigned char*)"X",
    1962             :              ski->s2k.mode,
    1963          31 :              openpgp_md_algo_name (ski->s2k.hash_algo),
    1964          31 :              (int)sizeof (ski->s2k.salt), ski->s2k.salt,
    1965             :              countbuf);
    1966             :         }
    1967             :       else
    1968           2 :         err = gcry_sexp_build (&prot, NULL, " (protection none)\n");
    1969             : 
    1970          33 :       tmpsexp = NULL;
    1971          33 :       xfree (transferkey);
    1972          33 :       transferkey = NULL;
    1973          33 :       if (!err)
    1974         132 :         err = gcry_sexp_build (&tmpsexp, NULL,
    1975             :                                "(openpgp-private-key\n"
    1976             :                                " (version %d)\n"
    1977             :                                " (algo %s)\n"
    1978             :                                " %S%S\n"
    1979             :                                " (csum %d)\n"
    1980             :                                " %S)\n",
    1981          33 :                                pk->version,
    1982          33 :                                openpgp_pk_algo_name (pk->pubkey_algo),
    1983             :                                curve, skey,
    1984          33 :                                (int)(unsigned long)ski->csum, prot);
    1985          33 :       gcry_sexp_release (skey);
    1986          33 :       gcry_sexp_release (prot);
    1987          33 :       if (!err)
    1988          33 :         err = make_canon_sexp_pad (tmpsexp, 1, &transferkey, &transferkeylen);
    1989          33 :       gcry_sexp_release (tmpsexp);
    1990          33 :       if (err)
    1991             :         {
    1992           0 :           log_error ("error building transfer key: %s\n", gpg_strerror (err));
    1993           0 :           goto leave;
    1994             :         }
    1995             : 
    1996             :       /* Wrap the key.  */
    1997          33 :       wrappedkeylen = transferkeylen + 8;
    1998          33 :       xfree (wrappedkey);
    1999          33 :       wrappedkey = xtrymalloc (wrappedkeylen);
    2000          33 :       if (!wrappedkey)
    2001           0 :         err = gpg_error_from_syserror ();
    2002             :       else
    2003          33 :         err = gcry_cipher_encrypt (cipherhd, wrappedkey, wrappedkeylen,
    2004             :                                    transferkey, transferkeylen);
    2005          33 :       if (err)
    2006           0 :         goto leave;
    2007          33 :       xfree (transferkey);
    2008          33 :       transferkey = NULL;
    2009             : 
    2010             :       /* Send the wrapped key to the agent.  */
    2011             :       {
    2012          33 :         char *desc = gpg_format_keydesc (pk, FORMAT_KEYDESC_IMPORT, 1);
    2013          33 :         err = agent_import_key (ctrl, desc, &cache_nonce,
    2014             :                                 wrappedkey, wrappedkeylen, batch, force);
    2015          33 :         xfree (desc);
    2016             :       }
    2017          33 :       if (!err)
    2018             :         {
    2019          31 :           if (opt.verbose)
    2020           0 :             log_info (_("key %s: secret key imported\n"),
    2021             :                       keystr_from_pk_with_sub (main_pk, pk));
    2022          31 :           if (stats)
    2023          31 :             stats->secret_imported++;
    2024             :         }
    2025           2 :       else if ( gpg_err_code (err) == GPG_ERR_EEXIST )
    2026             :         {
    2027           2 :           if (opt.verbose)
    2028           0 :             log_info (_("key %s: secret key already exists\n"),
    2029             :                       keystr_from_pk_with_sub (main_pk, pk));
    2030           2 :           err = 0;
    2031           2 :           if (stats)
    2032           2 :             stats->secret_dups++;
    2033             :         }
    2034             :       else
    2035             :         {
    2036           0 :           log_error (_("key %s: error sending to agent: %s\n"),
    2037             :                      keystr_from_pk_with_sub (main_pk, pk),
    2038             :                      gpg_strerror (err));
    2039           0 :           if (gpg_err_code (err) == GPG_ERR_CANCELED
    2040           0 :               || gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
    2041             :             break; /* Don't try the other subkeys.  */
    2042             :         }
    2043             :     }
    2044             : 
    2045          18 :   if (!err && stub_key_skipped)
    2046             :     /* We need to notify user how to migrate stub keys.  */
    2047           0 :     err = gpg_error (GPG_ERR_NOT_PROCESSED);
    2048             : 
    2049             :  leave:
    2050          18 :   gcry_sexp_release (curve);
    2051          18 :   xfree (cache_nonce);
    2052          18 :   xfree (wrappedkey);
    2053          18 :   xfree (transferkey);
    2054          18 :   gcry_cipher_close (cipherhd);
    2055          18 :   xfree (kek);
    2056          18 :   return err;
    2057             : }
    2058             : 
    2059             : 
    2060             : /* Walk a secret keyblock and produce a public keyblock out of it.
    2061             :    Returns a new node or NULL on error. */
    2062             : static kbnode_t
    2063          18 : sec_to_pub_keyblock (kbnode_t sec_keyblock)
    2064             : {
    2065          18 :   kbnode_t pub_keyblock = NULL;
    2066          18 :   kbnode_t ctx = NULL;
    2067             :   kbnode_t secnode, pubnode;
    2068             : 
    2069         119 :   while ((secnode = walk_kbnode (sec_keyblock, &ctx, 0)))
    2070             :     {
    2071          83 :       if (secnode->pkt->pkttype == PKT_SECRET_KEY
    2072          65 :           || secnode->pkt->pkttype == PKT_SECRET_SUBKEY)
    2073          33 :         {
    2074             :           /* Make a public key.  */
    2075             :           PACKET *pkt;
    2076             :           PKT_public_key *pk;
    2077             : 
    2078          33 :           pkt = xtrycalloc (1, sizeof *pkt);
    2079          33 :           pk = pkt? copy_public_key (NULL, secnode->pkt->pkt.public_key): NULL;
    2080          33 :           if (!pk)
    2081             :             {
    2082           0 :               xfree (pkt);
    2083           0 :               release_kbnode (pub_keyblock);
    2084           0 :               return NULL;
    2085             :             }
    2086          33 :           if (secnode->pkt->pkttype == PKT_SECRET_KEY)
    2087          18 :             pkt->pkttype = PKT_PUBLIC_KEY;
    2088             :           else
    2089          15 :             pkt->pkttype = PKT_PUBLIC_SUBKEY;
    2090          33 :           pkt->pkt.public_key = pk;
    2091             : 
    2092          33 :           pubnode = new_kbnode (pkt);
    2093             :         }
    2094             :       else
    2095             :         {
    2096          50 :           pubnode = clone_kbnode (secnode);
    2097             :         }
    2098             : 
    2099          83 :       if (!pub_keyblock)
    2100          18 :         pub_keyblock = pubnode;
    2101             :       else
    2102          65 :         add_kbnode (pub_keyblock, pubnode);
    2103             :     }
    2104             : 
    2105          18 :   return pub_keyblock;
    2106             : }
    2107             : 
    2108             : /****************
    2109             :  * Ditto for secret keys.  Handling is simpler than for public keys.
    2110             :  * We allow secret key importing only when allow is true, this is so
    2111             :  * that a secret key can not be imported accidentally and thereby tampering
    2112             :  * with the trust calculation.
    2113             :  */
    2114             : static int
    2115          18 : import_secret_one (ctrl_t ctrl, kbnode_t keyblock,
    2116             :                    struct import_stats_s *stats, int batch, unsigned int options,
    2117             :                    int for_migration,
    2118             :                    import_screener_t screener, void *screener_arg)
    2119             : {
    2120             :   PKT_public_key *pk;
    2121             :   struct seckey_info *ski;
    2122             :   kbnode_t node, uidnode;
    2123             :   u32 keyid[2];
    2124          18 :   int rc = 0;
    2125             :   int nr_prev;
    2126             :   kbnode_t pub_keyblock;
    2127             :   char pkstrbuf[PUBKEY_STRING_SIZE];
    2128             : 
    2129             :   /* Get the key and print some info about it */
    2130          18 :   node = find_kbnode (keyblock, PKT_SECRET_KEY);
    2131          18 :   if (!node)
    2132           0 :     BUG ();
    2133             : 
    2134          18 :   pk = node->pkt->pkt.public_key;
    2135             : 
    2136          18 :   keyid_from_pk (pk, keyid);
    2137          18 :   uidnode = find_next_kbnode (keyblock, PKT_USER_ID);
    2138             : 
    2139          18 :   if (screener && screener (keyblock, screener_arg))
    2140             :     {
    2141           0 :       log_error (_("secret key %s: %s\n"), keystr_from_pk (pk),
    2142             :                  _("rejected by import screener"));
    2143           0 :       return 0;
    2144             :   }
    2145             : 
    2146          18 :   if (opt.verbose && !for_migration)
    2147             :     {
    2148           0 :       log_info ("sec  %s/%s %s   ",
    2149             :                 pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
    2150             :                 keystr_from_pk (pk), datestr_from_pk (pk));
    2151           0 :       if (uidnode)
    2152           0 :         print_utf8_buffer (log_get_stream (), uidnode->pkt->pkt.user_id->name,
    2153           0 :                            uidnode->pkt->pkt.user_id->len);
    2154           0 :       log_printf ("\n");
    2155             :     }
    2156          18 :   stats->secret_read++;
    2157             : 
    2158          18 :   if ((options & IMPORT_NO_SECKEY))
    2159             :     {
    2160           0 :       if (!for_migration)
    2161           0 :         log_error (_("importing secret keys not allowed\n"));
    2162           0 :       return 0;
    2163             :     }
    2164             : 
    2165          18 :   if (!uidnode)
    2166             :     {
    2167           0 :       if (!for_migration)
    2168           0 :         log_error( _("key %s: no user ID\n"), keystr_from_pk (pk));
    2169           0 :       return 0;
    2170             :     }
    2171             : 
    2172          18 :   ski = pk->seckey_info;
    2173          18 :   if (!ski)
    2174             :     {
    2175             :       /* Actually an internal error.  */
    2176           0 :       log_error ("key %s: secret key info missing\n", keystr_from_pk (pk));
    2177           0 :       return 0;
    2178             :     }
    2179             : 
    2180             :   /* A quick check to not import keys with an invalid protection
    2181             :      cipher algorithm (only checks the primary key, though).  */
    2182          18 :   if (ski->algo > 110)
    2183             :     {
    2184           0 :       if (!for_migration)
    2185           0 :         log_error (_("key %s: secret key with invalid cipher %d"
    2186           0 :                      " - skipped\n"), keystr_from_pk (pk), ski->algo);
    2187           0 :       return 0;
    2188             :     }
    2189             : 
    2190             : #ifdef ENABLE_SELINUX_HACKS
    2191             :   if (1)
    2192             :     {
    2193             :       /* We don't allow importing secret keys because that may be used
    2194             :          to put a secret key into the keyring and the user might later
    2195             :          be tricked into signing stuff with that key.  */
    2196             :       log_error (_("importing secret keys not allowed\n"));
    2197             :       return 0;
    2198             :     }
    2199             : #endif
    2200             : 
    2201          18 :   clear_kbnode_flags (keyblock);
    2202             : 
    2203          18 :   nr_prev = stats->skipped_new_keys;
    2204             : 
    2205             :   /* Make a public key out of the key. */
    2206          18 :   pub_keyblock = sec_to_pub_keyblock (keyblock);
    2207          18 :   if (!pub_keyblock)
    2208           0 :     log_error ("key %s: failed to create public key from secret key\n",
    2209             :                    keystr_from_pk (pk));
    2210             :   else
    2211             :     {
    2212             :       /* Note that this outputs an IMPORT_OK status message for the
    2213             :          public key block, and below we will output another one for
    2214             :          the secret keys.  FIXME?  */
    2215          18 :       import_one (ctrl, pub_keyblock, stats,
    2216             :                   NULL, NULL, options, 1, for_migration,
    2217             :                   screener, screener_arg);
    2218             : 
    2219             :       /* Fixme: We should check for an invalid keyblock and
    2220             :          cancel the secret key import in this case.  */
    2221          18 :       release_kbnode (pub_keyblock);
    2222             : 
    2223             :       /* At least we cancel the secret key import when the public key
    2224             :          import was skipped due to MERGE_ONLY option and a new
    2225             :          key.  */
    2226          18 :       if (stats->skipped_new_keys <= nr_prev)
    2227             :         {
    2228             :           /* Read the keyblock again to get the effects of a merge.  */
    2229             :           /* Fixme: we should do this based on the fingerprint or
    2230             :              even better let import_one return the merged
    2231             :              keyblock.  */
    2232          18 :           node = get_pubkeyblock (keyid);
    2233          18 :           if (!node)
    2234           0 :             log_error ("key %s: failed to re-lookup public key\n",
    2235             :                        keystr_from_pk (pk));
    2236             :           else
    2237             :             {
    2238             :               gpg_error_t err;
    2239             : 
    2240             :               /* transfer_secret_keys collects subkey stats.  */
    2241          18 :               struct import_stats_s subkey_stats = {0};
    2242             : 
    2243          18 :               err = transfer_secret_keys (ctrl, &subkey_stats, keyblock,
    2244             :                                           batch, 0);
    2245          18 :               if (gpg_err_code (err) == GPG_ERR_NOT_PROCESSED)
    2246             :                 {
    2247             :                   /* TRANSLATORS: For smartcard, each private key on
    2248             :                      host has a reference (stub) to a smartcard and
    2249             :                      actual private key data is stored on the card.  A
    2250             :                      single smartcard can have up to three private key
    2251             :                      data.  Importing private key stub is always
    2252             :                      skipped in 2.1, and it returns
    2253             :                      GPG_ERR_NOT_PROCESSED.  Instead, user should be
    2254             :                      suggested to run 'gpg --card-status', then,
    2255             :                      references to a card will be automatically
    2256             :                      created again.  */
    2257           0 :                   log_info (_("To migrate '%s', with each smartcard, "
    2258             :                               "run: %s\n"), "secring.gpg", "gpg --card-status");
    2259           0 :                   err = 0;
    2260             :                 }
    2261          18 :               if (!err)
    2262             :                 {
    2263          18 :                   int status = 16;
    2264          18 :                   if (!opt.quiet)
    2265          18 :                     log_info (_("key %s: secret key imported\n"),
    2266             :                               keystr_from_pk (pk));
    2267          18 :                   if (subkey_stats.secret_imported)
    2268             :                     {
    2269          17 :                       status |= 1;
    2270          17 :                       stats->secret_imported += 1;
    2271             :                     }
    2272          18 :                   if (subkey_stats.secret_dups)
    2273           1 :                     stats->secret_dups += 1;
    2274             : 
    2275          18 :                   if (is_status_enabled ())
    2276           1 :                     print_import_ok (pk, status);
    2277          18 :                   check_prefs (ctrl, node);
    2278             :                 }
    2279          18 :               release_kbnode (node);
    2280             :             }
    2281             :         }
    2282             :     }
    2283             : 
    2284          18 :   return rc;
    2285             : }
    2286             : 
    2287             : 
    2288             : /****************
    2289             :  * Import a revocation certificate; this is a single signature packet.
    2290             :  */
    2291             : static int
    2292           0 : import_revoke_cert (ctrl_t ctrl, kbnode_t node, struct import_stats_s *stats)
    2293             : {
    2294           0 :   PKT_public_key *pk = NULL;
    2295             :   kbnode_t onode;
    2296           0 :   kbnode_t keyblock = NULL;
    2297           0 :   KEYDB_HANDLE hd = NULL;
    2298             :   u32 keyid[2];
    2299           0 :   int rc = 0;
    2300             : 
    2301           0 :   log_assert (!node->next );
    2302           0 :   log_assert (node->pkt->pkttype == PKT_SIGNATURE );
    2303           0 :   log_assert (node->pkt->pkt.signature->sig_class == 0x20 );
    2304             : 
    2305           0 :   keyid[0] = node->pkt->pkt.signature->keyid[0];
    2306           0 :   keyid[1] = node->pkt->pkt.signature->keyid[1];
    2307             : 
    2308           0 :   pk = xmalloc_clear( sizeof *pk );
    2309           0 :   rc = get_pubkey( pk, keyid );
    2310           0 :   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY )
    2311             :     {
    2312           0 :       log_error(_("key %s: no public key -"
    2313             :                   " can't apply revocation certificate\n"), keystr(keyid));
    2314           0 :       rc = 0;
    2315           0 :       goto leave;
    2316             :     }
    2317           0 :   else if (rc )
    2318             :     {
    2319           0 :       log_error(_("key %s: public key not found: %s\n"),
    2320             :                 keystr(keyid), gpg_strerror (rc));
    2321           0 :       goto leave;
    2322             :     }
    2323             : 
    2324             :   /* Read the original keyblock. */
    2325           0 :   hd = keydb_new ();
    2326           0 :   if (!hd)
    2327             :     {
    2328           0 :       rc = gpg_error_from_syserror ();
    2329           0 :       goto leave;
    2330             :     }
    2331             : 
    2332             :   {
    2333             :     byte afp[MAX_FINGERPRINT_LEN];
    2334             :     size_t an;
    2335             : 
    2336           0 :     fingerprint_from_pk (pk, afp, &an);
    2337           0 :     while (an < MAX_FINGERPRINT_LEN)
    2338           0 :       afp[an++] = 0;
    2339           0 :     rc = keydb_search_fpr (hd, afp);
    2340             :   }
    2341           0 :   if (rc)
    2342             :     {
    2343           0 :       log_error (_("key %s: can't locate original keyblock: %s\n"),
    2344             :                  keystr(keyid), gpg_strerror (rc));
    2345           0 :       goto leave;
    2346             :     }
    2347           0 :   rc = keydb_get_keyblock (hd, &keyblock );
    2348           0 :   if (rc)
    2349             :     {
    2350           0 :       log_error (_("key %s: can't read original keyblock: %s\n"),
    2351             :                  keystr(keyid), gpg_strerror (rc));
    2352           0 :       goto leave;
    2353             :     }
    2354             : 
    2355             :   /* it is okay, that node is not in keyblock because
    2356             :    * check_key_signature works fine for sig_class 0x20 in this
    2357             :    * special case. */
    2358           0 :   rc = check_key_signature( keyblock, node, NULL);
    2359           0 :   if (rc )
    2360             :     {
    2361           0 :       log_error( _("key %s: invalid revocation certificate"
    2362             :                    ": %s - rejected\n"), keystr(keyid), gpg_strerror (rc));
    2363           0 :       goto leave;
    2364             :     }
    2365             : 
    2366             :   /* check whether we already have this */
    2367           0 :   for(onode=keyblock->next; onode; onode=onode->next ) {
    2368           0 :     if (onode->pkt->pkttype == PKT_USER_ID )
    2369           0 :       break;
    2370           0 :     else if (onode->pkt->pkttype == PKT_SIGNATURE
    2371           0 :              && !cmp_signatures(node->pkt->pkt.signature,
    2372           0 :                                 onode->pkt->pkt.signature))
    2373             :       {
    2374           0 :         rc = 0;
    2375           0 :         goto leave; /* yes, we already know about it */
    2376             :       }
    2377             :   }
    2378             : 
    2379             :   /* insert it */
    2380           0 :   insert_kbnode( keyblock, clone_kbnode(node), 0 );
    2381             : 
    2382             :   /* and write the keyblock back */
    2383           0 :   rc = keydb_update_keyblock (ctrl, hd, keyblock );
    2384           0 :   if (rc)
    2385           0 :     log_error (_("error writing keyring '%s': %s\n"),
    2386             :                keydb_get_resource_name (hd), gpg_strerror (rc) );
    2387           0 :   keydb_release (hd);
    2388           0 :   hd = NULL;
    2389             : 
    2390             :   /* we are ready */
    2391           0 :   if (!opt.quiet )
    2392             :     {
    2393           0 :       char *p=get_user_id_native (keyid);
    2394           0 :       log_info( _("key %s: \"%s\" revocation certificate imported\n"),
    2395             :                 keystr(keyid),p);
    2396           0 :       xfree(p);
    2397             :     }
    2398           0 :   stats->n_revoc++;
    2399             : 
    2400             :   /* If the key we just revoked was ultimately trusted, remove its
    2401             :      ultimate trust.  This doesn't stop the user from putting the
    2402             :      ultimate trust back, but is a reasonable solution for now. */
    2403           0 :   if(get_ownertrust(pk)==TRUST_ULTIMATE)
    2404           0 :     clear_ownertrusts(pk);
    2405             : 
    2406           0 :   revalidation_mark ();
    2407             : 
    2408             :  leave:
    2409           0 :   keydb_release (hd);
    2410           0 :   release_kbnode( keyblock );
    2411           0 :   free_public_key( pk );
    2412           0 :   return rc;
    2413             : }
    2414             : 
    2415             : 
    2416             : /* Loop over the keyblock and check all self signatures.  On return
    2417             :  * the following bis in the node flags are set:
    2418             :  *
    2419             :  * - NODE_GOOD_SELFSIG  :: User ID or subkey has a self-signature
    2420             :  * - NODE_BAD_SELFSIG   :: Used ID or subkey has an invalid self-signature
    2421             :  * - NODE_DELETION_MARK :: This node shall be deleted
    2422             :  *
    2423             :  * NON_SELF is set to true if there are any sigs other than self-sigs
    2424             :  * in this keyblock.
    2425             :  *
    2426             :  * Returns 0 on success or -1 (but not an error code) if the keyblock
    2427             :  * is invalid.
    2428             :  */
    2429             : static int
    2430         202 : chk_self_sigs (kbnode_t keyblock, u32 *keyid, int *non_self )
    2431             : {
    2432         202 :   kbnode_t n, knode = NULL;
    2433             :   PKT_signature *sig;
    2434             :   int rc;
    2435         202 :   u32 bsdate=0, rsdate=0;
    2436         202 :   kbnode_t bsnode = NULL, rsnode = NULL;
    2437             : 
    2438        1396 :   for (n=keyblock; (n = find_next_kbnode (n, 0)); )
    2439             :     {
    2440         992 :       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY)
    2441             :         {
    2442         194 :           knode = n;
    2443         194 :           bsdate = 0;
    2444         194 :           rsdate = 0;
    2445         194 :           bsnode = NULL;
    2446         194 :           rsnode = NULL;
    2447         194 :           continue;
    2448             :         }
    2449             : 
    2450         798 :       if ( n->pkt->pkttype != PKT_SIGNATURE )
    2451         226 :         continue;
    2452             : 
    2453         572 :       sig = n->pkt->pkt.signature;
    2454         572 :       if ( keyid[0] != sig->keyid[0] || keyid[1] != sig->keyid[1] )
    2455             :         {
    2456         146 :           *non_self = 1;
    2457         146 :           continue;
    2458             :         }
    2459             : 
    2460             :       /* This just caches the sigs for later use.  That way we
    2461             :          import a fully-cached key which speeds things up. */
    2462         426 :       if (!opt.no_sig_cache)
    2463         426 :         check_key_signature (keyblock, n, NULL);
    2464             : 
    2465         426 :       if ( IS_UID_SIG(sig) || IS_UID_REV(sig) )
    2466         233 :         {
    2467         233 :           kbnode_t unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
    2468         233 :           if ( !unode )
    2469             :             {
    2470           0 :               log_error( _("key %s: no user ID for signature\n"),
    2471             :                          keystr(keyid));
    2472           0 :               return -1;  /* The complete keyblock is invalid.  */
    2473             :             }
    2474             : 
    2475             :           /* If it hasn't been marked valid yet, keep trying.  */
    2476         233 :           if (!(unode->flag & NODE_GOOD_SELFSIG))
    2477             :             {
    2478         222 :               rc = check_key_signature (keyblock, n, NULL);
    2479         222 :               if ( rc )
    2480             :                 {
    2481           0 :                   if ( opt.verbose )
    2482             :                     {
    2483           0 :                       char *p = utf8_to_native
    2484           0 :                         (unode->pkt->pkt.user_id->name,
    2485           0 :                          strlen (unode->pkt->pkt.user_id->name),0);
    2486           0 :                       log_info (gpg_err_code(rc) == GPG_ERR_PUBKEY_ALGO ?
    2487             :                                 _("key %s: unsupported public key "
    2488             :                                   "algorithm on user ID \"%s\"\n"):
    2489             :                                 _("key %s: invalid self-signature "
    2490             :                                   "on user ID \"%s\"\n"),
    2491             :                                 keystr (keyid),p);
    2492           0 :                       xfree (p);
    2493             :                     }
    2494             :                 }
    2495             :               else
    2496         222 :                 unode->flag |= NODE_GOOD_SELFSIG;
    2497             :             }
    2498             :         }
    2499         193 :       else if (IS_KEY_SIG (sig))
    2500             :         {
    2501           2 :           rc = check_key_signature (keyblock, n, NULL);
    2502           2 :           if ( rc )
    2503             :             {
    2504           1 :               if (opt.verbose)
    2505           0 :                 log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
    2506             :                           _("key %s: unsupported public key algorithm\n"):
    2507             :                           _("key %s: invalid direct key signature\n"),
    2508             :                           keystr (keyid));
    2509           1 :               n->flag |= NODE_DELETION_MARK;
    2510             :             }
    2511             :         }
    2512         191 :       else if ( IS_SUBKEY_SIG (sig) )
    2513             :         {
    2514             :           /* Note that this works based solely on the timestamps like
    2515             :              the rest of gpg.  If the standard gets revocation
    2516             :              targets, this may need to be revised.  */
    2517             : 
    2518         191 :           if ( !knode )
    2519             :             {
    2520           0 :               if (opt.verbose)
    2521           0 :                 log_info (_("key %s: no subkey for key binding\n"),
    2522             :                           keystr (keyid));
    2523           0 :               n->flag |= NODE_DELETION_MARK;
    2524             :             }
    2525             :           else
    2526             :             {
    2527         191 :               rc = check_key_signature (keyblock, n, NULL);
    2528         191 :               if ( rc )
    2529             :                 {
    2530           0 :                   if (opt.verbose)
    2531           0 :                     log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
    2532             :                               _("key %s: unsupported public key"
    2533             :                                 " algorithm\n"):
    2534             :                               _("key %s: invalid subkey binding\n"),
    2535             :                               keystr (keyid));
    2536           0 :                   n->flag |= NODE_DELETION_MARK;
    2537             :                 }
    2538             :               else
    2539             :                 {
    2540             :                   /* It's valid, so is it newer? */
    2541         191 :                   if (sig->timestamp >= bsdate)
    2542             :                     {
    2543         191 :                       knode->flag |= NODE_GOOD_SELFSIG; /* Subkey is valid.  */
    2544         191 :                       if (bsnode)
    2545             :                         {
    2546             :                           /* Delete the last binding sig since this
    2547             :                              one is newer */
    2548           1 :                           bsnode->flag |= NODE_DELETION_MARK;
    2549           1 :                           if (opt.verbose)
    2550           0 :                             log_info (_("key %s: removed multiple subkey"
    2551             :                                         " binding\n"),keystr(keyid));
    2552             :                         }
    2553             : 
    2554         191 :                       bsnode = n;
    2555         191 :                       bsdate = sig->timestamp;
    2556             :                     }
    2557             :                   else
    2558           0 :                     n->flag |= NODE_DELETION_MARK; /* older */
    2559             :                 }
    2560             :             }
    2561             :         }
    2562           0 :       else if ( IS_SUBKEY_REV (sig) )
    2563             :         {
    2564             :           /* We don't actually mark the subkey as revoked right now,
    2565             :              so just check that the revocation sig is the most recent
    2566             :              valid one.  Note that we don't care if the binding sig is
    2567             :              newer than the revocation sig.  See the comment in
    2568             :              getkey.c:merge_selfsigs_subkey for more.  */
    2569           0 :           if ( !knode )
    2570             :             {
    2571           0 :               if (opt.verbose)
    2572           0 :                 log_info (_("key %s: no subkey for key revocation\n"),
    2573             :                           keystr(keyid));
    2574           0 :               n->flag |= NODE_DELETION_MARK;
    2575             :             }
    2576             :           else
    2577             :             {
    2578           0 :               rc = check_key_signature (keyblock, n, NULL);
    2579           0 :               if ( rc )
    2580             :                 {
    2581           0 :                   if(opt.verbose)
    2582           0 :                     log_info (gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
    2583             :                               _("key %s: unsupported public"
    2584             :                                 " key algorithm\n"):
    2585             :                               _("key %s: invalid subkey revocation\n"),
    2586             :                               keystr(keyid));
    2587           0 :                   n->flag |= NODE_DELETION_MARK;
    2588             :                 }
    2589             :               else
    2590             :                 {
    2591             :                   /* It's valid, so is it newer? */
    2592           0 :                   if (sig->timestamp >= rsdate)
    2593             :                     {
    2594           0 :                       if (rsnode)
    2595             :                         {
    2596             :                           /* Delete the last revocation sig since
    2597             :                              this one is newer.  */
    2598           0 :                           rsnode->flag |= NODE_DELETION_MARK;
    2599           0 :                           if (opt.verbose)
    2600           0 :                             log_info (_("key %s: removed multiple subkey"
    2601             :                                         " revocation\n"),keystr(keyid));
    2602             :                         }
    2603             : 
    2604           0 :                       rsnode = n;
    2605           0 :                       rsdate = sig->timestamp;
    2606             :                     }
    2607             :                   else
    2608           0 :                     n->flag |= NODE_DELETION_MARK; /* older */
    2609             :                 }
    2610             :             }
    2611             :         }
    2612             :     }
    2613             : 
    2614         202 :   return 0;
    2615             : }
    2616             : 
    2617             : 
    2618             : /* Delete all parts which are invalid and those signatures whose
    2619             :  * public key algorithm is not available in this implemenation; but
    2620             :  * consider RSA as valid, because parse/build_packets knows about it.
    2621             :  *
    2622             :  * Returns: True if at least one valid user-id is left over.
    2623             :  */
    2624             : static int
    2625         202 : delete_inv_parts (kbnode_t keyblock, u32 *keyid, unsigned int options)
    2626             : {
    2627             :   kbnode_t node;
    2628         202 :   int nvalid=0, uid_seen=0, subkey_seen=0;
    2629             : 
    2630        1194 :   for (node=keyblock->next; node; node = node->next )
    2631             :     {
    2632         992 :       if (node->pkt->pkttype == PKT_USER_ID)
    2633             :         {
    2634         226 :           uid_seen = 1;
    2635         226 :           if ((node->flag & NODE_BAD_SELFSIG)
    2636         226 :               || !(node->flag & NODE_GOOD_SELFSIG))
    2637             :             {
    2638           0 :               if (opt.verbose )
    2639             :                 {
    2640           0 :                   char *p=utf8_to_native(node->pkt->pkt.user_id->name,
    2641           0 :                                          node->pkt->pkt.user_id->len,0);
    2642           0 :                   log_info( _("key %s: skipped user ID \"%s\"\n"),
    2643             :                             keystr(keyid),p);
    2644           0 :                   xfree(p);
    2645             :                 }
    2646           0 :               delete_kbnode( node ); /* the user-id */
    2647             :               /* and all following packets up to the next user-id */
    2648           0 :               while (node->next
    2649           0 :                      && node->next->pkt->pkttype != PKT_USER_ID
    2650           0 :                      && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
    2651           0 :                      && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
    2652           0 :                 delete_kbnode( node->next );
    2653           0 :                 node = node->next;
    2654             :               }
    2655             :             }
    2656             :           else
    2657         226 :             nvalid++;
    2658             :         }
    2659         766 :       else if (   node->pkt->pkttype == PKT_PUBLIC_SUBKEY
    2660         572 :                || node->pkt->pkttype == PKT_SECRET_SUBKEY )
    2661             :         {
    2662         392 :           if ((node->flag & NODE_BAD_SELFSIG)
    2663         194 :               || !(node->flag & NODE_GOOD_SELFSIG))
    2664             :             {
    2665           4 :               if (opt.verbose )
    2666           0 :                 log_info( _("key %s: skipped subkey\n"),keystr(keyid));
    2667             : 
    2668           4 :               delete_kbnode( node ); /* the subkey */
    2669             :               /* and all following signature packets */
    2670           8 :               while (node->next
    2671           0 :                      && node->next->pkt->pkttype == PKT_SIGNATURE ) {
    2672           0 :                 delete_kbnode( node->next );
    2673           0 :                 node = node->next;
    2674             :               }
    2675             :             }
    2676             :           else
    2677         190 :             subkey_seen = 1;
    2678             :         }
    2679         572 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    2680         572 :                && openpgp_pk_test_algo (node->pkt->pkt.signature->pubkey_algo)
    2681           0 :                && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
    2682             :         {
    2683           0 :           delete_kbnode( node ); /* build_packet() can't handle this */
    2684             :         }
    2685         572 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    2686         572 :                && !node->pkt->pkt.signature->flags.exportable
    2687           0 :                && !(options&IMPORT_LOCAL_SIGS)
    2688           0 :                && !have_secret_key_with_kid (node->pkt->pkt.signature->keyid))
    2689             :         {
    2690             :           /* here we violate the rfc a bit by still allowing
    2691             :            * to import non-exportable signature when we have the
    2692             :            * the secret key used to create this signature - it
    2693             :            * seems that this makes sense */
    2694           0 :           if(opt.verbose)
    2695           0 :             log_info( _("key %s: non exportable signature"
    2696             :                         " (class 0x%02X) - skipped\n"),
    2697           0 :                       keystr(keyid), node->pkt->pkt.signature->sig_class );
    2698           0 :           delete_kbnode( node );
    2699             :         }
    2700         572 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    2701         572 :                && node->pkt->pkt.signature->sig_class == 0x20)
    2702             :         {
    2703           0 :           if (uid_seen )
    2704             :             {
    2705           0 :               if(opt.verbose)
    2706           0 :                 log_info( _("key %s: revocation certificate"
    2707             :                             " at wrong place - skipped\n"),keystr(keyid));
    2708           0 :               delete_kbnode( node );
    2709             :             }
    2710             :           else
    2711             :             {
    2712             :               /* If the revocation cert is from a different key than
    2713             :                  the one we're working on don't check it - it's
    2714             :                  probably from a revocation key and won't be
    2715             :                  verifiable with this key anyway. */
    2716             : 
    2717           0 :               if(node->pkt->pkt.signature->keyid[0]==keyid[0]
    2718           0 :                  && node->pkt->pkt.signature->keyid[1]==keyid[1])
    2719             :                 {
    2720           0 :                   int rc = check_key_signature( keyblock, node, NULL);
    2721           0 :                   if (rc )
    2722             :                     {
    2723           0 :                       if(opt.verbose)
    2724           0 :                         log_info( _("key %s: invalid revocation"
    2725             :                                     " certificate: %s - skipped\n"),
    2726             :                                   keystr(keyid), gpg_strerror (rc));
    2727           0 :                       delete_kbnode( node );
    2728             :                     }
    2729             :                 }
    2730             :             }
    2731             :         }
    2732         572 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    2733         572 :                && (node->pkt->pkt.signature->sig_class == 0x18
    2734         381 :                    || node->pkt->pkt.signature->sig_class == 0x28)
    2735         191 :                && !subkey_seen )
    2736             :         {
    2737           0 :           if(opt.verbose)
    2738           0 :             log_info( _("key %s: subkey signature"
    2739             :                         " in wrong place - skipped\n"), keystr(keyid));
    2740           0 :           delete_kbnode( node );
    2741             :         }
    2742         572 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    2743         572 :                && !IS_CERT(node->pkt->pkt.signature))
    2744             :         {
    2745           0 :           if(opt.verbose)
    2746           0 :             log_info(_("key %s: unexpected signature class (0x%02X) -"
    2747             :                        " skipped\n"),keystr(keyid),
    2748           0 :                      node->pkt->pkt.signature->sig_class);
    2749           0 :           delete_kbnode(node);
    2750             :           }
    2751         572 :       else if ((node->flag & NODE_DELETION_MARK))
    2752           2 :         delete_kbnode( node );
    2753             :     }
    2754             : 
    2755             :   /* note: because keyblock is the public key, it is never marked
    2756             :    * for deletion and so keyblock cannot change */
    2757         202 :   commit_kbnode( &keyblock );
    2758         202 :   return nvalid;
    2759             : }
    2760             : 
    2761             : /* This function returns true if any UID is left in the keyring.  */
    2762             : static int
    2763           0 : any_uid_left (kbnode_t keyblock)
    2764             : {
    2765             :   kbnode_t node;
    2766             : 
    2767           0 :   for (node=keyblock->next; node; node = node->next)
    2768           0 :     if (node->pkt->pkttype == PKT_USER_ID)
    2769           0 :       return 1;
    2770           0 :   return 0;
    2771             : }
    2772             : 
    2773             : 
    2774             : 
    2775             : /****************
    2776             :  * It may happen that the imported keyblock has duplicated user IDs.
    2777             :  * We check this here and collapse those user IDs together with their
    2778             :  * sigs into one.
    2779             :  * Returns: True if the keyblock has changed.
    2780             :  */
    2781             : int
    2782         204 : collapse_uids( kbnode_t *keyblock )
    2783             : {
    2784             :   kbnode_t uid1;
    2785         204 :   int any=0;
    2786             : 
    2787        1468 :   for(uid1=*keyblock;uid1;uid1=uid1->next)
    2788             :     {
    2789             :       kbnode_t uid2;
    2790             : 
    2791        1264 :       if(is_deleted_kbnode(uid1))
    2792          58 :         continue;
    2793             : 
    2794        1206 :       if(uid1->pkt->pkttype!=PKT_USER_ID)
    2795         977 :         continue;
    2796             : 
    2797        1493 :       for(uid2=uid1->next;uid2;uid2=uid2->next)
    2798             :         {
    2799        1264 :           if(is_deleted_kbnode(uid2))
    2800          54 :             continue;
    2801             : 
    2802        1210 :           if(uid2->pkt->pkttype!=PKT_USER_ID)
    2803        1164 :             continue;
    2804             : 
    2805          46 :           if(cmp_user_ids(uid1->pkt->pkt.user_id,
    2806          46 :                           uid2->pkt->pkt.user_id)==0)
    2807             :             {
    2808             :               /* We have a duplicated uid */
    2809             :               kbnode_t sig1,last;
    2810             : 
    2811           4 :               any=1;
    2812             : 
    2813             :               /* Now take uid2's signatures, and attach them to
    2814             :                  uid1 */
    2815          56 :               for(last=uid2;last->next;last=last->next)
    2816             :                 {
    2817          56 :                   if(is_deleted_kbnode(last))
    2818           0 :                     continue;
    2819             : 
    2820          56 :                   if(last->next->pkt->pkttype==PKT_USER_ID
    2821          54 :                      || last->next->pkt->pkttype==PKT_PUBLIC_SUBKEY
    2822          52 :                      || last->next->pkt->pkttype==PKT_SECRET_SUBKEY)
    2823             :                     break;
    2824             :                 }
    2825             : 
    2826             :               /* Snip out uid2 */
    2827           4 :               (find_prev_kbnode(*keyblock,uid2,0))->next=last->next;
    2828             : 
    2829             :               /* Now put uid2 in place as part of uid1 */
    2830           4 :               last->next=uid1->next;
    2831           4 :               uid1->next=uid2;
    2832           4 :               delete_kbnode(uid2);
    2833             : 
    2834             :               /* Now dedupe uid1 */
    2835         165 :               for(sig1=uid1->next;sig1;sig1=sig1->next)
    2836             :                 {
    2837             :                   kbnode_t sig2;
    2838             : 
    2839         165 :                   if(is_deleted_kbnode(sig1))
    2840          58 :                     continue;
    2841             : 
    2842         107 :                   if(sig1->pkt->pkttype==PKT_USER_ID
    2843         104 :                      || sig1->pkt->pkttype==PKT_PUBLIC_SUBKEY
    2844         103 :                      || sig1->pkt->pkttype==PKT_SECRET_SUBKEY)
    2845             :                     break;
    2846             : 
    2847         103 :                   if(sig1->pkt->pkttype!=PKT_SIGNATURE)
    2848           0 :                     continue;
    2849             : 
    2850        4161 :                   for(sig2=sig1->next,last=sig1;sig2;last=sig2,sig2=sig2->next)
    2851             :                     {
    2852        4161 :                       if(is_deleted_kbnode(sig2))
    2853        1454 :                         continue;
    2854             : 
    2855        2707 :                       if(sig2->pkt->pkttype==PKT_USER_ID
    2856        2648 :                          || sig2->pkt->pkttype==PKT_PUBLIC_SUBKEY
    2857        2604 :                          || sig2->pkt->pkttype==PKT_SECRET_SUBKEY)
    2858             :                         break;
    2859             : 
    2860        2604 :                       if(sig2->pkt->pkttype!=PKT_SIGNATURE)
    2861           0 :                         continue;
    2862             : 
    2863        2604 :                       if(cmp_signatures(sig1->pkt->pkt.signature,
    2864        2604 :                                         sig2->pkt->pkt.signature)==0)
    2865             :                         {
    2866             :                           /* We have a match, so delete the second
    2867             :                              signature */
    2868          54 :                           delete_kbnode(sig2);
    2869          54 :                           sig2=last;
    2870             :                         }
    2871             :                     }
    2872             :                 }
    2873             :             }
    2874             :         }
    2875             :     }
    2876             : 
    2877         204 :   commit_kbnode(keyblock);
    2878             : 
    2879         204 :   if(any && !opt.quiet)
    2880             :     {
    2881           2 :       const char *key="???";
    2882             : 
    2883           2 :       if ((uid1 = find_kbnode (*keyblock, PKT_PUBLIC_KEY)) )
    2884           2 :         key = keystr_from_pk (uid1->pkt->pkt.public_key);
    2885           0 :       else if ((uid1 = find_kbnode( *keyblock, PKT_SECRET_KEY)) )
    2886           0 :         key = keystr_from_pk (uid1->pkt->pkt.public_key);
    2887             : 
    2888           2 :       log_info (_("key %s: duplicated user ID detected - merged\n"), key);
    2889             :     }
    2890             : 
    2891         204 :   return any;
    2892             : }
    2893             : 
    2894             : 
    2895             : /* Check for a 0x20 revocation from a revocation key that is not
    2896             :    present.  This may be called without the benefit of merge_xxxx so
    2897             :    you can't rely on pk->revkey and friends. */
    2898             : static void
    2899         158 : revocation_present (ctrl_t ctrl, kbnode_t keyblock)
    2900             : {
    2901             :   kbnode_t onode, inode;
    2902         158 :   PKT_public_key *pk = keyblock->pkt->pkt.public_key;
    2903             : 
    2904         159 :   for(onode=keyblock->next;onode;onode=onode->next)
    2905             :     {
    2906             :       /* If we reach user IDs, we're done. */
    2907         159 :       if(onode->pkt->pkttype==PKT_USER_ID)
    2908         158 :         break;
    2909             : 
    2910           2 :       if(onode->pkt->pkttype==PKT_SIGNATURE &&
    2911           2 :          onode->pkt->pkt.signature->sig_class==0x1F &&
    2912           1 :          onode->pkt->pkt.signature->revkey)
    2913             :         {
    2914             :           int idx;
    2915           1 :           PKT_signature *sig=onode->pkt->pkt.signature;
    2916             : 
    2917           2 :           for(idx=0;idx<sig->numrevkeys;idx++)
    2918             :             {
    2919             :               u32 keyid[2];
    2920             : 
    2921           1 :               keyid_from_fingerprint(sig->revkey[idx].fpr,
    2922             :                                      MAX_FINGERPRINT_LEN,keyid);
    2923             : 
    2924           2 :               for(inode=keyblock->next;inode;inode=inode->next)
    2925             :                 {
    2926             :                   /* If we reach user IDs, we're done. */
    2927           2 :                   if(inode->pkt->pkttype==PKT_USER_ID)
    2928           1 :                     break;
    2929             : 
    2930           2 :                   if(inode->pkt->pkttype==PKT_SIGNATURE &&
    2931           1 :                      inode->pkt->pkt.signature->sig_class==0x20 &&
    2932           0 :                      inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
    2933           0 :                      inode->pkt->pkt.signature->keyid[1]==keyid[1])
    2934             :                     {
    2935             :                       /* Okay, we have a revocation key, and a
    2936             :                          revocation issued by it.  Do we have the key
    2937             :                          itself? */
    2938             :                       int rc;
    2939             : 
    2940           0 :                       rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx].fpr,
    2941             :                                                    MAX_FINGERPRINT_LEN);
    2942           0 :                       if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
    2943           0 :                           || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
    2944             :                         {
    2945           0 :                           char *tempkeystr=xstrdup(keystr_from_pk(pk));
    2946             : 
    2947             :                           /* No, so try and get it */
    2948           0 :                           if ((opt.keyserver_options.options
    2949           0 :                                & KEYSERVER_AUTO_KEY_RETRIEVE)
    2950           0 :                               && keyserver_any_configured (ctrl))
    2951             :                             {
    2952           0 :                               log_info(_("WARNING: key %s may be revoked:"
    2953             :                                          " fetching revocation key %s\n"),
    2954             :                                        tempkeystr,keystr(keyid));
    2955           0 :                               keyserver_import_fprint (ctrl,
    2956           0 :                                                        sig->revkey[idx].fpr,
    2957             :                                                        MAX_FINGERPRINT_LEN,
    2958             :                                                        opt.keyserver, 0);
    2959             : 
    2960             :                               /* Do we have it now? */
    2961           0 :                               rc=get_pubkey_byfprint_fast (NULL,
    2962           0 :                                                      sig->revkey[idx].fpr,
    2963             :                                                      MAX_FINGERPRINT_LEN);
    2964             :                             }
    2965             : 
    2966           0 :                           if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
    2967           0 :                               || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
    2968           0 :                             log_info(_("WARNING: key %s may be revoked:"
    2969             :                                        " revocation key %s not present.\n"),
    2970             :                                      tempkeystr,keystr(keyid));
    2971             : 
    2972           0 :                           xfree(tempkeystr);
    2973             :                         }
    2974             :                     }
    2975             :                 }
    2976             :             }
    2977             :         }
    2978             :     }
    2979         158 : }
    2980             : 
    2981             : 
    2982             : /*
    2983             :  * compare and merge the blocks
    2984             :  *
    2985             :  * o compare the signatures: If we already have this signature, check
    2986             :  *   that they compare okay; if not, issue a warning and ask the user.
    2987             :  * o Simply add the signature.  Can't verify here because we may not have
    2988             :  *   the signature's public key yet; verification is done when putting it
    2989             :  *   into the trustdb, which is done automagically as soon as this pubkey
    2990             :  *   is used.
    2991             :  * Note: We indicate newly inserted packets with NODE_FLAG_A.
    2992             :  */
    2993             : static int
    2994          48 : merge_blocks (kbnode_t keyblock_orig, kbnode_t keyblock,
    2995             :               u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
    2996             : {
    2997             :   kbnode_t onode, node;
    2998             :   int rc, found;
    2999             : 
    3000             :   /* 1st: handle revocation certificates */
    3001          49 :   for (node=keyblock->next; node; node=node->next )
    3002             :     {
    3003          49 :       if (node->pkt->pkttype == PKT_USER_ID )
    3004          48 :         break;
    3005           1 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    3006           1 :                && node->pkt->pkt.signature->sig_class == 0x20)
    3007             :         {
    3008             :           /* check whether we already have this */
    3009           0 :           found = 0;
    3010           0 :           for (onode=keyblock_orig->next; onode; onode=onode->next)
    3011             :             {
    3012           0 :               if (onode->pkt->pkttype == PKT_USER_ID )
    3013           0 :                 break;
    3014           0 :               else if (onode->pkt->pkttype == PKT_SIGNATURE
    3015           0 :                        && onode->pkt->pkt.signature->sig_class == 0x20
    3016           0 :                        && !cmp_signatures(onode->pkt->pkt.signature,
    3017           0 :                                           node->pkt->pkt.signature))
    3018             :                 {
    3019           0 :                   found = 1;
    3020           0 :                   break;
    3021             :                 }
    3022             :             }
    3023           0 :           if (!found)
    3024             :             {
    3025           0 :               kbnode_t n2 = clone_kbnode(node);
    3026           0 :               insert_kbnode( keyblock_orig, n2, 0 );
    3027           0 :               n2->flag |= NODE_FLAG_A;
    3028           0 :               ++*n_sigs;
    3029           0 :               if(!opt.quiet)
    3030             :                 {
    3031           0 :                   char *p=get_user_id_native (keyid);
    3032           0 :                   log_info(_("key %s: \"%s\" revocation"
    3033             :                              " certificate added\n"), keystr(keyid),p);
    3034           0 :                   xfree(p);
    3035             :                 }
    3036             :             }
    3037             :         }
    3038             :     }
    3039             : 
    3040             :   /* 2nd: merge in any direct key (0x1F) sigs */
    3041          49 :   for(node=keyblock->next; node; node=node->next)
    3042             :     {
    3043          49 :       if (node->pkt->pkttype == PKT_USER_ID )
    3044          48 :         break;
    3045           1 :       else if (node->pkt->pkttype == PKT_SIGNATURE
    3046           1 :                && node->pkt->pkt.signature->sig_class == 0x1F)
    3047             :         {
    3048             :           /* check whether we already have this */
    3049           1 :           found = 0;
    3050           1 :           for (onode=keyblock_orig->next; onode; onode=onode->next)
    3051             :             {
    3052           1 :               if (onode->pkt->pkttype == PKT_USER_ID)
    3053           1 :                 break;
    3054           0 :               else if (onode->pkt->pkttype == PKT_SIGNATURE
    3055           0 :                        && onode->pkt->pkt.signature->sig_class == 0x1F
    3056           0 :                        && !cmp_signatures(onode->pkt->pkt.signature,
    3057           0 :                                           node->pkt->pkt.signature))
    3058             :                 {
    3059           0 :                   found = 1;
    3060           0 :                   break;
    3061             :                 }
    3062             :             }
    3063           1 :           if (!found )
    3064             :             {
    3065           1 :               kbnode_t n2 = clone_kbnode(node);
    3066           1 :               insert_kbnode( keyblock_orig, n2, 0 );
    3067           1 :               n2->flag |= NODE_FLAG_A;
    3068           1 :               ++*n_sigs;
    3069           1 :               if(!opt.quiet)
    3070           1 :                 log_info( _("key %s: direct key signature added\n"),
    3071             :                           keystr(keyid));
    3072             :             }
    3073             :         }
    3074             :     }
    3075             : 
    3076             :   /* 3rd: try to merge new certificates in */
    3077         267 :   for (onode=keyblock_orig->next; onode; onode=onode->next)
    3078             :     {
    3079         219 :       if (!(onode->flag & NODE_FLAG_A) && onode->pkt->pkttype == PKT_USER_ID)
    3080             :         {
    3081             :           /* find the user id in the imported keyblock */
    3082          87 :           for (node=keyblock->next; node; node=node->next)
    3083          87 :             if (node->pkt->pkttype == PKT_USER_ID
    3084          71 :                 && !cmp_user_ids( onode->pkt->pkt.user_id,
    3085          71 :                                   node->pkt->pkt.user_id ) )
    3086          58 :               break;
    3087          58 :           if (node ) /* found: merge */
    3088             :             {
    3089          58 :               rc = merge_sigs (onode, node, n_sigs);
    3090          58 :               if (rc )
    3091           0 :                 return rc;
    3092             :             }
    3093             :         }
    3094             :     }
    3095             : 
    3096             :   /* 4th: add new user-ids */
    3097         264 :   for (node=keyblock->next; node; node=node->next)
    3098             :     {
    3099         216 :       if (node->pkt->pkttype == PKT_USER_ID)
    3100             :         {
    3101             :           /* do we have this in the original keyblock */
    3102         101 :           for (onode=keyblock_orig->next; onode; onode=onode->next )
    3103          99 :             if (onode->pkt->pkttype == PKT_USER_ID
    3104          73 :                 && !cmp_user_ids( onode->pkt->pkt.user_id,
    3105          73 :                                   node->pkt->pkt.user_id ) )
    3106          58 :               break;
    3107          60 :           if (!onode ) /* this is a new user id: append */
    3108             :             {
    3109           2 :               rc = append_uid (keyblock_orig, node, n_sigs);
    3110           2 :               if (rc )
    3111           0 :                 return rc;
    3112           2 :               ++*n_uids;
    3113             :             }
    3114             :         }
    3115             :     }
    3116             : 
    3117             :   /* 5th: add new subkeys */
    3118         264 :   for (node=keyblock->next; node; node=node->next)
    3119             :     {
    3120         216 :       onode = NULL;
    3121         216 :       if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
    3122             :         {
    3123             :           /* do we have this in the original keyblock? */
    3124         164 :           for(onode=keyblock_orig->next; onode; onode=onode->next)
    3125         164 :             if (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3126          42 :                 && !cmp_public_keys( onode->pkt->pkt.public_key,
    3127          42 :                                      node->pkt->pkt.public_key))
    3128          42 :               break;
    3129          42 :           if (!onode ) /* This is a new subkey: append.  */
    3130             :             {
    3131           0 :               rc = append_key (keyblock_orig, node, n_sigs);
    3132           0 :               if (rc)
    3133           0 :                 return rc;
    3134           0 :               ++*n_subk;
    3135             :             }
    3136             :         }
    3137         174 :       else if (node->pkt->pkttype == PKT_SECRET_SUBKEY)
    3138             :         {
    3139             :           /* do we have this in the original keyblock? */
    3140           0 :           for (onode=keyblock_orig->next; onode; onode=onode->next )
    3141           0 :             if (onode->pkt->pkttype == PKT_SECRET_SUBKEY
    3142           0 :                 && !cmp_public_keys (onode->pkt->pkt.public_key,
    3143           0 :                                      node->pkt->pkt.public_key) )
    3144           0 :               break;
    3145           0 :           if (!onode ) /* This is a new subkey: append.  */
    3146             :             {
    3147           0 :               rc = append_key (keyblock_orig, node, n_sigs);
    3148           0 :               if (rc )
    3149           0 :                 return rc;
    3150           0 :               ++*n_subk;
    3151             :             }
    3152             :         }
    3153             :     }
    3154             : 
    3155             :   /* 6th: merge subkey certificates */
    3156         271 :   for (onode=keyblock_orig->next; onode; onode=onode->next)
    3157             :     {
    3158         223 :       if (!(onode->flag & NODE_FLAG_A)
    3159         211 :           && (onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3160         167 :               || onode->pkt->pkttype == PKT_SECRET_SUBKEY))
    3161             :         {
    3162             :           /* find the subkey in the imported keyblock */
    3163         167 :           for(node=keyblock->next; node; node=node->next)
    3164             :             {
    3165         165 :               if ((node->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3166         123 :                    || node->pkt->pkttype == PKT_SECRET_SUBKEY)
    3167          42 :                   && !cmp_public_keys( onode->pkt->pkt.public_key,
    3168          42 :                                        node->pkt->pkt.public_key ) )
    3169          42 :                 break;
    3170             :             }
    3171          44 :           if (node) /* Found: merge.  */
    3172             :             {
    3173          42 :               rc = merge_keysigs( onode, node, n_sigs);
    3174          42 :               if (rc )
    3175           0 :                 return rc;
    3176             :             }
    3177             :         }
    3178             :     }
    3179             : 
    3180          48 :   return 0;
    3181             : }
    3182             : 
    3183             : 
    3184             : /* Helper function for merge_blocks.
    3185             :  * Append the userid starting with NODE and all signatures to KEYBLOCK.
    3186             :  */
    3187             : static int
    3188           2 : append_uid (kbnode_t keyblock, kbnode_t node, int *n_sigs)
    3189             : {
    3190             :   kbnode_t n;
    3191           2 :   kbnode_t n_where = NULL;
    3192             : 
    3193           2 :   log_assert (node->pkt->pkttype == PKT_USER_ID );
    3194             : 
    3195             :   /* find the position */
    3196          10 :   for (n = keyblock; n; n_where = n, n = n->next)
    3197             :     {
    3198          10 :       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3199           8 :           || n->pkt->pkttype == PKT_SECRET_SUBKEY )
    3200             :         break;
    3201             :     }
    3202           2 :   if (!n)
    3203           0 :     n_where = NULL;
    3204             : 
    3205             :   /* and append/insert */
    3206           6 :   while (node)
    3207             :     {
    3208             :       /* we add a clone to the original keyblock, because this
    3209             :        * one is released first */
    3210           4 :       n = clone_kbnode(node);
    3211           4 :       if (n_where)
    3212             :         {
    3213           4 :           insert_kbnode( n_where, n, 0 );
    3214           4 :           n_where = n;
    3215             :         }
    3216             :       else
    3217           0 :         add_kbnode( keyblock, n );
    3218           4 :       n->flag |= NODE_FLAG_A;
    3219           4 :       node->flag |= NODE_FLAG_A;
    3220           4 :       if (n->pkt->pkttype == PKT_SIGNATURE )
    3221           2 :         ++*n_sigs;
    3222             : 
    3223           4 :       node = node->next;
    3224           4 :       if (node && node->pkt->pkttype != PKT_SIGNATURE )
    3225           2 :         break;
    3226             :     }
    3227             : 
    3228           2 :   return 0;
    3229             : }
    3230             : 
    3231             : 
    3232             : /* Helper function for merge_blocks
    3233             :  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
    3234             :  * (how should we handle comment packets here?)
    3235             :  */
    3236             : static int
    3237          58 : merge_sigs (kbnode_t dst, kbnode_t src, int *n_sigs)
    3238             : {
    3239             :   kbnode_t n, n2;
    3240          58 :   int found = 0;
    3241             : 
    3242          58 :   log_assert (dst->pkt->pkttype == PKT_USER_ID);
    3243          58 :   log_assert (src->pkt->pkttype == PKT_USER_ID);
    3244             : 
    3245         207 :   for (n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next)
    3246             :     {
    3247         149 :       if (n->pkt->pkttype != PKT_SIGNATURE )
    3248          40 :         continue;
    3249         109 :       if (n->pkt->pkt.signature->sig_class == 0x18
    3250          69 :           || n->pkt->pkt.signature->sig_class == 0x28 )
    3251          40 :         continue; /* skip signatures which are only valid on subkeys */
    3252             : 
    3253          69 :       found = 0;
    3254          95 :       for (n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
    3255          88 :         if (!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
    3256             :           {
    3257          62 :             found++;
    3258          62 :             break;
    3259             :           }
    3260          69 :       if (!found )
    3261             :         {
    3262             :           /* This signature is new or newer, append N to DST.
    3263             :            * We add a clone to the original keyblock, because this
    3264             :            * one is released first */
    3265           7 :           n2 = clone_kbnode(n);
    3266           7 :           insert_kbnode( dst, n2, PKT_SIGNATURE );
    3267           7 :           n2->flag |= NODE_FLAG_A;
    3268           7 :           n->flag |= NODE_FLAG_A;
    3269           7 :           ++*n_sigs;
    3270             :         }
    3271             :     }
    3272             : 
    3273          58 :   return 0;
    3274             : }
    3275             : 
    3276             : 
    3277             : /* Helper function for merge_blocks
    3278             :  * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
    3279             :  */
    3280             : static int
    3281          42 : merge_keysigs (kbnode_t dst, kbnode_t src, int *n_sigs)
    3282             : {
    3283             :   kbnode_t n, n2;
    3284          42 :   int found = 0;
    3285             : 
    3286          42 :   log_assert (dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3287             :               || dst->pkt->pkttype == PKT_SECRET_SUBKEY);
    3288             : 
    3289          84 :   for (n=src->next; n ; n = n->next)
    3290             :     {
    3291          42 :       if (n->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3292          42 :           || n->pkt->pkttype == PKT_PUBLIC_KEY )
    3293             :         break;
    3294          42 :       if (n->pkt->pkttype != PKT_SIGNATURE )
    3295           0 :         continue;
    3296             : 
    3297          42 :       found = 0;
    3298          42 :       for (n2=dst->next; n2; n2 = n2->next)
    3299             :         {
    3300          42 :           if (n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3301          42 :               || n2->pkt->pkttype == PKT_PUBLIC_KEY )
    3302             :             break;
    3303          42 :           if (n2->pkt->pkttype == PKT_SIGNATURE
    3304          84 :               && (n->pkt->pkt.signature->keyid[0]
    3305          42 :                   == n2->pkt->pkt.signature->keyid[0])
    3306          84 :               && (n->pkt->pkt.signature->keyid[1]
    3307          42 :                   == n2->pkt->pkt.signature->keyid[1])
    3308          84 :               && (n->pkt->pkt.signature->timestamp
    3309          42 :                   <= n2->pkt->pkt.signature->timestamp)
    3310          84 :               && (n->pkt->pkt.signature->sig_class
    3311          42 :                   == n2->pkt->pkt.signature->sig_class))
    3312             :             {
    3313          42 :               found++;
    3314          42 :               break;
    3315             :             }
    3316             :         }
    3317          42 :       if (!found )
    3318             :         {
    3319             :           /* This signature is new or newer, append N to DST.
    3320             :            * We add a clone to the original keyblock, because this
    3321             :            * one is released first */
    3322           0 :           n2 = clone_kbnode(n);
    3323           0 :           insert_kbnode( dst, n2, PKT_SIGNATURE );
    3324           0 :           n2->flag |= NODE_FLAG_A;
    3325           0 :           n->flag |= NODE_FLAG_A;
    3326           0 :           ++*n_sigs;
    3327             :         }
    3328             :     }
    3329             : 
    3330          42 :   return 0;
    3331             : }
    3332             : 
    3333             : 
    3334             : /* Helper function for merge_blocks.
    3335             :  * Append the subkey starting with NODE and all signatures to KEYBLOCK.
    3336             :  * Mark all new and copied packets by setting flag bit 0.
    3337             :  */
    3338             : static int
    3339           0 : append_key (kbnode_t keyblock, kbnode_t node, int *n_sigs)
    3340             : {
    3341             :   kbnode_t n;
    3342             : 
    3343           0 :   log_assert (node->pkt->pkttype == PKT_PUBLIC_SUBKEY
    3344             :               || node->pkt->pkttype == PKT_SECRET_SUBKEY);
    3345             : 
    3346           0 :   while (node)
    3347             :     {
    3348             :       /* we add a clone to the original keyblock, because this
    3349             :        * one is released first */
    3350           0 :       n = clone_kbnode(node);
    3351           0 :       add_kbnode( keyblock, n );
    3352           0 :       n->flag |= NODE_FLAG_A;
    3353           0 :       node->flag |= NODE_FLAG_A;
    3354           0 :       if (n->pkt->pkttype == PKT_SIGNATURE )
    3355           0 :         ++*n_sigs;
    3356             : 
    3357           0 :       node = node->next;
    3358           0 :       if (node && node->pkt->pkttype != PKT_SIGNATURE )
    3359           0 :         break;
    3360             :     }
    3361             : 
    3362           0 :   return 0;
    3363             : }

Generated by: LCOV version 1.11