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