~ubuntu-branches/ubuntu/precise/gnupg2/precise-updates

« back to all changes in this revision

Viewing changes to g10/import.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Mueller
  • Date: 2005-03-29 10:30:32 UTC
  • Revision ID: james.westby@ubuntu.com-20050329103032-sj42n2ain3ipx310
Tags: upstream-1.9.15
ImportĀ upstreamĀ versionĀ 1.9.15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* import.c - Import OpenPGP key material
 
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002,
 
3
 *               2003 Free Software Foundation, Inc.
 
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 2 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, write to the Free Software
 
19
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
20
 */
 
21
 
 
22
#include <config.h>
 
23
#include <stdio.h>
 
24
#include <stdlib.h>
 
25
#include <string.h>
 
26
#include <errno.h>
 
27
#include <assert.h>
 
28
 
 
29
#include "options.h"
 
30
#include "packet.h"
 
31
#include "errors.h"
 
32
#include "keydb.h"
 
33
#include "memory.h"
 
34
#include "util.h"
 
35
#include "trustdb.h"
 
36
#include "main.h"
 
37
#include "i18n.h"
 
38
#include "ttyio.h"
 
39
#include "status.h"
 
40
#include "keyserver-internal.h"
 
41
 
 
42
struct stats_s {
 
43
    ulong count;
 
44
    ulong no_user_id;
 
45
    ulong imported;
 
46
    ulong imported_rsa;
 
47
    ulong n_uids;
 
48
    ulong n_sigs;
 
49
    ulong n_subk;
 
50
    ulong unchanged;
 
51
    ulong n_revoc;
 
52
    ulong secret_read;
 
53
    ulong secret_imported;
 
54
    ulong secret_dups;
 
55
    ulong skipped_new_keys;
 
56
    ulong not_imported;
 
57
};
 
58
 
 
59
 
 
60
static int import( iobuf_t inp, const char* fname,
 
61
                   struct stats_s *stats, unsigned int options );
 
62
static int read_block( iobuf_t a, PACKET **pending_pkt, KBNODE *ret_root );
 
63
static void revocation_present(KBNODE keyblock);
 
64
static int import_one( const char *fname, KBNODE keyblock,
 
65
                       struct stats_s *stats, unsigned int options);
 
66
static int import_secret_one( const char *fname, KBNODE keyblock,
 
67
                              struct stats_s *stats, unsigned int options);
 
68
static int import_revoke_cert( const char *fname, KBNODE node,
 
69
                               struct stats_s *stats);
 
70
static int chk_self_sigs( const char *fname, KBNODE keyblock,
 
71
                          PKT_public_key *pk, u32 *keyid, int *non_self );
 
72
static int delete_inv_parts( const char *fname, KBNODE keyblock,
 
73
                             u32 *keyid, unsigned int options );
 
74
static int merge_blocks( const char *fname, KBNODE keyblock_orig,
 
75
                         KBNODE keyblock, u32 *keyid,
 
76
                         int *n_uids, int *n_sigs, int *n_subk );
 
77
static int append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
 
78
                             const char *fname, u32 *keyid );
 
79
static int append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
 
80
                             const char *fname, u32 *keyid );
 
81
static int merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
 
82
                             const char *fname, u32 *keyid );
 
83
static int merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
 
84
                             const char *fname, u32 *keyid );
 
85
 
 
86
int
 
87
parse_import_options(char *str,unsigned int *options)
 
88
{
 
89
  struct parse_options import_opts[]=
 
90
    {
 
91
      {"allow-local-sigs",IMPORT_ALLOW_LOCAL_SIGS},
 
92
      {"repair-hkp-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG},
 
93
      {"repair-pks-subkey-bug",IMPORT_REPAIR_PKS_SUBKEY_BUG},
 
94
      {"fast-import",IMPORT_FAST_IMPORT},
 
95
      {"convert-sk-to-pk",IMPORT_SK2PK},
 
96
      {NULL,0}
 
97
    };
 
98
 
 
99
  return parse_options(str,options,import_opts);
 
100
}
 
101
 
 
102
void *
 
103
import_new_stats_handle (void)
 
104
{
 
105
    return xcalloc (1, sizeof (struct stats_s) );
 
106
}
 
107
 
 
108
void
 
109
import_release_stats_handle (void *p)
 
110
{
 
111
    xfree (p);
 
112
}
 
113
 
 
114
/****************
 
115
 * Import the public keys from the given filename. Input may be armored.
 
116
 * This function rejects all keys which are not validly self signed on at
 
117
 * least one userid. Only user ids which are self signed will be imported.
 
118
 * Other signatures are not checked.
 
119
 *
 
120
 * Actually this function does a merge. It works like this:
 
121
 *
 
122
 *  - get the keyblock
 
123
 *  - check self-signatures and remove all userids and their signatures
 
124
 *    without/invalid self-signatures.
 
125
 *  - reject the keyblock, if we have no valid userid.
 
126
 *  - See whether we have this key already in one of our pubrings.
 
127
 *    If not, simply add it to the default keyring.
 
128
 *  - Compare the key and the self-signatures of the new and the one in
 
129
 *    our keyring.  If they are different something weird is going on;
 
130
 *    ask what to do.
 
131
 *  - See whether we have only non-self-signature on one user id; if not
 
132
 *    ask the user what to do.
 
133
 *  - compare the signatures: If we already have this signature, check
 
134
 *    that they compare okay; if not, issue a warning and ask the user.
 
135
 *    (consider looking at the timestamp and use the newest?)
 
136
 *  - Simply add the signature.  Can't verify here because we may not have
 
137
 *    the signature's public key yet; verification is done when putting it
 
138
 *    into the trustdb, which is done automagically as soon as this pubkey
 
139
 *    is used.
 
140
 *  - Proceed with next signature.
 
141
 *
 
142
 *  Key revocation certificates have special handling.
 
143
 *
 
144
 */
 
145
static int
 
146
import_keys_internal( iobuf_t inp, char **fnames, int nnames,
 
147
                      void *stats_handle, unsigned int options )
 
148
{
 
149
    int i, rc = 0;
 
150
    struct stats_s *stats = stats_handle;
 
151
 
 
152
    if (!stats)
 
153
        stats = import_new_stats_handle ();
 
154
 
 
155
    if (inp) {
 
156
        rc = import( inp, "[stream]", stats, options);
 
157
    }
 
158
    else {
 
159
        if( !fnames && !nnames )
 
160
            nnames = 1;  /* Ohh what a ugly hack to jump into the loop */
 
161
 
 
162
        for(i=0; i < nnames; i++ ) {
 
163
            const char *fname = fnames? fnames[i] : NULL;
 
164
            iobuf_t inp2 = iobuf_open(fname);
 
165
            if( !fname )
 
166
                fname = "[stdin]";
 
167
            if( !inp2 )
 
168
                log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
 
169
            else {
 
170
                rc = import( inp2, fname, stats, options );
 
171
                iobuf_close(inp2);
 
172
                /* Must invalidate that ugly cache to actually close it. */
 
173
                iobuf_ioctl (NULL, 2, 0, (char*)fname);
 
174
                if( rc )
 
175
                    log_error("import from `%s' failed: %s\n", fname,
 
176
                              gpg_strerror (rc) );
 
177
            }
 
178
            if( !fname )
 
179
                break;
 
180
        }
 
181
    }
 
182
    if (!stats_handle) {
 
183
        import_print_stats (stats);
 
184
        import_release_stats_handle (stats);
 
185
    }
 
186
    /* If no fast import and the trustdb is dirty (i.e. we added a key
 
187
       or userID that had something other than a selfsig, a signature
 
188
       that was other than a selfsig, or any revocation), then
 
189
       update/check the trustdb if the user specified by setting
 
190
       interactive or by not setting no-auto-check-trustdb */
 
191
    if (!(options&IMPORT_FAST_IMPORT) && trustdb_pending_check())
 
192
      {
 
193
        if (opt.interactive)
 
194
          update_trustdb();
 
195
        else if (!opt.no_auto_check_trustdb)
 
196
          check_trustdb();
 
197
      }
 
198
 
 
199
    return rc;
 
200
}
 
201
 
 
202
void
 
203
import_keys( char **fnames, int nnames,
 
204
             void *stats_handle, unsigned int options )
 
205
{
 
206
    import_keys_internal( NULL, fnames, nnames, stats_handle, options);
 
207
}
 
208
 
 
209
int
 
210
import_keys_stream( iobuf_t inp, void *stats_handle, unsigned int options )
 
211
{
 
212
    return import_keys_internal( inp, NULL, 0, stats_handle, options);
 
213
}
 
214
 
 
215
static int
 
216
import( iobuf_t inp, const char* fname,
 
217
        struct stats_s *stats, unsigned int options )
 
218
{
 
219
    PACKET *pending_pkt = NULL;
 
220
    KBNODE keyblock;
 
221
    int rc = 0;
 
222
 
 
223
    getkey_disable_caches();
 
224
 
 
225
    if( !opt.no_armor ) { /* armored reading is not disabled */
 
226
        armor_filter_context_t *afx = xcalloc (1, sizeof *afx );
 
227
        afx->only_keyblocks = 1;
 
228
        iobuf_push_filter2( inp, armor_filter, afx, 1 );
 
229
    }
 
230
 
 
231
    while( !(rc = read_block( inp, &pending_pkt, &keyblock) )) {
 
232
        if( keyblock->pkt->pkttype == PKT_PUBLIC_KEY )
 
233
            rc = import_one( fname, keyblock, stats, options );
 
234
        else if( keyblock->pkt->pkttype == PKT_SECRET_KEY ) 
 
235
                rc = import_secret_one( fname, keyblock, stats, options );
 
236
        else if( keyblock->pkt->pkttype == PKT_SIGNATURE
 
237
                 && keyblock->pkt->pkt.signature->sig_class == 0x20 )
 
238
            rc = import_revoke_cert( fname, keyblock, stats );
 
239
        else {
 
240
            log_info( _("skipping block of type %d\n"),
 
241
                                            keyblock->pkt->pkttype );
 
242
        }
 
243
        release_kbnode(keyblock);
 
244
        /* fixme: we should increment the not imported counter but this
 
245
           does only make sense if we keep on going despite of errors. */
 
246
        if( rc )
 
247
            break;
 
248
        if( !(++stats->count % 100) && !opt.quiet )
 
249
            log_info(_("%lu keys processed so far\n"), stats->count );
 
250
    }
 
251
    if( rc == -1 )
 
252
        rc = 0;
 
253
    else if( rc && rc != GPG_ERR_INV_KEYRING )
 
254
        log_error( _("error reading `%s': %s\n"), fname, gpg_strerror (rc));
 
255
 
 
256
    return rc;
 
257
}
 
258
 
 
259
 
 
260
void
 
261
import_print_stats (void *hd)
 
262
{
 
263
    struct stats_s *stats = hd;
 
264
 
 
265
    if( !opt.quiet ) {
 
266
        log_info(_("Total number processed: %lu\n"), stats->count );
 
267
        if( stats->skipped_new_keys )
 
268
            log_info(_("      skipped new keys: %lu\n"),
 
269
                                                stats->skipped_new_keys );
 
270
        if( stats->no_user_id )
 
271
            log_info(_("          w/o user IDs: %lu\n"), stats->no_user_id );
 
272
        if( stats->imported || stats->imported_rsa ) {
 
273
            log_info(_("              imported: %lu"), stats->imported );
 
274
            if( stats->imported_rsa )
 
275
                fprintf(stderr, "  (RSA: %lu)", stats->imported_rsa );
 
276
            putc('\n', stderr);
 
277
        }
 
278
        if( stats->unchanged )
 
279
            log_info(_("             unchanged: %lu\n"), stats->unchanged );
 
280
        if( stats->n_uids )
 
281
            log_info(_("          new user IDs: %lu\n"), stats->n_uids );
 
282
        if( stats->n_subk )
 
283
            log_info(_("           new subkeys: %lu\n"), stats->n_subk );
 
284
        if( stats->n_sigs )
 
285
            log_info(_("        new signatures: %lu\n"), stats->n_sigs );
 
286
        if( stats->n_revoc )
 
287
            log_info(_("   new key revocations: %lu\n"), stats->n_revoc );
 
288
        if( stats->secret_read )
 
289
            log_info(_("      secret keys read: %lu\n"), stats->secret_read );
 
290
        if( stats->secret_imported )
 
291
            log_info(_("  secret keys imported: %lu\n"), stats->secret_imported );
 
292
        if( stats->secret_dups )
 
293
            log_info(_(" secret keys unchanged: %lu\n"), stats->secret_dups );
 
294
        if( stats->not_imported )
 
295
            log_info(_("          not imported: %lu\n"), stats->not_imported );
 
296
    }
 
297
 
 
298
    if( is_status_enabled() ) {
 
299
        char buf[14*20];
 
300
        sprintf(buf, "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
 
301
                stats->count,
 
302
                stats->no_user_id,
 
303
                stats->imported,
 
304
                stats->imported_rsa,
 
305
                stats->unchanged,
 
306
                stats->n_uids,
 
307
                stats->n_subk,
 
308
                stats->n_sigs,
 
309
                stats->n_revoc,
 
310
                stats->secret_read,
 
311
                stats->secret_imported,
 
312
                stats->secret_dups,
 
313
                stats->skipped_new_keys,
 
314
                stats->not_imported );
 
315
        write_status_text( STATUS_IMPORT_RES, buf );
 
316
    }
 
317
}
 
318
 
 
319
 
 
320
/****************
 
321
 * Read the next keyblock from stream A.
 
322
 * PENDING_PKT should be initialzed to NULL
 
323
 * and not chnaged form the caller.
 
324
 * Retunr: 0 = okay, -1 no more blocks or another errorcode.
 
325
 */
 
326
static int
 
327
read_block( iobuf_t a, PACKET **pending_pkt, KBNODE *ret_root )
 
328
{
 
329
    int rc;
 
330
    PACKET *pkt;
 
331
    KBNODE root = NULL;
 
332
    int in_cert;
 
333
 
 
334
    if( *pending_pkt ) {
 
335
        root = new_kbnode( *pending_pkt );
 
336
        *pending_pkt = NULL;
 
337
        in_cert = 1;
 
338
    }
 
339
    else
 
340
        in_cert = 0;
 
341
    pkt = xmalloc ( sizeof *pkt );
 
342
    init_packet(pkt);
 
343
    while( (rc=parse_packet(a, pkt)) != -1 ) {
 
344
        if( rc ) {  /* ignore errors */
 
345
            if( rc != GPG_ERR_UNKNOWN_PACKET ) {
 
346
                log_error("read_block: read error: %s\n", gpg_strerror (rc) );
 
347
                rc = GPG_ERR_INV_KEYRING;
 
348
                goto ready;
 
349
            }
 
350
            free_packet( pkt );
 
351
            init_packet(pkt);
 
352
            continue;
 
353
        }
 
354
 
 
355
        if( !root && pkt->pkttype == PKT_SIGNATURE
 
356
                  && pkt->pkt.signature->sig_class == 0x20 ) {
 
357
            /* this is a revocation certificate which is handled
 
358
             * in a special way */
 
359
            root = new_kbnode( pkt );
 
360
            pkt = NULL;
 
361
            goto ready;
 
362
        }
 
363
 
 
364
        /* make a linked list of all packets */
 
365
        switch( pkt->pkttype ) {
 
366
          case PKT_COMPRESSED:
 
367
            if( pkt->pkt.compressed->algorithm < 1
 
368
                || pkt->pkt.compressed->algorithm > 2 ) {
 
369
                rc = GPG_ERR_COMPR_ALGO;
 
370
                goto ready;
 
371
            }
 
372
            {
 
373
                compress_filter_context_t *cfx = xcalloc (1, sizeof *cfx );
 
374
                cfx->algo = pkt->pkt.compressed->algorithm;
 
375
                pkt->pkt.compressed->buf = NULL;
 
376
                iobuf_push_filter2( a, compress_filter, cfx, 1 );
 
377
            }
 
378
            free_packet( pkt );
 
379
            init_packet(pkt);
 
380
            break;
 
381
 
 
382
          case PKT_RING_TRUST:
 
383
            /* skip those packets */
 
384
            free_packet( pkt );
 
385
            init_packet(pkt);
 
386
            break;
 
387
 
 
388
          case PKT_PUBLIC_KEY:
 
389
          case PKT_SECRET_KEY:
 
390
            if( in_cert ) { /* store this packet */
 
391
                *pending_pkt = pkt;
 
392
                pkt = NULL;
 
393
                goto ready;
 
394
            }
 
395
            in_cert = 1;
 
396
          default:
 
397
            if( in_cert ) {
 
398
                if( !root )
 
399
                    root = new_kbnode( pkt );
 
400
                else
 
401
                    add_kbnode( root, new_kbnode( pkt ) );
 
402
                pkt = xmalloc ( sizeof *pkt );
 
403
            }
 
404
            init_packet(pkt);
 
405
            break;
 
406
        }
 
407
    }
 
408
  ready:
 
409
    if( rc == -1 && root )
 
410
        rc = 0;
 
411
 
 
412
    if( rc )
 
413
        release_kbnode( root );
 
414
    else
 
415
        *ret_root = root;
 
416
    free_packet( pkt );
 
417
    xfree ( pkt );
 
418
    return rc;
 
419
}
 
420
 
 
421
/* Walk through the subkeys on a pk to find if we have the PKS
 
422
   disease: multiple subkeys with their binding sigs stripped, and the
 
423
   sig for the first subkey placed after the last subkey.  That is,
 
424
   instead of "pk uid sig sub1 bind1 sub2 bind2 sub3 bind3" we have
 
425
   "pk uid sig sub1 sub2 sub3 bind1".  We can't do anything about sub2
 
426
   and sub3, as they are already lost, but we can try and rescue sub1
 
427
   by reordering the keyblock so that it reads "pk uid sig sub1 bind1
 
428
   sub2 sub3".  Returns TRUE if the keyblock was modified. */
 
429
 
 
430
static int
 
431
fix_pks_corruption(KBNODE keyblock)
 
432
{
 
433
  int changed=0,keycount=0;
 
434
  KBNODE node,last=NULL,sknode=NULL;
 
435
 
 
436
  /* First determine if we have the problem at all.  Look for 2 or
 
437
     more subkeys in a row, followed by a single binding sig. */
 
438
  for(node=keyblock;node;last=node,node=node->next)
 
439
    {
 
440
      if(node->pkt->pkttype==PKT_PUBLIC_SUBKEY)
 
441
        {
 
442
          keycount++;
 
443
          if(!sknode)
 
444
            sknode=node;
 
445
        }
 
446
      else if(node->pkt->pkttype==PKT_SIGNATURE &&
 
447
              node->pkt->pkt.signature->sig_class==0x18 &&
 
448
              keycount>=2 && node->next==NULL)
 
449
        {
 
450
          /* We might have the problem, as this key has two subkeys in
 
451
             a row without any intervening packets. */
 
452
 
 
453
          /* Sanity check */
 
454
          if(last==NULL)
 
455
            break;
 
456
 
 
457
          /* Temporarily attach node to sknode. */
 
458
          node->next=sknode->next;
 
459
          sknode->next=node;
 
460
          last->next=NULL;
 
461
 
 
462
          /* Note we aren't checking whether this binding sig is a
 
463
             selfsig.  This is not necessary here as the subkey and
 
464
             binding sig will be rejected later if that is the
 
465
             case. */
 
466
          if(check_key_signature(keyblock,node,NULL))
 
467
            {
 
468
              /* Not a match, so undo the changes. */
 
469
              sknode->next=node->next;
 
470
              last->next=node;
 
471
              node->next=NULL;
 
472
              break;
 
473
            }
 
474
          else
 
475
            {
 
476
              sknode->flag |= 1; /* Mark it good so we don't need to
 
477
                                    check it again */
 
478
              changed=1;
 
479
              break;
 
480
            }
 
481
        }
 
482
      else
 
483
        keycount=0;
 
484
    }
 
485
 
 
486
  return changed;
 
487
}
 
488
 
 
489
 
 
490
static void
 
491
print_import_ok (PKT_public_key *pk, PKT_secret_key *sk, unsigned int reason)
 
492
{
 
493
  byte array[MAX_FINGERPRINT_LEN], *s;
 
494
  char buf[MAX_FINGERPRINT_LEN*2+30], *p;
 
495
  size_t i, n;
 
496
 
 
497
  sprintf (buf, "%u ", reason);
 
498
  p = buf + strlen (buf);
 
499
 
 
500
  if (pk)
 
501
    fingerprint_from_pk (pk, array, &n);
 
502
  else
 
503
    fingerprint_from_sk (sk, array, &n);
 
504
  s = array;
 
505
  for (i=0; i < n ; i++, s++, p += 2)
 
506
    sprintf (p, "%02X", *s);
 
507
 
 
508
  write_status_text (STATUS_IMPORT_OK, buf);
 
509
}
 
510
 
 
511
void
 
512
print_import_check (PKT_public_key * pk, PKT_user_id * id)
 
513
{
 
514
    char * buf;
 
515
    byte fpr[24];
 
516
    u32 keyid[2];
 
517
    size_t i, pos = 0, n;
 
518
 
 
519
    buf = xmalloc (17+41+id->len+32);
 
520
    keyid_from_pk (pk, keyid);
 
521
    sprintf (buf, "%08X%08X ", keyid[0], keyid[1]);
 
522
    pos = 17;
 
523
    fingerprint_from_pk (pk, fpr, &n);
 
524
    for (i = 0; i < n; i++, pos += 2)
 
525
        sprintf (buf+pos, "%02X", fpr[i]);
 
526
    strcat (buf, " ");
 
527
    pos += 1;
 
528
    strcat (buf, id->name);
 
529
    write_status_text (STATUS_IMPORT_CHECK, buf);
 
530
    xfree (buf);
 
531
}
 
532
 
 
533
/****************
 
534
 * Try to import one keyblock.  Return an error only in serious cases, but
 
535
 * never for an invalid keyblock.  It uses log_error to increase the
 
536
 * internal errorcount, so that invalid input can be detected by programs
 
537
 * which called g10.
 
538
 */
 
539
static int
 
540
import_one( const char *fname, KBNODE keyblock,
 
541
            struct stats_s *stats, unsigned int options )
 
542
{
 
543
    PKT_public_key *pk;
 
544
    PKT_public_key *pk_orig;
 
545
    KBNODE node, uidnode;
 
546
    KBNODE keyblock_orig = NULL;
 
547
    u32 keyid[2];
 
548
    int rc = 0;
 
549
    int new_key = 0;
 
550
    int mod_key = 0;
 
551
    int non_self = 0;
 
552
 
 
553
    /* get the key and print some info about it */
 
554
    node = find_kbnode( keyblock, PKT_PUBLIC_KEY );
 
555
    if( !node )
 
556
        BUG();
 
557
 
 
558
    pk = node->pkt->pkt.public_key;
 
559
    keyid_from_pk( pk, keyid );
 
560
    uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
 
561
 
 
562
    if(pk->pubkey_algo==PUBKEY_ALGO_ELGAMAL)
 
563
      log_info(_("NOTE: Elgamal primary key detected - "
 
564
                 "this may take some time to import\n"));
 
565
 
 
566
    if( opt.verbose && !opt.interactive ) {
 
567
        log_info( "pub  %4u%c/%08lX %s   ",
 
568
                  nbits_from_pk( pk ),
 
569
                  pubkey_letter( pk->pubkey_algo ),
 
570
                  (ulong)keyid[1], datestr_from_pk(pk) );
 
571
        if( uidnode )
 
572
            print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
 
573
                                       uidnode->pkt->pkt.user_id->len );
 
574
        putc('\n', stderr);
 
575
    }
 
576
    if( !uidnode ) {
 
577
        log_error( _("key %08lX: no user ID\n"), (ulong)keyid[1]);
 
578
        return 0;
 
579
    }
 
580
    
 
581
    if (opt.interactive) {
 
582
        if(is_status_enabled())
 
583
          print_import_check (pk, uidnode->pkt->pkt.user_id);
 
584
        merge_keys_and_selfsig (keyblock);
 
585
        tty_printf ("\n");
 
586
        show_basic_key_info (keyblock);
 
587
        tty_printf ("\n");
 
588
        if (!cpr_get_answer_is_yes ("import.okay",
 
589
                                    "Do you want to import this key? (y/N) "))
 
590
            return 0;
 
591
    }
 
592
 
 
593
    clear_kbnode_flags( keyblock );
 
594
 
 
595
    if((options&IMPORT_REPAIR_PKS_SUBKEY_BUG) && fix_pks_corruption(keyblock)
 
596
       && opt.verbose)
 
597
      log_info(_("key %08lX: PKS subkey corruption repaired\n"),
 
598
               (ulong)keyid[1]);
 
599
 
 
600
    rc = chk_self_sigs( fname, keyblock , pk, keyid, &non_self );
 
601
    if( rc )
 
602
        return rc== -1? 0:rc;
 
603
 
 
604
    /* If we allow such a thing, mark unsigned uids as valid */
 
605
    if( opt.allow_non_selfsigned_uid )
 
606
      for( node=keyblock; node; node = node->next )
 
607
        if( node->pkt->pkttype == PKT_USER_ID && !(node->flag & 1) )
 
608
          {
 
609
            char *user=utf8_to_native(node->pkt->pkt.user_id->name,
 
610
                                      node->pkt->pkt.user_id->len,0);
 
611
            node->flag |= 1;
 
612
            log_info( _("key %08lX: accepted non self-signed user ID '%s'\n"),
 
613
                      (ulong)keyid[1],user);
 
614
            xfree (user);
 
615
          }
 
616
 
 
617
    if( !delete_inv_parts( fname, keyblock, keyid, options ) ) {
 
618
        log_error ( _("key %08lX: no valid user IDs\n"), (ulong)keyid[1]);
 
619
        if( !opt.quiet )
 
620
            log_info(_("this may be caused by a missing self-signature\n"));
 
621
        stats->no_user_id++;
 
622
        return 0;
 
623
    }
 
624
 
 
625
    /* do we have this key already in one of our pubrings ? */
 
626
    pk_orig = xcalloc (1, sizeof *pk_orig );
 
627
    rc = get_pubkey_fast ( pk_orig, keyid );
 
628
    if( rc && gpg_err_code (rc) != GPG_ERR_NO_PUBKEY
 
629
        && gpg_err_code (rc) != GPG_ERR_UNUSABLE_PUBKEY ) {
 
630
        log_error( _("key %08lX: public key not found: %s\n"),
 
631
                                (ulong)keyid[1], gpg_strerror (rc));
 
632
    }
 
633
    else if ( rc && opt.merge_only ) {
 
634
        if( opt.verbose )
 
635
            log_info( _("key %08lX: new key - skipped\n"), (ulong)keyid[1] );
 
636
        rc = 0;
 
637
        stats->skipped_new_keys++;
 
638
    }
 
639
    else if( rc ) { /* insert this key */
 
640
        KEYDB_HANDLE hd = keydb_new (0);
 
641
 
 
642
        rc = keydb_locate_writable (hd, NULL);
 
643
        if (rc) {
 
644
            log_error (_("no writable keyring found: %s\n"), gpg_strerror (rc));
 
645
            keydb_release (hd);
 
646
            return GPG_ERR_GENERAL;
 
647
        }
 
648
        if( opt.verbose > 1 )
 
649
            log_info (_("writing to `%s'\n"), keydb_get_resource_name (hd) );
 
650
        rc = keydb_insert_keyblock (hd, keyblock );
 
651
        if (rc)
 
652
           log_error (_("error writing keyring `%s': %s\n"),
 
653
                       keydb_get_resource_name (hd), gpg_strerror (rc));
 
654
        else
 
655
          {
 
656
            /* This should not be possible since we delete the
 
657
               ownertrust when a key is deleted, but it can happen if
 
658
               the keyring and trustdb are out of sync.  It can also
 
659
               be made to happen with the trusted-key command. */
 
660
 
 
661
            clear_ownertrusts (pk);
 
662
            if(non_self)
 
663
              revalidation_mark ();
 
664
          }
 
665
        keydb_release (hd);
 
666
 
 
667
        /* we are ready */
 
668
        if( !opt.quiet ) {
 
669
            char *p=get_user_id_printable (keyid);
 
670
            log_info( _("key %08lX: public key \"%s\" imported\n"),
 
671
                      (ulong)keyid[1],p);
 
672
            xfree (p);
 
673
        }
 
674
        if( is_status_enabled() ) {
 
675
            char *us = get_long_user_id_string( keyid );
 
676
            write_status_text( STATUS_IMPORTED, us );
 
677
            xfree (us);
 
678
            print_import_ok (pk,NULL, 1);
 
679
        }
 
680
        stats->imported++;
 
681
        if( is_RSA( pk->pubkey_algo ) )
 
682
            stats->imported_rsa++;
 
683
        new_key = 1;
 
684
    }
 
685
    else { /* merge */
 
686
        KEYDB_HANDLE hd;
 
687
        int n_uids, n_sigs, n_subk;
 
688
 
 
689
        /* Compare the original against the new key; just to be sure nothing
 
690
         * weird is going on */
 
691
        if( cmp_public_keys( pk_orig, pk ) ) {
 
692
            log_error( _("key %08lX: doesn't match our copy\n"),
 
693
                                                          (ulong)keyid[1]);
 
694
            goto leave;
 
695
        }
 
696
 
 
697
        /* now read the original keyblock */
 
698
        hd = keydb_new (0);
 
699
        {
 
700
            byte afp[MAX_FINGERPRINT_LEN];
 
701
            size_t an;
 
702
 
 
703
            fingerprint_from_pk (pk_orig, afp, &an);
 
704
            while (an < MAX_FINGERPRINT_LEN) 
 
705
                afp[an++] = 0;
 
706
            rc = keydb_search_fpr (hd, afp);
 
707
        }
 
708
        if( rc ) {
 
709
            log_error (_("key %08lX: can't locate original keyblock: %s\n"),
 
710
                                     (ulong)keyid[1], gpg_strerror (rc));
 
711
            keydb_release (hd);
 
712
            goto leave;
 
713
        }
 
714
        rc = keydb_get_keyblock (hd, &keyblock_orig );
 
715
        if (rc) {
 
716
            log_error (_("key %08lX: can't read original keyblock: %s\n"),
 
717
                                            (ulong)keyid[1], gpg_strerror (rc));
 
718
            keydb_release (hd);
 
719
            goto leave;
 
720
        }
 
721
 
 
722
        collapse_uids( &keyblock );
 
723
        /* and try to merge the block */
 
724
        clear_kbnode_flags( keyblock_orig );
 
725
        clear_kbnode_flags( keyblock );
 
726
        n_uids = n_sigs = n_subk = 0;
 
727
        rc = merge_blocks( fname, keyblock_orig, keyblock,
 
728
                                keyid, &n_uids, &n_sigs, &n_subk );
 
729
        if( rc ) {
 
730
            keydb_release (hd);
 
731
            goto leave;
 
732
        }
 
733
        if( n_uids || n_sigs || n_subk ) {
 
734
            mod_key = 1;
 
735
            /* keyblock_orig has been updated; write */
 
736
            rc = keydb_update_keyblock (hd, keyblock_orig);
 
737
            if (rc)
 
738
                log_error (_("error writing keyring `%s': %s\n"),
 
739
                             keydb_get_resource_name (hd), gpg_strerror (rc) );
 
740
            else if(non_self)
 
741
              revalidation_mark ();
 
742
 
 
743
            /* we are ready */
 
744
            if( !opt.quiet ) {
 
745
                char *p=get_user_id_printable(keyid);
 
746
                if( n_uids == 1 )
 
747
                    log_info( _("key %08lX: \"%s\" 1 new user ID\n"),
 
748
                                             (ulong)keyid[1], p);
 
749
                else if( n_uids )
 
750
                    log_info( _("key %08lX: \"%s\" %d new user IDs\n"),
 
751
                                             (ulong)keyid[1], p, n_uids );
 
752
                if( n_sigs == 1 )
 
753
                    log_info( _("key %08lX: \"%s\" 1 new signature\n"),
 
754
                                             (ulong)keyid[1], p);
 
755
                else if( n_sigs )
 
756
                    log_info( _("key %08lX: \"%s\" %d new signatures\n"),
 
757
                                             (ulong)keyid[1], p, n_sigs );
 
758
                if( n_subk == 1 )
 
759
                    log_info( _("key %08lX: \"%s\" 1 new subkey\n"),
 
760
                                             (ulong)keyid[1], p);
 
761
                else if( n_subk )
 
762
                    log_info( _("key %08lX: \"%s\" %d new subkeys\n"),
 
763
                                             (ulong)keyid[1], p, n_subk );
 
764
                xfree (p);
 
765
            }
 
766
 
 
767
            stats->n_uids +=n_uids;
 
768
            stats->n_sigs +=n_sigs;
 
769
            stats->n_subk +=n_subk;
 
770
 
 
771
            if (is_status_enabled ()) 
 
772
                 print_import_ok (pk, NULL,
 
773
                                  ((n_uids?2:0)|(n_sigs?4:0)|(n_subk?8:0)));
 
774
        }
 
775
        else {
 
776
             if (is_status_enabled ()) 
 
777
                  print_import_ok (pk, NULL, 0);
 
778
        
 
779
            if( !opt.quiet ) {
 
780
                char *p=get_user_id_printable(keyid);
 
781
                log_info( _("key %08lX: \"%s\" not changed\n"),
 
782
                          (ulong)keyid[1],p);
 
783
                xfree (p);
 
784
            }
 
785
            stats->unchanged++;
 
786
        }
 
787
        keydb_release (hd); hd = NULL;
 
788
    }
 
789
 
 
790
  leave:
 
791
    release_kbnode( keyblock_orig );
 
792
    free_public_key( pk_orig );
 
793
 
 
794
    revocation_present(keyblock);
 
795
 
 
796
    return rc;
 
797
}
 
798
 
 
799
/* Walk a secret keyblock and produce a public keyblock out of it. */
 
800
static KBNODE
 
801
sec_to_pub_keyblock(KBNODE sec_keyblock)
 
802
{
 
803
  KBNODE secnode,pub_keyblock=NULL,ctx=NULL;
 
804
 
 
805
  while((secnode=walk_kbnode(sec_keyblock,&ctx,0)))
 
806
    {
 
807
      KBNODE pubnode;
 
808
 
 
809
      if(secnode->pkt->pkttype==PKT_SECRET_KEY ||
 
810
         secnode->pkt->pkttype==PKT_SECRET_SUBKEY)
 
811
        {
 
812
          /* Make a public key.  We only need to convert enough to
 
813
             write the keyblock out. */
 
814
 
 
815
          PKT_secret_key *sk=secnode->pkt->pkt.secret_key;
 
816
          PACKET *pkt=xcalloc (1,sizeof(PACKET));
 
817
          PKT_public_key *pk=xcalloc (1,sizeof(PKT_public_key));
 
818
          int n;
 
819
 
 
820
          if(secnode->pkt->pkttype==PKT_SECRET_KEY)
 
821
            pkt->pkttype=PKT_PUBLIC_KEY;
 
822
          else
 
823
            pkt->pkttype=PKT_PUBLIC_SUBKEY;
 
824
 
 
825
          pkt->pkt.public_key=pk;
 
826
 
 
827
          pk->version=sk->version;
 
828
          pk->timestamp=sk->timestamp;
 
829
          pk->expiredate=sk->expiredate;
 
830
          pk->pubkey_algo=sk->pubkey_algo;
 
831
 
 
832
          n=pubkey_get_npkey(pk->pubkey_algo);
 
833
          if(n==0)
 
834
            pk->pkey[0]=mpi_copy(sk->skey[0]);
 
835
          else
 
836
            {
 
837
              int i;
 
838
 
 
839
              for(i=0;i<n;i++)
 
840
                pk->pkey[i]=mpi_copy(sk->skey[i]);
 
841
            }
 
842
 
 
843
          pubnode=new_kbnode(pkt);
 
844
        }
 
845
      else
 
846
        {
 
847
          pubnode=clone_kbnode(secnode);
 
848
        }
 
849
 
 
850
      if(pub_keyblock==NULL)
 
851
        pub_keyblock=pubnode;
 
852
      else
 
853
        add_kbnode(pub_keyblock,pubnode);
 
854
    }
 
855
 
 
856
  return pub_keyblock;
 
857
}
 
858
 
 
859
/****************
 
860
 * Ditto for secret keys.  Handling is simpler than for public keys.
 
861
 * We allow secret key importing only when allow is true, this is so
 
862
 * that a secret key can not be imported accidently and thereby tampering
 
863
 * with the trust calculation.
 
864
 */
 
865
static int
 
866
import_secret_one( const char *fname, KBNODE keyblock, 
 
867
                   struct stats_s *stats, unsigned int options)
 
868
{
 
869
    PKT_secret_key *sk;
 
870
    KBNODE node, uidnode;
 
871
    u32 keyid[2];
 
872
    int rc = 0;
 
873
 
 
874
    /* get the key and print some info about it */
 
875
    node = find_kbnode( keyblock, PKT_SECRET_KEY );
 
876
    if( !node )
 
877
        BUG();
 
878
 
 
879
    sk = node->pkt->pkt.secret_key;
 
880
    keyid_from_sk( sk, keyid );
 
881
    uidnode = find_next_kbnode( keyblock, PKT_USER_ID );
 
882
 
 
883
    if( opt.verbose ) {
 
884
        log_info( "sec  %4u%c/%08lX %s   ",
 
885
                  nbits_from_sk( sk ),
 
886
                  pubkey_letter( sk->pubkey_algo ),
 
887
                  (ulong)keyid[1], datestr_from_sk(sk) );
 
888
        if( uidnode )
 
889
            print_utf8_string( stderr, uidnode->pkt->pkt.user_id->name,
 
890
                                       uidnode->pkt->pkt.user_id->len );
 
891
        putc('\n', stderr);
 
892
    }
 
893
    stats->secret_read++;
 
894
 
 
895
    if( !uidnode ) {
 
896
        log_error( _("key %08lX: no user ID\n"), (ulong)keyid[1]);
 
897
        return 0;
 
898
    }
 
899
 
 
900
    if(sk->protect.algo>110)
 
901
      {
 
902
        log_error(_("key %08lX: secret key with invalid cipher %d "
 
903
                    "- skipped\n"),(ulong)keyid[1],sk->protect.algo);
 
904
        return 0;
 
905
      }
 
906
 
 
907
    clear_kbnode_flags( keyblock );
 
908
 
 
909
    /* do we have this key already in one of our secrings ? */
 
910
    rc = seckey_available( keyid );
 
911
    if( gpg_err_code (rc) == GPG_ERR_NO_SECKEY && !opt.merge_only ) { 
 
912
        /* simply insert this key */
 
913
        KEYDB_HANDLE hd = keydb_new (1);
 
914
 
 
915
        /* get default resource */
 
916
        rc = keydb_locate_writable (hd, NULL);
 
917
        if (rc) {
 
918
            log_error (_("no default secret keyring: %s\n"), gpg_strerror (rc));
 
919
            keydb_release (hd);
 
920
            return GPG_ERR_GENERAL;
 
921
        }
 
922
        rc = keydb_insert_keyblock (hd, keyblock );
 
923
        if (rc)
 
924
            log_error (_("error writing keyring `%s': %s\n"),
 
925
                       keydb_get_resource_name (hd), gpg_strerror (rc) );
 
926
        keydb_release (hd);
 
927
        /* we are ready */
 
928
        if( !opt.quiet )
 
929
            log_info( _("key %08lX: secret key imported\n"), (ulong)keyid[1]);
 
930
        stats->secret_imported++;
 
931
        if (is_status_enabled ()) 
 
932
             print_import_ok (NULL, sk, 1|16);
 
933
 
 
934
        if(options&IMPORT_SK2PK)
 
935
          {
 
936
            /* Try and make a public key out of this. */
 
937
 
 
938
            KBNODE pub_keyblock=sec_to_pub_keyblock(keyblock);
 
939
            import_one(fname,pub_keyblock,stats,opt.import_options);
 
940
            release_kbnode(pub_keyblock);
 
941
          }
 
942
 
 
943
    }
 
944
    else if( !rc ) { /* we can't merge secret keys */
 
945
        log_error( _("key %08lX: already in secret keyring\n"),
 
946
                                                        (ulong)keyid[1]);
 
947
        stats->secret_dups++;
 
948
        if (is_status_enabled ()) 
 
949
             print_import_ok (NULL, sk, 16);
 
950
 
 
951
        /* TODO: if we ever do merge secret keys, make sure to handle
 
952
           the sec_to_pub_keyblock feature as well. */
 
953
    }
 
954
    else
 
955
        log_error( _("key %08lX: secret key not found: %s\n"),
 
956
                                (ulong)keyid[1], gpg_strerror (rc));
 
957
 
 
958
    return rc;
 
959
}
 
960
 
 
961
 
 
962
/****************
 
963
 * Import a revocation certificate; this is a single signature packet.
 
964
 */
 
965
static int
 
966
import_revoke_cert( const char *fname, KBNODE node, struct stats_s *stats )
 
967
{
 
968
    PKT_public_key *pk=NULL;
 
969
    KBNODE onode, keyblock = NULL;
 
970
    KEYDB_HANDLE hd = NULL;
 
971
    u32 keyid[2];
 
972
    int rc = 0;
 
973
 
 
974
    assert( !node->next );
 
975
    assert( node->pkt->pkttype == PKT_SIGNATURE );
 
976
    assert( node->pkt->pkt.signature->sig_class == 0x20 );
 
977
 
 
978
    keyid[0] = node->pkt->pkt.signature->keyid[0];
 
979
    keyid[1] = node->pkt->pkt.signature->keyid[1];
 
980
 
 
981
    pk = xcalloc (1, sizeof *pk );
 
982
    rc = get_pubkey( pk, keyid );
 
983
    if( gpg_err_code (rc) == GPG_ERR_NO_PUBKEY ) {
 
984
        log_error ( _("key %08lX: no public key - "
 
985
                      "can't apply revocation certificate\n"), (ulong)keyid[1]);
 
986
        rc = 0;
 
987
        goto leave;
 
988
    }
 
989
    else if( rc ) {
 
990
        log_error( _("key %08lX: public key not found: %s\n"),
 
991
                                       (ulong)keyid[1], gpg_strerror (rc));
 
992
        goto leave;
 
993
    }
 
994
 
 
995
    /* read the original keyblock */
 
996
    hd = keydb_new (0);
 
997
    {
 
998
        byte afp[MAX_FINGERPRINT_LEN];
 
999
        size_t an;
 
1000
        
 
1001
        fingerprint_from_pk (pk, afp, &an);
 
1002
        while (an < MAX_FINGERPRINT_LEN) 
 
1003
            afp[an++] = 0;
 
1004
        rc = keydb_search_fpr (hd, afp);
 
1005
    }
 
1006
    if (rc) {
 
1007
        log_error (_("key %08lX: can't locate original keyblock: %s\n"),
 
1008
                   (ulong)keyid[1], gpg_strerror (rc));
 
1009
        goto leave;
 
1010
    }
 
1011
    rc = keydb_get_keyblock (hd, &keyblock );
 
1012
    if (rc) {
 
1013
        log_error (_("key %08lX: can't read original keyblock: %s\n"),
 
1014
                   (ulong)keyid[1], gpg_strerror (rc));
 
1015
        goto leave;
 
1016
    }
 
1017
 
 
1018
 
 
1019
    /* it is okay, that node is not in keyblock because
 
1020
     * check_key_signature works fine for sig_class 0x20 in this
 
1021
     * special case. */
 
1022
    rc = check_key_signature( keyblock, node, NULL);
 
1023
    if( rc ) {
 
1024
        log_error( _("key %08lX: invalid revocation certificate"
 
1025
                  ": %s - rejected\n"), (ulong)keyid[1], gpg_strerror (rc));
 
1026
        goto leave;
 
1027
    }
 
1028
 
 
1029
 
 
1030
    /* check whether we already have this */
 
1031
    for(onode=keyblock->next; onode; onode=onode->next ) {
 
1032
        if( onode->pkt->pkttype == PKT_USER_ID )
 
1033
            break;
 
1034
        else if( onode->pkt->pkttype == PKT_SIGNATURE
 
1035
                 && !cmp_signatures(node->pkt->pkt.signature,
 
1036
                                    onode->pkt->pkt.signature))
 
1037
          {
 
1038
            rc = 0;
 
1039
            goto leave; /* yes, we already know about it */
 
1040
          }
 
1041
    }
 
1042
 
 
1043
 
 
1044
    /* insert it */
 
1045
    insert_kbnode( keyblock, clone_kbnode(node), 0 );
 
1046
 
 
1047
    /* and write the keyblock back */
 
1048
    rc = keydb_update_keyblock (hd, keyblock );
 
1049
    if (rc)
 
1050
        log_error (_("error writing keyring `%s': %s\n"),
 
1051
                   keydb_get_resource_name (hd), gpg_strerror (rc) );
 
1052
    keydb_release (hd); hd = NULL;
 
1053
    /* we are ready */
 
1054
    if( !opt.quiet ) {
 
1055
        char *p=get_user_id_printable (keyid);
 
1056
        log_info( _("key %08lX: \"%s\" revocation certificate imported\n"),
 
1057
                                        (ulong)keyid[1],p);
 
1058
        xfree (p);
 
1059
    }
 
1060
    stats->n_revoc++;
 
1061
 
 
1062
    /* If the key we just revoked was ultimately trusted, remove its
 
1063
       ultimate trust.  This doesn't stop the user from putting the
 
1064
       ultimate trust back, but is a reasonable solution for now. */
 
1065
    if(get_ownertrust(pk)==TRUST_ULTIMATE)
 
1066
      clear_ownertrusts(pk);
 
1067
 
 
1068
    revalidation_mark ();
 
1069
 
 
1070
  leave:
 
1071
    keydb_release (hd);
 
1072
    release_kbnode( keyblock );
 
1073
    free_public_key( pk );
 
1074
    return rc;
 
1075
}
 
1076
 
 
1077
 
 
1078
/****************
 
1079
 * loop over the keyblock and check all self signatures.
 
1080
 * Mark all user-ids with a self-signature by setting flag bit 0.
 
1081
 * Mark all user-ids with an invalid self-signature by setting bit 1.
 
1082
 * This works also for subkeys, here the subkey is marked.  Invalid or
 
1083
 * extra subkey sigs (binding or revocation) are marked for deletion.
 
1084
 * non_self is set to true if there are any sigs other than self-sigs
 
1085
 * in this keyblock.
 
1086
 */
 
1087
static int
 
1088
chk_self_sigs( const char *fname, KBNODE keyblock,
 
1089
               PKT_public_key *pk, u32 *keyid, int *non_self )
 
1090
{
 
1091
    KBNODE n,knode=NULL;
 
1092
    PKT_signature *sig;
 
1093
    int rc;
 
1094
    u32 bsdate=0,rsdate=0;
 
1095
    KBNODE bsnode=NULL,rsnode=NULL;
 
1096
 
 
1097
    for( n=keyblock; (n = find_next_kbnode(n, 0)); ) {
 
1098
      if(n->pkt->pkttype==PKT_PUBLIC_SUBKEY)
 
1099
        {
 
1100
          knode=n;
 
1101
          bsdate=0;
 
1102
          rsdate=0;
 
1103
          bsnode=NULL;
 
1104
          rsnode=NULL;
 
1105
          continue;
 
1106
        }
 
1107
      else if( n->pkt->pkttype != PKT_SIGNATURE )
 
1108
            continue;
 
1109
        sig = n->pkt->pkt.signature;
 
1110
        if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] ) {
 
1111
 
 
1112
          /* This just caches the sigs for later use.  That way we
 
1113
             import a fully-cached key which speeds things up. */
 
1114
          if(!opt.no_sig_cache)
 
1115
            check_key_signature(keyblock,n,NULL);
 
1116
 
 
1117
            if( (sig->sig_class&~3) == 0x10 ) {
 
1118
                KBNODE unode = find_prev_kbnode( keyblock, n, PKT_USER_ID );
 
1119
                if( !unode )  {
 
1120
                    log_error( _("key %08lX: no user ID for signature\n"),
 
1121
                                            (ulong)keyid[1]);
 
1122
                    return -1;  /* the complete keyblock is invalid */
 
1123
                }
 
1124
 
 
1125
                /* If it hasn't been marked valid yet, keep trying */
 
1126
                if(!(unode->flag&1)) {
 
1127
                  rc = check_key_signature( keyblock, n, NULL);
 
1128
                  if( rc )
 
1129
                    {
 
1130
                      if (opt.verbose)
 
1131
                        {
 
1132
                          char *p=utf8_to_native(unode->pkt->pkt.user_id->name,
 
1133
                                       strlen(unode->pkt->pkt.user_id->name),0);
 
1134
                          log_info( gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
 
1135
                                    _("key %08lX: unsupported public key "
 
1136
                                      "algorithm on user id \"%s\"\n"):
 
1137
                                    _("key %08lX: invalid self-signature "
 
1138
                                      "on user id \"%s\"\n"),
 
1139
                                    (ulong)keyid[1],p);
 
1140
                          xfree (p);
 
1141
                        }
 
1142
                    }
 
1143
                  else
 
1144
                    unode->flag |= 1; /* mark that signature checked */
 
1145
                }
 
1146
            }
 
1147
            else if( sig->sig_class == 0x18 ) {
 
1148
              /* Note that this works based solely on the timestamps
 
1149
                 like the rest of gpg.  If the standard gets
 
1150
                 revocation targets, this may need to be revised. */
 
1151
 
 
1152
                if( !knode )
 
1153
                  {
 
1154
                    if (opt.verbose)
 
1155
                      log_info( _("key %08lX: no subkey for subkey "
 
1156
                                  "binding signature\n"),(ulong)keyid[1]);
 
1157
                    n->flag |= 4; /* delete this */
 
1158
                  }
 
1159
                else
 
1160
                  {
 
1161
                    rc = check_key_signature( keyblock, n, NULL);
 
1162
                    if( rc )
 
1163
                      {
 
1164
                        if (opt.verbose)
 
1165
                          log_info(  gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
 
1166
                            _("key %08lX: unsupported public key algorithm\n"):
 
1167
                            _("key %08lX: invalid subkey binding\n"),
 
1168
                                     (ulong)keyid[1]);
 
1169
                        n->flag|=4;
 
1170
                      }
 
1171
                    else
 
1172
                      {
 
1173
                        /* It's valid, so is it newer? */
 
1174
                        if(sig->timestamp>=bsdate) 
 
1175
                          {
 
1176
                            knode->flag |= 1;  /* the subkey is valid */
 
1177
                            if(bsnode)
 
1178
                              {
 
1179
                                bsnode->flag|=4; /* Delete the last binding
 
1180
                                                    sig since this one is
 
1181
                                                    newer */
 
1182
                                if (opt.verbose)
 
1183
                                  log_info(_("key %08lX: removed multiple "
 
1184
                                             "subkey binding\n"),
 
1185
                                           (ulong)keyid[1]);
 
1186
                              }
 
1187
                            
 
1188
                            bsnode=n;
 
1189
                            bsdate=sig->timestamp;
 
1190
                          }
 
1191
                        else
 
1192
                          n->flag|=4; /* older */
 
1193
                      }
 
1194
                  }
 
1195
            }
 
1196
            else if( sig->sig_class == 0x28 ) {
 
1197
              /* We don't actually mark the subkey as revoked right
 
1198
                 now, so just check that the revocation sig is the
 
1199
                 most recent valid one.  Note that we don't care if
 
1200
                 the binding sig is newer than the revocation sig.
 
1201
                 See the comment in getkey.c:merge_selfsigs_subkey for
 
1202
                 more */
 
1203
                if( !knode ) {
 
1204
                  if (opt.verbose)
 
1205
                    log_info( _("key %08lX: no subkey for subkey "
 
1206
                                "revocation signature\n"),(ulong)keyid[1]);
 
1207
                  n->flag |= 4; /* delete this */
 
1208
                }
 
1209
                else {
 
1210
                  rc = check_key_signature( keyblock, n, NULL);
 
1211
                  if( rc ) {
 
1212
                    if (opt.verbose)
 
1213
                      log_info(  gpg_err_code (rc) == GPG_ERR_PUBKEY_ALGO ?
 
1214
                            _("key %08lX: unsupported public key algorithm\n"):
 
1215
                            _("key %08lX: invalid subkey revocation\n"),
 
1216
                               (ulong)keyid[1]);
 
1217
                    n->flag|=4;
 
1218
                  }
 
1219
                  else {
 
1220
                    /* It's valid, so is it newer? */
 
1221
                    if(sig->timestamp>=rsdate) {
 
1222
                      if(rsnode) {
 
1223
                        rsnode->flag|=4; /* Delete the last revocation
 
1224
                                            sig since this one is
 
1225
                                            newer */
 
1226
                        if (opt.verbose)
 
1227
                          log_info(_("key %08lX: removed multiple subkey "
 
1228
                                     "revocation signatures\n"),
 
1229
                                   (ulong)keyid[1]);
 
1230
                      }
 
1231
 
 
1232
                      rsnode=n;
 
1233
                      rsdate=sig->timestamp;
 
1234
                    }
 
1235
                    else
 
1236
                      n->flag|=4; /* older */
 
1237
                  }
 
1238
                }
 
1239
            }
 
1240
        }
 
1241
        else
 
1242
          *non_self=1;
 
1243
    }
 
1244
 
 
1245
    return 0;
 
1246
}
 
1247
 
 
1248
/****************
 
1249
 * delete all parts which are invalid and those signatures whose
 
1250
 * public key algorithm is not available in this implemenation;
 
1251
 * but consider RSA as valid, because parse/build_packets knows
 
1252
 * about it.
 
1253
 * returns: true if at least one valid user-id is left over.
 
1254
 */
 
1255
static int
 
1256
delete_inv_parts( const char *fname, KBNODE keyblock,
 
1257
                  u32 *keyid, unsigned int options)
 
1258
{
 
1259
    KBNODE node;
 
1260
    int nvalid=0, uid_seen=0, subkey_seen=0;
 
1261
 
 
1262
    for(node=keyblock->next; node; node = node->next ) {
 
1263
        if( node->pkt->pkttype == PKT_USER_ID ) {
 
1264
            uid_seen = 1;
 
1265
            if( (node->flag & 2) || !(node->flag & 1) ) {
 
1266
                if( opt.verbose ) {
 
1267
                    log_info( _("key %08lX: skipped user ID '"),
 
1268
                                                         (ulong)keyid[1]);
 
1269
                    print_utf8_string( stderr, node->pkt->pkt.user_id->name,
 
1270
                                       node->pkt->pkt.user_id->len );
 
1271
                    fputs("'\n", stderr );
 
1272
                }
 
1273
                delete_kbnode( node ); /* the user-id */
 
1274
                /* and all following packets up to the next user-id */
 
1275
                while( node->next
 
1276
                       && node->next->pkt->pkttype != PKT_USER_ID
 
1277
                       && node->next->pkt->pkttype != PKT_PUBLIC_SUBKEY
 
1278
                       && node->next->pkt->pkttype != PKT_SECRET_SUBKEY ){
 
1279
                    delete_kbnode( node->next );
 
1280
                    node = node->next;
 
1281
                }
 
1282
            }
 
1283
            else
 
1284
                nvalid++;
 
1285
        }
 
1286
        else if(    node->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1287
                 || node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
 
1288
            if( (node->flag & 2) || !(node->flag & 1) ) {
 
1289
                if( opt.verbose ) {
 
1290
                    log_info( _("key %08lX: skipped subkey\n"),
 
1291
                                                         (ulong)keyid[1]);
 
1292
                }
 
1293
                delete_kbnode( node ); /* the subkey */
 
1294
                /* and all following signature packets */
 
1295
                while( node->next
 
1296
                       && node->next->pkt->pkttype == PKT_SIGNATURE ) {
 
1297
                    delete_kbnode( node->next );
 
1298
                    node = node->next;
 
1299
                }
 
1300
            }
 
1301
            else
 
1302
              subkey_seen = 1;
 
1303
        }
 
1304
        else if( node->pkt->pkttype == PKT_SIGNATURE
 
1305
                 && openpgp_pk_test_algo( node->pkt->pkt.signature
 
1306
                                                     ->pubkey_algo, 0)
 
1307
                 && node->pkt->pkt.signature->pubkey_algo != PUBKEY_ALGO_RSA )
 
1308
            delete_kbnode( node ); /* build_packet() can't handle this */
 
1309
        else if( node->pkt->pkttype == PKT_SIGNATURE &&
 
1310
                 !node->pkt->pkt.signature->flags.exportable &&
 
1311
                 !(options&IMPORT_ALLOW_LOCAL_SIGS) &&
 
1312
                 seckey_available( node->pkt->pkt.signature->keyid ) ) {
 
1313
            /* Here we violate the rfc a bit by still allowing
 
1314
             * to import non-exportable signature when we have the
 
1315
             * the secret key used to create this signature - it
 
1316
             * seems that this makes sense. */
 
1317
          if (opt.verbose)
 
1318
            log_info( _("key %08lX: non exportable signature "
 
1319
                                    "(class %02x) - skipped\n"),
 
1320
                      (ulong)keyid[1],
 
1321
                                     node->pkt->pkt.signature->sig_class );
 
1322
          delete_kbnode( node );
 
1323
        }
 
1324
        else if( node->pkt->pkttype == PKT_SIGNATURE
 
1325
                 && node->pkt->pkt.signature->sig_class == 0x20 )  {
 
1326
            if( uid_seen ) {
 
1327
              if (opt.verbose)
 
1328
                log_error( _("key %08lX: revocation certificate "
 
1329
                             "at wrong place - skipped\n"),
 
1330
                                    (ulong)keyid[1]);
 
1331
              delete_kbnode( node );
 
1332
            }
 
1333
            else {
 
1334
              /* If the revocation cert is from a different key than
 
1335
                 the one we're working on don't check it - it's
 
1336
                 probably from a revocation key and won't be
 
1337
                 verifiable with this key anyway. */
 
1338
 
 
1339
              if(node->pkt->pkt.signature->keyid[0]==keyid[0] &&
 
1340
                 node->pkt->pkt.signature->keyid[1]==keyid[1])
 
1341
                {
 
1342
                  int rc = check_key_signature( keyblock, node, NULL);
 
1343
                  if( rc )
 
1344
                    {
 
1345
                      if (opt.verbose)
 
1346
                        log_info ( _("key %08lX: invalid revocation "
 
1347
                                     "certificate: %s - skipped\n"),
 
1348
                                   (ulong)keyid[1], gpg_strerror (rc));
 
1349
                      delete_kbnode( node );
 
1350
                    }
 
1351
                }
 
1352
            }
 
1353
        }
 
1354
        else if( node->pkt->pkttype == PKT_SIGNATURE &&
 
1355
                 (node->pkt->pkt.signature->sig_class == 0x18 ||
 
1356
                  node->pkt->pkt.signature->sig_class == 0x28) &&
 
1357
                 !subkey_seen ) {
 
1358
          if (opt.verbose)
 
1359
            log_info ( _("key %08lX: subkey signature "
 
1360
                         "in wrong place - skipped\n"),
 
1361
                       (ulong)keyid[1]);
 
1362
          delete_kbnode( node );
 
1363
        }
 
1364
        else if( node->pkt->pkttype == PKT_SIGNATURE
 
1365
                 && !IS_CERT(node->pkt->pkt.signature))
 
1366
          {
 
1367
            if (opt.verbose)
 
1368
              log_info (_("key %08lX: unexpected signature class (0x%02X) -"
 
1369
                          " skipped\n"),(ulong)keyid[1],
 
1370
                        node->pkt->pkt.signature->sig_class);
 
1371
            delete_kbnode(node);
 
1372
          }
 
1373
        else if( (node->flag & 4) ) /* marked for deletion */
 
1374
            delete_kbnode( node );
 
1375
    }
 
1376
 
 
1377
    /* note: because keyblock is the public key, it is never marked
 
1378
     * for deletion and so keyblock cannot change */
 
1379
    commit_kbnode( &keyblock );
 
1380
    return nvalid;
 
1381
}
 
1382
 
 
1383
 
 
1384
/****************
 
1385
 * It may happen that the imported keyblock has duplicated user IDs.
 
1386
 * We check this here and collapse those user IDs together with their
 
1387
 * sigs into one.
 
1388
 * Returns: True if the keyblock hash changed.
 
1389
 */
 
1390
int
 
1391
collapse_uids( KBNODE *keyblock )
 
1392
{
 
1393
    KBNODE n, n2;
 
1394
    int in_uid;
 
1395
    int any=0;
 
1396
    u32 kid1;
 
1397
 
 
1398
  restart:
 
1399
    for( n = *keyblock; n; n = n->next ) {
 
1400
        if( n->pkt->pkttype != PKT_USER_ID )
 
1401
            continue;
 
1402
        for( n2 = n->next; n2; n2 = n2->next ) {
 
1403
            if( n2->pkt->pkttype == PKT_USER_ID
 
1404
                && !cmp_user_ids( n->pkt->pkt.user_id,
 
1405
                                  n2->pkt->pkt.user_id ) ) {
 
1406
                /* found a duplicate */
 
1407
                any = 1;
 
1408
                if( !n2->next
 
1409
                    || n2->next->pkt->pkttype == PKT_USER_ID
 
1410
                    || n2->next->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1411
                    || n2->next->pkt->pkttype == PKT_SECRET_SUBKEY  ) {
 
1412
                    /* no more signatures: delete the user ID
 
1413
                     * and start over */
 
1414
                    remove_kbnode( keyblock, n2 );
 
1415
                }
 
1416
                else {
 
1417
                    /* The simple approach: Move one signature and
 
1418
                     * then start over to delete the next one :-( */
 
1419
                    move_kbnode( keyblock, n2->next, n->next );
 
1420
                }
 
1421
                goto restart;
 
1422
            }
 
1423
        }
 
1424
    }
 
1425
    if( !any )
 
1426
        return 0;
 
1427
 
 
1428
  restart_sig:
 
1429
    /* now we may have duplicate signatures on one user ID: fix this */
 
1430
    for( in_uid = 0, n = *keyblock; n; n = n->next ) {
 
1431
        if( n->pkt->pkttype == PKT_USER_ID )
 
1432
            in_uid = 1;
 
1433
        else if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1434
                 || n->pkt->pkttype == PKT_SECRET_SUBKEY )
 
1435
            in_uid = 0;
 
1436
        else if( in_uid ) {
 
1437
            n2 = n;
 
1438
            do {
 
1439
                KBNODE ncmp = NULL;
 
1440
                for( ; n2; n2 = n2->next ) {
 
1441
                    if(    n2->pkt->pkttype == PKT_USER_ID
 
1442
                        || n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1443
                        || n2->pkt->pkttype == PKT_SECRET_SUBKEY )
 
1444
                        break;
 
1445
                    if( n2->pkt->pkttype != PKT_SIGNATURE )
 
1446
                        ;
 
1447
                    else if( !ncmp )
 
1448
                        ncmp = n2;
 
1449
                    else if( !cmp_signatures( ncmp->pkt->pkt.signature,
 
1450
                                                n2->pkt->pkt.signature )) {
 
1451
                        remove_kbnode( keyblock, n2 );
 
1452
                        goto restart_sig;
 
1453
                    }
 
1454
                }
 
1455
                n2 = ncmp? ncmp->next : NULL;
 
1456
            } while( n2 );
 
1457
        }
 
1458
    }
 
1459
 
 
1460
    if( (n = find_kbnode( *keyblock, PKT_PUBLIC_KEY )) )
 
1461
        kid1 = keyid_from_pk( n->pkt->pkt.public_key, NULL );
 
1462
    else if( (n = find_kbnode( *keyblock, PKT_SECRET_KEY )) )
 
1463
        kid1 = keyid_from_sk( n->pkt->pkt.secret_key, NULL );
 
1464
    else
 
1465
        kid1 = 0;
 
1466
    if (!opt.quiet)
 
1467
      log_info (_("key %08lX: duplicated user ID detected - merged\n"),
 
1468
                (ulong)kid1);
 
1469
 
 
1470
    return 1;
 
1471
}
 
1472
 
 
1473
/* Check for a 0x20 revocation from a revocation key that is not
 
1474
   present.  This gets called without the benefit of merge_xxxx so you
 
1475
   can't rely on pk->revkey and friends. */
 
1476
static void
 
1477
revocation_present(KBNODE keyblock)
 
1478
{
 
1479
  KBNODE onode,inode;
 
1480
  PKT_public_key *pk=keyblock->pkt->pkt.public_key;
 
1481
 
 
1482
  for(onode=keyblock->next;onode;onode=onode->next)
 
1483
    {
 
1484
      /* If we reach user IDs, we're done. */
 
1485
      if(onode->pkt->pkttype==PKT_USER_ID)
 
1486
        break;
 
1487
 
 
1488
      if(onode->pkt->pkttype==PKT_SIGNATURE &&
 
1489
         onode->pkt->pkt.signature->sig_class==0x1F &&
 
1490
         onode->pkt->pkt.signature->revkey)
 
1491
        {
 
1492
          int idx;
 
1493
          PKT_signature *sig=onode->pkt->pkt.signature;
 
1494
 
 
1495
          for(idx=0;idx<sig->numrevkeys;idx++)
 
1496
            {
 
1497
              u32 keyid[2];
 
1498
 
 
1499
              keyid_from_fingerprint(sig->revkey[idx]->fpr,
 
1500
                                     MAX_FINGERPRINT_LEN,keyid);
 
1501
 
 
1502
              for(inode=keyblock->next;inode;inode=inode->next)
 
1503
                {
 
1504
                  /* If we reach user IDs, we're done. */
 
1505
                  if(inode->pkt->pkttype==PKT_USER_ID)
 
1506
                    break;
 
1507
 
 
1508
                  if(inode->pkt->pkttype==PKT_SIGNATURE &&
 
1509
                     inode->pkt->pkt.signature->sig_class==0x20 &&
 
1510
                     inode->pkt->pkt.signature->keyid[0]==keyid[0] &&
 
1511
                     inode->pkt->pkt.signature->keyid[1]==keyid[1])
 
1512
                    {
 
1513
                      /* Okay, we have a revocation key, and a
 
1514
                         revocation issued by it.  Do we have the key
 
1515
                         itself? */
 
1516
                      int rc;
 
1517
 
 
1518
                      rc=get_pubkey_byfprint_fast (NULL,sig->revkey[idx]->fpr,
 
1519
                                                   MAX_FINGERPRINT_LEN);
 
1520
                      if ( gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
 
1521
                          || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
 
1522
                        {
 
1523
                          /* No, so try and get it */
 
1524
                          if(opt.keyserver_scheme &&
 
1525
                             opt.keyserver_options.auto_key_retrieve)
 
1526
                            {
 
1527
                              log_info(_("WARNING: key %08lX may be revoked: "
 
1528
                                         "fetching revocation key %08lX\n"),
 
1529
                                       (ulong)keyid_from_pk(pk,NULL),
 
1530
                                       (ulong)keyid[1]);
 
1531
                              keyserver_import_fprint(sig->revkey[idx]->fpr,
 
1532
                                                      MAX_FINGERPRINT_LEN);
 
1533
 
 
1534
                              /* Do we have it now? */
 
1535
                              rc=get_pubkey_byfprint_fast (NULL,
 
1536
                                                     sig->revkey[idx]->fpr,
 
1537
                                                     MAX_FINGERPRINT_LEN);
 
1538
                            }
 
1539
 
 
1540
                          if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
 
1541
                              || gpg_err_code (rc) == GPG_ERR_UNUSABLE_PUBKEY)
 
1542
                            log_info(_("WARNING: key %08lX may be revoked: "
 
1543
                                       "revocation key %08lX not present.\n"),
 
1544
                                     (ulong)keyid_from_pk(pk,NULL),
 
1545
                                     (ulong)keyid[1]);
 
1546
                        }
 
1547
                    }
 
1548
                }
 
1549
            }
 
1550
        }
 
1551
    }
 
1552
}
 
1553
 
 
1554
/****************
 
1555
 * compare and merge the blocks
 
1556
 *
 
1557
 * o compare the signatures: If we already have this signature, check
 
1558
 *   that they compare okay; if not, issue a warning and ask the user.
 
1559
 * o Simply add the signature.  Can't verify here because we may not have
 
1560
 *   the signature's public key yet; verification is done when putting it
 
1561
 *   into the trustdb, which is done automagically as soon as this pubkey
 
1562
 *   is used.
 
1563
 * Note: We indicate newly inserted packets with flag bit 0
 
1564
 */
 
1565
static int
 
1566
merge_blocks( const char *fname, KBNODE keyblock_orig, KBNODE keyblock,
 
1567
              u32 *keyid, int *n_uids, int *n_sigs, int *n_subk )
 
1568
{
 
1569
    KBNODE onode, node;
 
1570
    int rc, found;
 
1571
 
 
1572
    /* 1st: handle revocation certificates */
 
1573
    for(node=keyblock->next; node; node=node->next ) {
 
1574
        if( node->pkt->pkttype == PKT_USER_ID )
 
1575
            break;
 
1576
        else if( node->pkt->pkttype == PKT_SIGNATURE
 
1577
                 && node->pkt->pkt.signature->sig_class == 0x20 )  {
 
1578
            /* check whether we already have this */
 
1579
            found = 0;
 
1580
            for(onode=keyblock_orig->next; onode; onode=onode->next ) {
 
1581
                if( onode->pkt->pkttype == PKT_USER_ID )
 
1582
                    break;
 
1583
                else if( onode->pkt->pkttype == PKT_SIGNATURE
 
1584
                         && onode->pkt->pkt.signature->sig_class == 0x20
 
1585
                         && !cmp_signatures(onode->pkt->pkt.signature,
 
1586
                                            node->pkt->pkt.signature))
 
1587
                  {
 
1588
                    found = 1;
 
1589
                    break;
 
1590
                  }
 
1591
            }
 
1592
            if( !found ) {
 
1593
                KBNODE n2 = clone_kbnode(node);
 
1594
                insert_kbnode( keyblock_orig, n2, 0 );
 
1595
                n2->flag |= 1;
 
1596
                ++*n_sigs;
 
1597
 
 
1598
                if (!opt.quiet)
 
1599
                  {
 
1600
                    char *p=get_user_id_printable (keyid);
 
1601
                    log_info(_("key %08lX: \"%s\" "
 
1602
                               "revocation certificate added\n"),
 
1603
                             (ulong)keyid[1],p);
 
1604
                    xfree (p);
 
1605
                  }
 
1606
            }
 
1607
        }
 
1608
    }
 
1609
 
 
1610
    /* 2nd: merge in any direct key (0x1F) sigs */
 
1611
    for(node=keyblock->next; node; node=node->next ) {
 
1612
        if( node->pkt->pkttype == PKT_USER_ID )
 
1613
            break;
 
1614
        else if( node->pkt->pkttype == PKT_SIGNATURE
 
1615
                 && node->pkt->pkt.signature->sig_class == 0x1F )  {
 
1616
            /* check whether we already have this */
 
1617
            found = 0;
 
1618
            for(onode=keyblock_orig->next; onode; onode=onode->next ) {
 
1619
                if( onode->pkt->pkttype == PKT_USER_ID )
 
1620
                    break;
 
1621
                else if( onode->pkt->pkttype == PKT_SIGNATURE
 
1622
                         && onode->pkt->pkt.signature->sig_class == 0x1F
 
1623
                         && !cmp_signatures(onode->pkt->pkt.signature,
 
1624
                                            node->pkt->pkt.signature)) {
 
1625
                    found = 1;
 
1626
                    break;
 
1627
                }
 
1628
            }
 
1629
            if( !found ) {
 
1630
                KBNODE n2 = clone_kbnode(node);
 
1631
                insert_kbnode( keyblock_orig, n2, 0 );
 
1632
                n2->flag |= 1;
 
1633
                ++*n_sigs;
 
1634
                if (!opt.quiet)
 
1635
                  log_info( _("key %08lX: direct key signature added\n"),
 
1636
                            (ulong)keyid[1]);
 
1637
            }
 
1638
        }
 
1639
    }
 
1640
 
 
1641
    /* 3rd: try to merge new certificates in */
 
1642
    for(onode=keyblock_orig->next; onode; onode=onode->next ) {
 
1643
        if( !(onode->flag & 1) && onode->pkt->pkttype == PKT_USER_ID) {
 
1644
            /* find the user id in the imported keyblock */
 
1645
            for(node=keyblock->next; node; node=node->next )
 
1646
                if( node->pkt->pkttype == PKT_USER_ID
 
1647
                    && !cmp_user_ids( onode->pkt->pkt.user_id,
 
1648
                                          node->pkt->pkt.user_id ) )
 
1649
                    break;
 
1650
            if( node ) { /* found: merge */
 
1651
                rc = merge_sigs( onode, node, n_sigs, fname, keyid );
 
1652
                if( rc )
 
1653
                    return rc;
 
1654
            }
 
1655
        }
 
1656
    }
 
1657
 
 
1658
    /* 4th: add new user-ids */
 
1659
    for(node=keyblock->next; node; node=node->next ) {
 
1660
        if( node->pkt->pkttype == PKT_USER_ID) {
 
1661
            /* do we have this in the original keyblock */
 
1662
            for(onode=keyblock_orig->next; onode; onode=onode->next )
 
1663
                if( onode->pkt->pkttype == PKT_USER_ID
 
1664
                    && !cmp_user_ids( onode->pkt->pkt.user_id,
 
1665
                                      node->pkt->pkt.user_id ) )
 
1666
                    break;
 
1667
            if( !onode ) { /* this is a new user id: append */
 
1668
                rc = append_uid( keyblock_orig, node, n_sigs, fname, keyid);
 
1669
                if( rc )
 
1670
                    return rc;
 
1671
                ++*n_uids;
 
1672
            }
 
1673
        }
 
1674
    }
 
1675
 
 
1676
    /* 5th: add new subkeys */
 
1677
    for(node=keyblock->next; node; node=node->next ) {
 
1678
        onode = NULL;
 
1679
        if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
 
1680
            /* do we have this in the original keyblock? */
 
1681
            for(onode=keyblock_orig->next; onode; onode=onode->next )
 
1682
                if( onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1683
                    && !cmp_public_keys( onode->pkt->pkt.public_key,
 
1684
                                         node->pkt->pkt.public_key ) )
 
1685
                    break;
 
1686
            if( !onode ) { /* this is a new subkey: append */
 
1687
                rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
 
1688
                if( rc )
 
1689
                    return rc;
 
1690
                ++*n_subk;
 
1691
            }
 
1692
        }
 
1693
        else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
 
1694
            /* do we have this in the original keyblock? */
 
1695
            for(onode=keyblock_orig->next; onode; onode=onode->next )
 
1696
                if( onode->pkt->pkttype == PKT_SECRET_SUBKEY
 
1697
                    && !cmp_secret_keys( onode->pkt->pkt.secret_key,
 
1698
                                         node->pkt->pkt.secret_key ) )
 
1699
                    break;
 
1700
            if( !onode ) { /* this is a new subkey: append */
 
1701
                rc = append_key( keyblock_orig, node, n_sigs, fname, keyid);
 
1702
                if( rc )
 
1703
                    return rc;
 
1704
                ++*n_subk;
 
1705
            }
 
1706
        }
 
1707
    }
 
1708
 
 
1709
    /* 6th: merge subkey certificates */
 
1710
    for(onode=keyblock_orig->next; onode; onode=onode->next ) {
 
1711
        if( !(onode->flag & 1)
 
1712
            &&  (   onode->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1713
                 || onode->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
 
1714
            /* find the subkey in the imported keyblock */
 
1715
            for(node=keyblock->next; node; node=node->next ) {
 
1716
                if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1717
                    && !cmp_public_keys( onode->pkt->pkt.public_key,
 
1718
                                          node->pkt->pkt.public_key ) )
 
1719
                    break;
 
1720
                else if( node->pkt->pkttype == PKT_SECRET_SUBKEY
 
1721
                    && !cmp_secret_keys( onode->pkt->pkt.secret_key,
 
1722
                                          node->pkt->pkt.secret_key ) )
 
1723
                    break;
 
1724
            }
 
1725
            if( node ) { /* found: merge */
 
1726
                rc = merge_keysigs( onode, node, n_sigs, fname, keyid );
 
1727
                if( rc )
 
1728
                    return rc;
 
1729
            }
 
1730
        }
 
1731
    }
 
1732
 
 
1733
 
 
1734
    return 0;
 
1735
}
 
1736
 
 
1737
 
 
1738
/****************
 
1739
 * append the userid starting with NODE and all signatures to KEYBLOCK.
 
1740
 */
 
1741
static int
 
1742
append_uid( KBNODE keyblock, KBNODE node, int *n_sigs,
 
1743
                                          const char *fname, u32 *keyid )
 
1744
{
 
1745
    KBNODE n, n_where=NULL;
 
1746
 
 
1747
    assert(node->pkt->pkttype == PKT_USER_ID );
 
1748
 
 
1749
    /* find the position */
 
1750
    for( n = keyblock; n; n_where = n, n = n->next ) {
 
1751
        if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1752
            || n->pkt->pkttype == PKT_SECRET_SUBKEY )
 
1753
            break;
 
1754
    }
 
1755
    if( !n )
 
1756
        n_where = NULL;
 
1757
 
 
1758
    /* and append/insert */
 
1759
    while( node ) {
 
1760
        /* we add a clone to the original keyblock, because this
 
1761
         * one is released first */
 
1762
        n = clone_kbnode(node);
 
1763
        if( n_where ) {
 
1764
            insert_kbnode( n_where, n, 0 );
 
1765
            n_where = n;
 
1766
        }
 
1767
        else
 
1768
            add_kbnode( keyblock, n );
 
1769
        n->flag |= 1;
 
1770
        node->flag |= 1;
 
1771
        if( n->pkt->pkttype == PKT_SIGNATURE )
 
1772
            ++*n_sigs;
 
1773
 
 
1774
        node = node->next;
 
1775
        if( node && node->pkt->pkttype != PKT_SIGNATURE )
 
1776
            break;
 
1777
    }
 
1778
 
 
1779
    return 0;
 
1780
}
 
1781
 
 
1782
 
 
1783
/****************
 
1784
 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_USER_ID.
 
1785
 * (how should we handle comment packets here?)
 
1786
 */
 
1787
static int
 
1788
merge_sigs( KBNODE dst, KBNODE src, int *n_sigs,
 
1789
                                    const char *fname, u32 *keyid )
 
1790
{
 
1791
    KBNODE n, n2;
 
1792
    int found=0;
 
1793
 
 
1794
    assert(dst->pkt->pkttype == PKT_USER_ID );
 
1795
    assert(src->pkt->pkttype == PKT_USER_ID );
 
1796
 
 
1797
    for(n=src->next; n && n->pkt->pkttype != PKT_USER_ID; n = n->next ) {
 
1798
        if( n->pkt->pkttype != PKT_SIGNATURE )
 
1799
            continue;
 
1800
        if( n->pkt->pkt.signature->sig_class == 0x18
 
1801
            || n->pkt->pkt.signature->sig_class == 0x28 )
 
1802
            continue; /* skip signatures which are only valid on subkeys */
 
1803
        found = 0;
 
1804
        for(n2=dst->next; n2 && n2->pkt->pkttype != PKT_USER_ID; n2 = n2->next)
 
1805
          if(!cmp_signatures(n->pkt->pkt.signature,n2->pkt->pkt.signature))
 
1806
            {
 
1807
              found++;
 
1808
              break;
 
1809
            }   
 
1810
        if( !found ) {
 
1811
            /* This signature is new or newer, append N to DST.
 
1812
             * We add a clone to the original keyblock, because this
 
1813
             * one is released first */
 
1814
            n2 = clone_kbnode(n);
 
1815
            insert_kbnode( dst, n2, PKT_SIGNATURE );
 
1816
            n2->flag |= 1;
 
1817
            n->flag |= 1;
 
1818
            ++*n_sigs;
 
1819
        }
 
1820
    }
 
1821
 
 
1822
    return 0;
 
1823
}
 
1824
 
 
1825
/****************
 
1826
 * Merge the sigs from SRC onto DST. SRC and DST are both a PKT_xxx_SUBKEY.
 
1827
 */
 
1828
static int
 
1829
merge_keysigs( KBNODE dst, KBNODE src, int *n_sigs,
 
1830
                                    const char *fname, u32 *keyid )
 
1831
{
 
1832
    KBNODE n, n2;
 
1833
    int found=0;
 
1834
 
 
1835
    assert(   dst->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1836
           || dst->pkt->pkttype == PKT_SECRET_SUBKEY );
 
1837
 
 
1838
    for(n=src->next; n ; n = n->next ) {
 
1839
        if( n->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1840
            || n->pkt->pkttype == PKT_PUBLIC_KEY )
 
1841
            break;
 
1842
        if( n->pkt->pkttype != PKT_SIGNATURE )
 
1843
            continue;
 
1844
        found = 0;
 
1845
        for(n2=dst->next; n2; n2 = n2->next){
 
1846
            if( n2->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1847
                || n2->pkt->pkttype == PKT_PUBLIC_KEY )
 
1848
                break;
 
1849
            if( n2->pkt->pkttype == PKT_SIGNATURE
 
1850
                && n->pkt->pkt.signature->keyid[0]
 
1851
                   == n2->pkt->pkt.signature->keyid[0]
 
1852
                && n->pkt->pkt.signature->keyid[1]
 
1853
                   == n2->pkt->pkt.signature->keyid[1]
 
1854
                && n->pkt->pkt.signature->timestamp
 
1855
                   <= n2->pkt->pkt.signature->timestamp
 
1856
                && n->pkt->pkt.signature->sig_class
 
1857
                   == n2->pkt->pkt.signature->sig_class ) {
 
1858
                found++;
 
1859
                break;
 
1860
            }
 
1861
        }
 
1862
        if( !found ) {
 
1863
            /* This signature is new or newer, append N to DST.
 
1864
             * We add a clone to the original keyblock, because this
 
1865
             * one is released first */
 
1866
            n2 = clone_kbnode(n);
 
1867
            insert_kbnode( dst, n2, PKT_SIGNATURE );
 
1868
            n2->flag |= 1;
 
1869
            n->flag |= 1;
 
1870
            ++*n_sigs;
 
1871
        }
 
1872
    }
 
1873
 
 
1874
    return 0;
 
1875
}
 
1876
 
 
1877
/****************
 
1878
 * append the subkey starting with NODE and all signatures to KEYBLOCK.
 
1879
 * Mark all new and copied packets by setting flag bit 0.
 
1880
 */
 
1881
static int
 
1882
append_key( KBNODE keyblock, KBNODE node, int *n_sigs,
 
1883
                                          const char *fname, u32 *keyid )
 
1884
{
 
1885
    KBNODE n;
 
1886
 
 
1887
    assert( node->pkt->pkttype == PKT_PUBLIC_SUBKEY
 
1888
           || node->pkt->pkttype == PKT_SECRET_SUBKEY );
 
1889
 
 
1890
    while(  node ) {
 
1891
        /* we add a clone to the original keyblock, because this
 
1892
         * one is released first */
 
1893
        n = clone_kbnode(node);
 
1894
        add_kbnode( keyblock, n );
 
1895
        n->flag |= 1;
 
1896
        node->flag |= 1;
 
1897
        if( n->pkt->pkttype == PKT_SIGNATURE )
 
1898
            ++*n_sigs;
 
1899
 
 
1900
        node = node->next;
 
1901
        if( node && node->pkt->pkttype != PKT_SIGNATURE )
 
1902
            break;
 
1903
    }
 
1904
 
 
1905
    return 0;
 
1906
}