Imported Upstream version 2.0.26
[platform/upstream/gpg2.git] / g10 / getkey.c
1 /* getkey.c -  Get a key from the database
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2007, 2008 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 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 <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
26 #include <ctype.h>
27
28 #include "gpg.h"
29 #include "util.h"
30 #include "packet.h"
31 #include "iobuf.h"
32 #include "keydb.h"
33 #include "options.h"
34 #include "main.h"
35 #include "trustdb.h"
36 #include "i18n.h"
37 #include "keyserver-internal.h"
38
39 #define MAX_PK_CACHE_ENTRIES   PK_UID_CACHE_SIZE
40 #define MAX_UID_CACHE_ENTRIES  PK_UID_CACHE_SIZE
41
42 #if MAX_PK_CACHE_ENTRIES < 2
43 #error We need the cache for key creation
44 #endif
45
46 struct getkey_ctx_s {
47     int exact;
48     KBNODE keyblock;
49     KBPOS  kbpos;
50     KBNODE found_key; /* Pointer into some keyblock. */
51     strlist_t extra_list;  /* Will be freed when releasing the context.  */
52     int last_rc;
53     int req_usage;
54     int req_algo;
55     KEYDB_HANDLE kr_handle;
56     int not_allocated;
57     int nitems;
58     KEYDB_SEARCH_DESC items[1];
59 };
60
61 #if 0
62 static struct {
63     int any;
64     int okay_count;
65     int nokey_count;
66     int error_count;
67 } lkup_stats[21];
68 #endif
69
70 typedef struct keyid_list {
71     struct keyid_list *next;
72     u32 keyid[2];
73 } *keyid_list_t;
74
75
76 #if MAX_PK_CACHE_ENTRIES
77   typedef struct pk_cache_entry {
78       struct pk_cache_entry *next;
79       u32 keyid[2];
80       PKT_public_key *pk;
81   } *pk_cache_entry_t;
82   static pk_cache_entry_t pk_cache;
83   static int pk_cache_entries;   /* number of entries in pk cache */
84   static int pk_cache_disabled;
85 #endif
86
87 #if MAX_UID_CACHE_ENTRIES < 5
88 #error we really need the userid cache
89 #endif
90 typedef struct user_id_db {
91     struct user_id_db *next;
92     keyid_list_t keyids;
93     int len;
94     char name[1];
95 } *user_id_db_t;
96 static user_id_db_t user_id_db;
97 static int uid_cache_entries;   /* number of entries in uid cache */
98
99 static void merge_selfsigs( KBNODE keyblock );
100 static int lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode );
101
102 #if 0
103 static void
104 print_stats()
105 {
106     int i;
107     for(i=0; i < DIM(lkup_stats); i++ ) {
108         if( lkup_stats[i].any )
109             fprintf(stderr,
110                     "lookup stats: mode=%-2d  ok=%-6d  nokey=%-6d  err=%-6d\n",
111                     i,
112                     lkup_stats[i].okay_count,
113                     lkup_stats[i].nokey_count,
114                     lkup_stats[i].error_count );
115     }
116 }
117 #endif
118
119
120 void
121 cache_public_key( PKT_public_key *pk )
122 {
123 #if MAX_PK_CACHE_ENTRIES
124     pk_cache_entry_t ce;
125     u32 keyid[2];
126
127     if( pk_cache_disabled )
128         return;
129
130     if( pk->dont_cache )
131         return;
132
133     if( is_ELGAMAL(pk->pubkey_algo)
134         || pk->pubkey_algo == PUBKEY_ALGO_DSA
135         || is_RSA(pk->pubkey_algo) ) {
136         keyid_from_pk( pk, keyid );
137     }
138     else
139         return; /* don't know how to get the keyid */
140
141     for( ce = pk_cache; ce; ce = ce->next )
142         if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] ) {
143             if( DBG_CACHE )
144                 log_debug("cache_public_key: already in cache\n");
145             return;
146         }
147
148     if( pk_cache_entries >= MAX_PK_CACHE_ENTRIES ) {
149         /* fixme: use another algorithm to free some cache slots */
150         pk_cache_disabled=1;
151         if( opt.verbose > 1 )
152             log_info(_("too many entries in pk cache - disabled\n"));
153         return;
154     }
155     pk_cache_entries++;
156     ce = xmalloc( sizeof *ce );
157     ce->next = pk_cache;
158     pk_cache = ce;
159     ce->pk = copy_public_key( NULL, pk );
160     ce->keyid[0] = keyid[0];
161     ce->keyid[1] = keyid[1];
162 #endif
163 }
164
165
166 /* Return a const utf-8 string with the text "[User ID not found]".
167    This fucntion is required so that we don't need to switch gettext's
168    encoding temporary. */
169 static const char *
170 user_id_not_found_utf8 (void)
171 {
172   static char *text;
173
174   if (!text)
175     text = native_to_utf8 (_("[User ID not found]"));
176   return text;
177 }
178
179
180
181 /*
182  * Return the user ID from the given keyblock.
183  * We use the primary uid flag which has been set by the merge_selfsigs
184  * function.  The returned value is only valid as long as then given
185  * keyblock is not changed
186  */
187 static const char *
188 get_primary_uid ( KBNODE keyblock, size_t *uidlen )
189 {
190     KBNODE k;
191     const char *s;
192
193     for (k=keyblock; k; k=k->next ) {
194         if ( k->pkt->pkttype == PKT_USER_ID
195              && !k->pkt->pkt.user_id->attrib_data
196              && k->pkt->pkt.user_id->is_primary ) {
197             *uidlen = k->pkt->pkt.user_id->len;
198             return k->pkt->pkt.user_id->name;
199         }
200     }
201     s = user_id_not_found_utf8 ();
202     *uidlen = strlen (s);
203     return s;
204 }
205
206
207 static void
208 release_keyid_list ( keyid_list_t k )
209 {
210     while (  k ) {
211         keyid_list_t k2 = k->next;
212         xfree (k);
213         k = k2;
214     }
215 }
216
217 /****************
218  * Store the association of keyid and userid
219  * Feed only public keys to this function.
220  */
221 static void
222 cache_user_id( KBNODE keyblock )
223 {
224     user_id_db_t r;
225     const char *uid;
226     size_t uidlen;
227     keyid_list_t keyids = NULL;
228     KBNODE k;
229
230     for (k=keyblock; k; k = k->next ) {
231         if ( k->pkt->pkttype == PKT_PUBLIC_KEY
232              || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
233             keyid_list_t a = xmalloc_clear ( sizeof *a );
234             /* Hmmm: For a long list of keyids it might be an advantage
235              * to append the keys */
236             keyid_from_pk( k->pkt->pkt.public_key, a->keyid );
237             /* first check for duplicates */
238             for(r=user_id_db; r; r = r->next ) {
239                 keyid_list_t b = r->keyids;
240                 for ( b = r->keyids; b; b = b->next ) {
241                     if( b->keyid[0] == a->keyid[0]
242                         && b->keyid[1] == a->keyid[1] ) {
243                         if( DBG_CACHE )
244                             log_debug("cache_user_id: already in cache\n");
245                         release_keyid_list ( keyids );
246                         xfree ( a );
247                         return;
248                     }
249                 }
250             }
251             /* now put it into the cache */
252             a->next = keyids;
253             keyids = a;
254         }
255     }
256     if ( !keyids )
257         BUG (); /* No key no fun */
258
259
260     uid = get_primary_uid ( keyblock, &uidlen );
261
262     if( uid_cache_entries >= MAX_UID_CACHE_ENTRIES ) {
263         /* fixme: use another algorithm to free some cache slots */
264         r = user_id_db;
265         user_id_db = r->next;
266         release_keyid_list ( r->keyids );
267         xfree(r);
268         uid_cache_entries--;
269     }
270     r = xmalloc( sizeof *r + uidlen-1 );
271     r->keyids = keyids;
272     r->len = uidlen;
273     memcpy(r->name, uid, r->len);
274     r->next = user_id_db;
275     user_id_db = r;
276     uid_cache_entries++;
277 }
278
279
280 void
281 getkey_disable_caches()
282 {
283 #if MAX_PK_CACHE_ENTRIES
284     {
285         pk_cache_entry_t ce, ce2;
286
287         for( ce = pk_cache; ce; ce = ce2 ) {
288             ce2 = ce->next;
289             free_public_key( ce->pk );
290             xfree( ce );
291         }
292         pk_cache_disabled=1;
293         pk_cache_entries = 0;
294         pk_cache = NULL;
295     }
296 #endif
297     /* fixme: disable user id cache ? */
298 }
299
300
301 static void
302 pk_from_block ( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE keyblock )
303 {
304     KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
305
306     assert ( a->pkt->pkttype == PKT_PUBLIC_KEY
307              ||  a->pkt->pkttype == PKT_PUBLIC_SUBKEY );
308
309     copy_public_key ( pk, a->pkt->pkt.public_key );
310 }
311
312 static void
313 sk_from_block ( GETKEY_CTX ctx,
314                 PKT_secret_key *sk, KBNODE keyblock )
315 {
316     KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
317
318     assert ( a->pkt->pkttype == PKT_SECRET_KEY
319              ||  a->pkt->pkttype == PKT_SECRET_SUBKEY );
320
321     copy_secret_key( sk, a->pkt->pkt.secret_key);
322 }
323
324
325 /****************
326  * Get a public key and store it into the allocated pk
327  * can be called with PK set to NULL to just read it into some
328  * internal structures.
329  */
330 int
331 get_pubkey( PKT_public_key *pk, u32 *keyid )
332 {
333     int internal = 0;
334     int rc = 0;
335
336 #if MAX_PK_CACHE_ENTRIES
337     if(pk)
338       {
339         /* Try to get it from the cache.  We don't do this when pk is
340            NULL as it does not guarantee that the user IDs are
341            cached. */
342         pk_cache_entry_t ce;
343         for( ce = pk_cache; ce; ce = ce->next )
344           {
345             if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] )
346               {
347                 copy_public_key( pk, ce->pk );
348                 return 0;
349               }
350           }
351       }
352 #endif
353     /* more init stuff */
354     if( !pk ) {
355         pk = xmalloc_clear( sizeof *pk );
356         internal++;
357     }
358
359
360     /* do a lookup */
361     {   struct getkey_ctx_s ctx;
362         KBNODE kb = NULL;
363         memset( &ctx, 0, sizeof ctx );
364         ctx.exact = 1; /* use the key ID exactly as given */
365         ctx.not_allocated = 1;
366         ctx.kr_handle = keydb_new (0);
367         ctx.nitems = 1;
368         ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
369         ctx.items[0].u.kid[0] = keyid[0];
370         ctx.items[0].u.kid[1] = keyid[1];
371         ctx.req_algo  = pk->req_algo;
372         ctx.req_usage = pk->req_usage;
373         rc = lookup( &ctx, &kb, 0 );
374         if ( !rc ) {
375             pk_from_block ( &ctx, pk, kb );
376         }
377         get_pubkey_end( &ctx );
378         release_kbnode ( kb );
379     }
380     if( !rc )
381         goto leave;
382
383     rc = G10ERR_NO_PUBKEY;
384
385   leave:
386     if( !rc )
387         cache_public_key( pk );
388     if( internal )
389         free_public_key(pk);
390     return rc;
391 }
392
393
394 /* Get a public key and store it into the allocated pk.  This function
395    differs from get_pubkey() in that it does not do a check of the key
396    to avoid recursion.  It should be used only in very certain cases.
397    It will only retrieve primary keys. */
398 int
399 get_pubkey_fast (PKT_public_key *pk, u32 *keyid)
400 {
401   int rc = 0;
402   KEYDB_HANDLE hd;
403   KBNODE keyblock;
404   u32 pkid[2];
405
406   assert (pk);
407 #if MAX_PK_CACHE_ENTRIES
408   { /* Try to get it from the cache */
409     pk_cache_entry_t ce;
410
411     for (ce = pk_cache; ce; ce = ce->next)
412       {
413         if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
414           {
415             if (pk)
416               copy_public_key (pk, ce->pk);
417             return 0;
418           }
419       }
420   }
421 #endif
422
423   hd = keydb_new (0);
424   rc = keydb_search_kid (hd, keyid);
425   if (rc == -1)
426     {
427       keydb_release (hd);
428       return G10ERR_NO_PUBKEY;
429     }
430   rc = keydb_get_keyblock (hd, &keyblock);
431   keydb_release (hd);
432   if (rc)
433     {
434       log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
435       return G10ERR_NO_PUBKEY;
436     }
437
438   assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
439            ||  keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
440
441   keyid_from_pk(keyblock->pkt->pkt.public_key,pkid);
442   if(keyid[0]==pkid[0] && keyid[1]==pkid[1])
443     copy_public_key (pk, keyblock->pkt->pkt.public_key );
444   else
445     rc=G10ERR_NO_PUBKEY;
446
447   release_kbnode (keyblock);
448
449   /* Not caching key here since it won't have all of the fields
450      properly set. */
451
452   return rc;
453 }
454
455
456 KBNODE
457 get_pubkeyblock( u32 *keyid )
458 {
459     struct getkey_ctx_s ctx;
460     int rc = 0;
461     KBNODE keyblock = NULL;
462
463     memset( &ctx, 0, sizeof ctx );
464     /* no need to set exact here because we want the entire block */
465     ctx.not_allocated = 1;
466     ctx.kr_handle = keydb_new (0);
467     ctx.nitems = 1;
468     ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
469     ctx.items[0].u.kid[0] = keyid[0];
470     ctx.items[0].u.kid[1] = keyid[1];
471     rc = lookup( &ctx, &keyblock, 0 );
472     get_pubkey_end( &ctx );
473
474     return rc ? NULL : keyblock;
475 }
476
477
478
479
480 /****************
481  * Get a secret key and store it into sk
482  */
483 int
484 get_seckey( PKT_secret_key *sk, u32 *keyid )
485 {
486     int rc;
487     struct getkey_ctx_s ctx;
488     KBNODE kb = NULL;
489
490     memset( &ctx, 0, sizeof ctx );
491     ctx.exact = 1; /* use the key ID exactly as given */
492     ctx.not_allocated = 1;
493     ctx.kr_handle = keydb_new (1);
494     ctx.nitems = 1;
495     ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
496     ctx.items[0].u.kid[0] = keyid[0];
497     ctx.items[0].u.kid[1] = keyid[1];
498     ctx.req_algo  = sk->req_algo;
499     ctx.req_usage = sk->req_usage;
500     rc = lookup( &ctx, &kb, 1 );
501     if ( !rc ) {
502         sk_from_block ( &ctx, sk, kb );
503     }
504     get_seckey_end( &ctx );
505     release_kbnode ( kb );
506
507     if( !rc ) {
508         /* check the secret key (this may prompt for a passprase to
509          * unlock the secret key
510          */
511         rc = check_secret_key( sk, 0 );
512     }
513
514     return rc;
515 }
516
517
518 /****************
519  * Check whether the secret key is available.  This is just a fast
520  * check and does not tell us whether the secret key is valid.  It
521  * merely tells other whether there is some secret key.
522  * Returns: 0 := key is available
523  * G10ERR_NO_SECKEY := not availabe
524  */
525 int
526 seckey_available( u32 *keyid )
527 {
528     int rc;
529     KEYDB_HANDLE hd = keydb_new (1);
530
531     rc = keydb_search_kid (hd, keyid);
532     if ( rc == -1 )
533         rc = G10ERR_NO_SECKEY;
534     keydb_release (hd);
535     return rc;
536 }
537
538
539 /****************
540  * Return the type of the user id:
541  *
542  * Please use the constants KEYDB_SERCH_MODE_xxx
543  *  0 = Invalid user ID
544  *  1 = exact match
545  *  2 = match a substring
546  *  3 = match an email address
547  *  4 = match a substring of an email address
548  *  5 = match an email address, but compare from end
549  *  6 = word match mode
550  * 10 = it is a short KEYID (don't care about keyid[0])
551  * 11 = it is a long  KEYID
552  * 12 = it is a trustdb index (keyid is looked up)
553  * 16 = it is a 16 byte fingerprint
554  * 20 = it is a 20 byte fingerprint
555  * 21 = Unified fingerprint :fpr:pk_algo:
556  *      (We don't use pk_algo yet)
557  *
558  * Rules used:
559  * - If the username starts with 8,9,16 or 17 hex-digits (the first one
560  *   must be in the range 0..9), this is considered a keyid; depending
561  *   on the length a short or complete one.
562  * - If the username starts with 32,33,40 or 41 hex-digits (the first one
563  *   must be in the range 0..9), this is considered a fingerprint.
564  * - If the username starts with a left angle, we assume it is a complete
565  *   email address and look only at this part.
566  * - If the username starts with a colon we assume it is a unified
567  *   key specfification.
568  * - If the username starts with a '.', we assume it is the ending
569  *   part of an email address
570  * - If the username starts with an '@', we assume it is a part of an
571  *   email address
572  * - If the userid start with an '=' an exact compare is done.
573  * - If the userid starts with a '*' a case insensitive substring search is
574  *   done (This is the default).
575  * - If the userid starts with a '+' we will compare individual words
576  *   and a match requires that all the words are in the userid.
577  *   Words are delimited by white space or "()<>[]{}.@-+_,;/&!"
578  *   (note that you can't search for these characters). Compare
579  *   is not case sensitive.
580  * - If the userid starts with a '&' a 40 hex digits keygrip is expected.
581  */
582
583 int
584 classify_user_id( const char *name, KEYDB_SEARCH_DESC *desc )
585 {
586     const char *s;
587     int hexprefix = 0;
588     int hexlength;
589     int mode = 0;
590     KEYDB_SEARCH_DESC dummy_desc;
591
592     if (!desc)
593         desc = &dummy_desc;
594
595     /* clear the structure so that the mode field is set to zero unless
596      * we set it to the correct value right at the end of this function */
597     memset (desc, 0, sizeof *desc);
598
599     /* skip leading spaces.  Fixme: what is with trailing spaces? */
600     for(s = name; *s && spacep (s); s++ )
601         ;
602
603     switch (*s) {
604         case 0:    /* empty string is an error */
605             return 0;
606
607 #if 0
608         case '.':  /* an email address, compare from end */
609             mode = KEYDB_SEARCH_MODE_MAILEND;
610             s++;
611             desc->u.name = s;
612             break;
613 #endif
614
615         case '<':  /* an email address */
616             mode = KEYDB_SEARCH_MODE_MAIL;
617             desc->u.name = s;
618             break;
619
620         case '@':  /* part of an email address */
621             mode = KEYDB_SEARCH_MODE_MAILSUB;
622             s++;
623             desc->u.name = s;
624             break;
625
626         case '=':  /* exact compare */
627             mode = KEYDB_SEARCH_MODE_EXACT;
628             s++;
629             desc->u.name = s;
630             break;
631
632         case '*':  /* case insensitive substring search */
633             mode = KEYDB_SEARCH_MODE_SUBSTR;
634             s++;
635             desc->u.name = s;
636             break;
637
638 #if 0
639         case '+':  /* compare individual words */
640             mode = KEYDB_SEARCH_MODE_WORDS;
641             s++;
642             desc->u.name = s;
643             break;
644 #endif
645
646         case '#':  /* local user id */
647             return 0; /* This is now obsolete and can't not be used anymore*/
648
649         case ':': /*Unified fingerprint */
650             {
651                 const char *se, *si;
652                 int i;
653
654                 se = strchr( ++s,':');
655                 if ( !se )
656                     return 0;
657                 for (i=0,si=s; si < se; si++, i++ ) {
658                     if ( !strchr("01234567890abcdefABCDEF", *si ) )
659                         return 0; /* invalid digit */
660                 }
661                 if (i != 32 && i != 40)
662                     return 0; /* invalid length of fpr*/
663                 for (i=0,si=s; si < se; i++, si +=2)
664                     desc->u.fpr[i] = hextobyte(si);
665                 for ( ; i < 20; i++)
666                     desc->u.fpr[i]= 0;
667                 s = se + 1;
668                 mode = KEYDB_SEARCH_MODE_FPR;
669             }
670             break;
671
672         case '&':  /* keygrip */
673           return 0; /* Not yet implememted. */
674
675         default:
676             if (s[0] == '0' && s[1] == 'x') {
677                 hexprefix = 1;
678                 s += 2;
679             }
680
681             hexlength = strspn(s, "0123456789abcdefABCDEF");
682             if (hexlength >= 8 && s[hexlength] =='!') {
683                 desc->exact = 1;
684                 hexlength++; /* just for the following check */
685             }
686
687             /* check if a hexadecimal number is terminated by EOS or blank */
688             if (hexlength && s[hexlength] && !spacep(s+hexlength)) {
689                 if (hexprefix)      /* a "0x" prefix without correct */
690                     return 0;       /* termination is an error */
691                 else                /* The first chars looked like */
692                     hexlength = 0;  /* a hex number, but really were not. */
693             }
694
695             if (desc->exact)
696                 hexlength--;
697
698             if (hexlength == 8
699                 || (!hexprefix && hexlength == 9 && *s == '0')){
700                 /* short keyid */
701                 if (hexlength == 9)
702                     s++;
703                 desc->u.kid[0] = 0;
704                 desc->u.kid[1] = strtoul( s, NULL, 16 );
705                 mode = KEYDB_SEARCH_MODE_SHORT_KID;
706             }
707             else if (hexlength == 16
708                      || (!hexprefix && hexlength == 17 && *s == '0')) {
709                 /* complete keyid */
710                 char buf[9];
711                 if (hexlength == 17)
712                     s++;
713                 mem2str(buf, s, 9 );
714                 desc->u.kid[0] = strtoul( buf, NULL, 16 );
715                 desc->u.kid[1] = strtoul( s+8, NULL, 16 );
716                 mode = KEYDB_SEARCH_MODE_LONG_KID;
717             }
718             else if (hexlength == 32 || (!hexprefix && hexlength == 33
719                                                             && *s == '0')) {
720                 /* md5 fingerprint */
721                 int i;
722                 if (hexlength == 33)
723                     s++;
724                 memset(desc->u.fpr+16, 0, 4);
725                 for (i=0; i < 16; i++, s+=2) {
726                     int c = hextobyte(s);
727                     if (c == -1)
728                         return 0;
729                     desc->u.fpr[i] = c;
730                 }
731                 mode = KEYDB_SEARCH_MODE_FPR16;
732             }
733             else if (hexlength == 40 || (!hexprefix && hexlength == 41
734                                                               && *s == '0')) {
735                 /* sha1/rmd160 fingerprint */
736                 int i;
737                 if (hexlength == 41)
738                     s++;
739                 for (i=0; i < 20; i++, s+=2) {
740                     int c = hextobyte(s);
741                     if (c == -1)
742                         return 0;
743                     desc->u.fpr[i] = c;
744                 }
745                 mode = KEYDB_SEARCH_MODE_FPR20;
746             }
747             else {
748                 if (hexprefix)  /* This was a hex number with a prefix */
749                     return 0;   /* and a wrong length */
750
751                 desc->exact = 0;
752                 desc->u.name = s;
753                 mode = KEYDB_SEARCH_MODE_SUBSTR;   /* default mode */
754             }
755     }
756
757     desc->mode = mode;
758     return mode;
759 }
760
761
762 static int
763 skip_unusable (void *dummy, u32 *keyid, PKT_user_id *uid)
764 {
765   int unusable=0;
766   KBNODE keyblock;
767
768   (void)dummy;
769
770   keyblock=get_pubkeyblock(keyid);
771   if(!keyblock)
772     {
773       log_error("error checking usability status of %s\n",keystr(keyid));
774       goto leave;
775     }
776
777   /* Is the user ID in question revoked/expired? */
778   if(uid)
779     {
780       KBNODE node;
781
782       for(node=keyblock;node;node=node->next)
783         {
784           if(node->pkt->pkttype==PKT_USER_ID)
785             {
786               if(cmp_user_ids(uid,node->pkt->pkt.user_id)==0
787                  && (node->pkt->pkt.user_id->is_revoked
788                      || node->pkt->pkt.user_id->is_expired))
789                 {
790                   unusable=1;
791                   break;
792                 }
793             }
794         }
795     }
796
797   if(!unusable)
798     unusable=pk_is_disabled(keyblock->pkt->pkt.public_key);
799
800  leave:
801   release_kbnode(keyblock);
802   return unusable;
803 }
804
805 /****************
806  * Try to get the pubkey by the userid. This function looks for the
807  * first pubkey certificate which has the given name in a user_id.  if
808  * pk/sk has the pubkey algo set, the function will only return a
809  * pubkey with that algo.  If namelist is NULL, the first key is
810  * returned.  The caller should provide storage for either the pk or
811  * the sk.  If ret_kb is not NULL the function will return the
812  * keyblock there.
813  */
814
815 static int
816 key_byname( GETKEY_CTX *retctx, strlist_t namelist,
817             PKT_public_key *pk, PKT_secret_key *sk,
818             int secmode, int include_unusable,
819             KBNODE *ret_kb, KEYDB_HANDLE *ret_kdbhd )
820 {
821     int rc = 0;
822     int n;
823     strlist_t r;
824     GETKEY_CTX ctx;
825     KBNODE help_kb = NULL;
826
827     if( retctx ) {/* reset the returned context in case of error */
828         assert (!ret_kdbhd);  /* not allowed because the handle is
829                                  stored in the context */
830         *retctx = NULL;
831     }
832     if (ret_kdbhd)
833         *ret_kdbhd = NULL;
834
835     if(!namelist)
836       {
837         ctx = xmalloc_clear (sizeof *ctx);
838         ctx->nitems = 1;
839         ctx->items[0].mode=KEYDB_SEARCH_MODE_FIRST;
840         if(!include_unusable)
841           ctx->items[0].skipfnc=skip_unusable;
842       }
843     else
844       {
845         /* build the search context */
846         for(n=0, r=namelist; r; r = r->next )
847           n++;
848
849         ctx = xmalloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
850         ctx->nitems = n;
851
852         for(n=0, r=namelist; r; r = r->next, n++ )
853           {
854             classify_user_id (r->d, &ctx->items[n]);
855
856             if (ctx->items[n].exact)
857               ctx->exact = 1;
858             if (!ctx->items[n].mode)
859               {
860                 xfree (ctx);
861                 return G10ERR_INV_USER_ID;
862               }
863             if(!include_unusable
864                && ctx->items[n].mode!=KEYDB_SEARCH_MODE_SHORT_KID
865                && ctx->items[n].mode!=KEYDB_SEARCH_MODE_LONG_KID
866                && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR16
867                && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR20
868                && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR)
869               ctx->items[n].skipfnc=skip_unusable;
870           }
871       }
872
873     ctx->kr_handle = keydb_new (secmode);
874     if ( !ret_kb )
875         ret_kb = &help_kb;
876
877     if( secmode ) {
878         if (sk) {
879             ctx->req_algo  = sk->req_algo;
880             ctx->req_usage = sk->req_usage;
881         }
882         rc = lookup( ctx, ret_kb, 1 );
883         if ( !rc && sk ) {
884             sk_from_block ( ctx, sk, *ret_kb );
885         }
886     }
887     else {
888         if (pk) {
889             ctx->req_algo  = pk->req_algo;
890             ctx->req_usage = pk->req_usage;
891         }
892         rc = lookup( ctx, ret_kb, 0 );
893         if ( !rc && pk ) {
894             pk_from_block ( ctx, pk, *ret_kb );
895         }
896     }
897
898     release_kbnode ( help_kb );
899
900     if (retctx) /* caller wants the context */
901         *retctx = ctx;
902     else {
903         if (ret_kdbhd) {
904             *ret_kdbhd = ctx->kr_handle;
905             ctx->kr_handle = NULL;
906         }
907         get_pubkey_end (ctx);
908     }
909
910     return rc;
911 }
912
913
914
915 /* Find a public key from NAME and return the keyblock or the key.  If
916    ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
917    is returned and the caller is responsible for closing it.  If a key
918    was not found (or if local search has been disabled) and NAME is a
919    valid RFC822 mailbox and --auto-key-locate has been enabled, we try
920    to import the key via the online mechanisms defined by
921    --auto-key-locate.  */
922 int
923 get_pubkey_byname (GETKEY_CTX *retctx, PKT_public_key *pk,
924                    const char *name, KBNODE *ret_keyblock,
925                    KEYDB_HANDLE *ret_kdbhd, int include_unusable,
926                    int no_akl)
927 {
928   int rc;
929   strlist_t namelist = NULL;
930   struct akl *akl;
931   int is_mbox;
932   int nodefault = 0;
933   int anylocalfirst = 0;
934
935   if (retctx)
936     *retctx = NULL;
937
938   is_mbox = is_valid_mailbox (name);
939
940   /* Check whether we the default local search has been disabled.
941      This is the case if either the "nodefault" or the "local" keyword
942      are in the list of auto key locate mechanisms.
943
944      ANYLOCALFIRST is set if the search order has the local method
945      before any other or if "local" is used first by default.  This
946      makes sure that if a RETCTX is used it gets only set if a local
947      search has precedence over the other search methods and only then
948      a followup call to get_pubkey_next shall succeed.  */
949   if (!no_akl)
950     {
951       for (akl=opt.auto_key_locate; akl; akl=akl->next)
952         if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
953           {
954             nodefault = 1;
955             break;
956           }
957       for (akl=opt.auto_key_locate; akl; akl=akl->next)
958         if (akl->type != AKL_NODEFAULT)
959           {
960             if (akl->type == AKL_LOCAL)
961               anylocalfirst = 1;
962             break;
963           }
964     }
965
966   if (!nodefault)
967     anylocalfirst = 1;
968
969   if (nodefault && is_mbox)
970     {
971       /* Nodefault but a mailbox - let the AKL locate the key.  */
972       rc = G10ERR_NO_PUBKEY;
973     }
974   else
975     {
976       add_to_strlist (&namelist, name);
977       rc = key_byname (retctx, namelist, pk, NULL, 0,
978                        include_unusable, ret_keyblock, ret_kdbhd);
979     }
980
981   /* If the requested name resembles a valid mailbox and automatic
982      retrieval has been enabled, we try to import the key. */
983   if (gpg_err_code (rc) == G10ERR_NO_PUBKEY && !no_akl && is_mbox)
984     {
985       for (akl=opt.auto_key_locate; akl; akl=akl->next)
986         {
987           unsigned char *fpr = NULL;
988           size_t fpr_len;
989           int did_key_byname = 0;
990           int no_fingerprint = 0;
991           const char *mechanism = "?";
992
993           switch(akl->type)
994             {
995             case AKL_NODEFAULT:
996               /* This is a dummy mechanism.  */
997               mechanism = "None";
998               rc = G10ERR_NO_PUBKEY;
999               break;
1000
1001             case AKL_LOCAL:
1002               mechanism = "Local";
1003               did_key_byname = 1;
1004               if (retctx)
1005                 {
1006                   get_pubkey_end (*retctx);
1007                   *retctx = NULL;
1008                 }
1009               add_to_strlist (&namelist, name);
1010               rc = key_byname (anylocalfirst? retctx:NULL,
1011                                namelist, pk, NULL, 0,
1012                                include_unusable, ret_keyblock, ret_kdbhd);
1013               break;
1014
1015             case AKL_CERT:
1016               mechanism = "DNS CERT";
1017               glo_ctrl.in_auto_key_retrieve++;
1018               rc=keyserver_import_cert(name,&fpr,&fpr_len);
1019               glo_ctrl.in_auto_key_retrieve--;
1020               break;
1021
1022             case AKL_PKA:
1023               mechanism = "PKA";
1024               glo_ctrl.in_auto_key_retrieve++;
1025               rc=keyserver_import_pka(name,&fpr,&fpr_len);
1026               glo_ctrl.in_auto_key_retrieve--;
1027               break;
1028
1029             case AKL_LDAP:
1030               mechanism = "LDAP";
1031               glo_ctrl.in_auto_key_retrieve++;
1032               rc=keyserver_import_ldap(name,&fpr,&fpr_len);
1033               glo_ctrl.in_auto_key_retrieve--;
1034               break;
1035
1036             case AKL_KEYSERVER:
1037               /* Strictly speaking, we don't need to only use a valid
1038                  mailbox for the getname search, but it helps cut down
1039                  on the problem of searching for something like "john"
1040                  and getting a whole lot of keys back. */
1041               if(opt.keyserver)
1042                 {
1043                   mechanism = opt.keyserver->uri;
1044                   glo_ctrl.in_auto_key_retrieve++;
1045                   rc=keyserver_import_name(name,&fpr,&fpr_len,opt.keyserver);
1046                   glo_ctrl.in_auto_key_retrieve--;
1047                 }
1048               else
1049                 {
1050                   mechanism = "Unconfigured keyserver";
1051                   rc = G10ERR_NO_PUBKEY;
1052                 }
1053               break;
1054
1055             case AKL_SPEC:
1056               {
1057                 struct keyserver_spec *keyserver;
1058
1059                 mechanism = akl->spec->uri;
1060                 keyserver=keyserver_match(akl->spec);
1061                 glo_ctrl.in_auto_key_retrieve++;
1062                 rc=keyserver_import_name(name,&fpr,&fpr_len,keyserver);
1063                 glo_ctrl.in_auto_key_retrieve--;
1064               }
1065               break;
1066             }
1067
1068           /* Use the fingerprint of the key that we actually fetched.
1069              This helps prevent problems where the key that we fetched
1070              doesn't have the same name that we used to fetch it.  In
1071              the case of CERT and PKA, this is an actual security
1072              requirement as the URL might point to a key put in by an
1073              attacker.  By forcing the use of the fingerprint, we
1074              won't use the attacker's key here. */
1075           if (!rc && fpr)
1076             {
1077               char fpr_string[MAX_FINGERPRINT_LEN*2+1];
1078
1079               assert(fpr_len<=MAX_FINGERPRINT_LEN);
1080
1081               free_strlist(namelist);
1082               namelist=NULL;
1083
1084               bin2hex (fpr, fpr_len, fpr_string);
1085
1086               if(opt.verbose)
1087                 log_info("auto-key-locate found fingerprint %s\n",fpr_string);
1088
1089               add_to_strlist( &namelist, fpr_string );
1090             }
1091           else if (!rc && !fpr && !did_key_byname)
1092             {
1093               no_fingerprint = 1;
1094               rc = G10ERR_NO_PUBKEY;
1095             }
1096           xfree (fpr);
1097           fpr = NULL;
1098
1099           if (!rc && !did_key_byname)
1100             {
1101               if (retctx)
1102                 {
1103                   get_pubkey_end (*retctx);
1104                   *retctx = NULL;
1105                 }
1106               rc = key_byname (anylocalfirst?retctx:NULL,
1107                                namelist, pk, NULL, 0,
1108                                include_unusable, ret_keyblock, ret_kdbhd);
1109             }
1110           if (!rc)
1111             {
1112               /* Key found.  */
1113               log_info (_("automatically retrieved `%s' via %s\n"),
1114                         name, mechanism);
1115               break;
1116             }
1117           if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
1118             log_info (_("error retrieving `%s' via %s: %s\n"),
1119                       name, mechanism,
1120                       no_fingerprint? _("No fingerprint"):g10_errstr(rc));
1121         }
1122     }
1123
1124
1125   if (rc && retctx)
1126     {
1127       get_pubkey_end (*retctx);
1128       *retctx = NULL;
1129     }
1130
1131   if (retctx && *retctx)
1132     {
1133       assert (!(*retctx)->extra_list);
1134       (*retctx)->extra_list = namelist;
1135     }
1136   else
1137     free_strlist (namelist);
1138   return rc;
1139 }
1140
1141
1142 int
1143 get_pubkey_bynames( GETKEY_CTX *retctx, PKT_public_key *pk,
1144                     strlist_t names, KBNODE *ret_keyblock )
1145 {
1146     return key_byname( retctx, names, pk, NULL, 0, 1, ret_keyblock, NULL);
1147 }
1148
1149 int
1150 get_pubkey_next( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE *ret_keyblock )
1151 {
1152     int rc;
1153
1154     rc = lookup( ctx, ret_keyblock, 0 );
1155     if ( !rc && pk && ret_keyblock )
1156         pk_from_block ( ctx, pk, *ret_keyblock );
1157
1158     return rc;
1159 }
1160
1161 void
1162 get_pubkey_end( GETKEY_CTX ctx )
1163 {
1164     if( ctx ) {
1165         memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1166         keydb_release (ctx->kr_handle);
1167         free_strlist (ctx->extra_list);
1168         if( !ctx->not_allocated )
1169             xfree( ctx );
1170     }
1171 }
1172
1173
1174 /****************
1175  * Search for a key with the given fingerprint.
1176  * FIXME:
1177  * We should replace this with the _byname function.  Thiscsan be done
1178  * by creating a userID conforming to the unified fingerprint style.
1179  */
1180 int
1181 get_pubkey_byfprint( PKT_public_key *pk,
1182                      const byte *fprint, size_t fprint_len)
1183 {
1184     int rc;
1185
1186     if( fprint_len == 20 || fprint_len == 16 ) {
1187         struct getkey_ctx_s ctx;
1188         KBNODE kb = NULL;
1189
1190         memset( &ctx, 0, sizeof ctx );
1191         ctx.exact = 1 ;
1192         ctx.not_allocated = 1;
1193         ctx.kr_handle = keydb_new (0);
1194         ctx.nitems = 1;
1195         ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1196                                           : KEYDB_SEARCH_MODE_FPR20;
1197         memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1198         rc = lookup( &ctx, &kb, 0 );
1199         if (!rc && pk )
1200             pk_from_block ( &ctx, pk, kb );
1201         release_kbnode ( kb );
1202         get_pubkey_end( &ctx );
1203     }
1204     else
1205         rc = G10ERR_GENERAL; /* Oops */
1206     return rc;
1207 }
1208
1209
1210 /* Get a public key and store it into the allocated pk.  This function
1211    differs from get_pubkey_byfprint() in that it does not do a check
1212    of the key to avoid recursion.  It should be used only in very
1213    certain cases.  PK may be NULL to check just for the existance of
1214    the key. */
1215 int
1216 get_pubkey_byfprint_fast (PKT_public_key *pk,
1217                           const byte *fprint, size_t fprint_len)
1218 {
1219   int rc = 0;
1220   KEYDB_HANDLE hd;
1221   KBNODE keyblock;
1222   byte fprbuf[MAX_FINGERPRINT_LEN];
1223   int i;
1224
1225   for (i=0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1226     fprbuf[i] = fprint[i];
1227   while (i < MAX_FINGERPRINT_LEN)
1228     fprbuf[i++] = 0;
1229
1230   hd = keydb_new (0);
1231   rc = keydb_search_fpr (hd, fprbuf);
1232   if (rc == -1)
1233     {
1234       keydb_release (hd);
1235       return G10ERR_NO_PUBKEY;
1236     }
1237   rc = keydb_get_keyblock (hd, &keyblock);
1238   keydb_release (hd);
1239   if (rc)
1240     {
1241       log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
1242       return G10ERR_NO_PUBKEY;
1243     }
1244
1245   assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1246            ||  keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
1247   if (pk)
1248     copy_public_key (pk, keyblock->pkt->pkt.public_key );
1249   release_kbnode (keyblock);
1250
1251   /* Not caching key here since it won't have all of the fields
1252      properly set. */
1253
1254   return 0;
1255 }
1256
1257 /****************
1258  * Search for a key with the given fingerprint and return the
1259  * complete keyblock which may have more than only this key.
1260  */
1261 int
1262 get_keyblock_byfprint( KBNODE *ret_keyblock, const byte *fprint,
1263                                                 size_t fprint_len )
1264 {
1265     int rc;
1266
1267     if( fprint_len == 20 || fprint_len == 16 ) {
1268         struct getkey_ctx_s ctx;
1269
1270         memset( &ctx, 0, sizeof ctx );
1271         ctx.not_allocated = 1;
1272         ctx.kr_handle = keydb_new (0);
1273         ctx.nitems = 1;
1274         ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1275                                           : KEYDB_SEARCH_MODE_FPR20;
1276         memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1277         rc = lookup( &ctx, ret_keyblock, 0 );
1278         get_pubkey_end( &ctx );
1279     }
1280     else
1281         rc = G10ERR_GENERAL; /* Oops */
1282
1283     return rc;
1284 }
1285
1286
1287 /****************
1288  * Get a secret key by name and store it into sk
1289  * If NAME is NULL use the default key
1290  */
1291 static int
1292 get_seckey_byname2( GETKEY_CTX *retctx,
1293                     PKT_secret_key *sk, const char *name, int unprotect,
1294                     KBNODE *retblock )
1295 {
1296   strlist_t namelist = NULL;
1297   int rc,include_unusable=1;
1298
1299   /* If we have no name, try to use the default secret key.  If we
1300      have no default, we'll use the first usable one. */
1301
1302   if( !name && opt.def_secret_key && *opt.def_secret_key )
1303     add_to_strlist( &namelist, opt.def_secret_key );
1304   else if(name)
1305     add_to_strlist( &namelist, name );
1306   else
1307     include_unusable=0;
1308
1309   rc = key_byname( retctx, namelist, NULL, sk, 1, include_unusable,
1310                    retblock, NULL );
1311
1312   free_strlist( namelist );
1313
1314   if( !rc && unprotect )
1315     rc = check_secret_key( sk, 0 );
1316
1317   return rc;
1318 }
1319
1320 int
1321 get_seckey_byname( PKT_secret_key *sk, const char *name, int unlock )
1322 {
1323     return get_seckey_byname2 ( NULL, sk, name, unlock, NULL );
1324 }
1325
1326
1327 int
1328 get_seckey_bynames( GETKEY_CTX *retctx, PKT_secret_key *sk,
1329                     strlist_t names, KBNODE *ret_keyblock )
1330 {
1331     return key_byname( retctx, names, NULL, sk, 1, 1, ret_keyblock, NULL );
1332 }
1333
1334
1335 int
1336 get_seckey_next( GETKEY_CTX ctx, PKT_secret_key *sk, KBNODE *ret_keyblock )
1337 {
1338     int rc;
1339
1340     rc = lookup( ctx, ret_keyblock, 1 );
1341     if ( !rc && sk && ret_keyblock )
1342         sk_from_block ( ctx, sk, *ret_keyblock );
1343
1344     return rc;
1345 }
1346
1347
1348 void
1349 get_seckey_end( GETKEY_CTX ctx )
1350 {
1351     get_pubkey_end( ctx );
1352 }
1353
1354
1355 /****************
1356  * Search for a key with the given fingerprint.
1357  * FIXME:
1358  * We should replace this with the _byname function.  Thiscsan be done
1359  * by creating a userID conforming to the unified fingerprint style.
1360  */
1361 int
1362 get_seckey_byfprint( PKT_secret_key *sk,
1363                      const byte *fprint, size_t fprint_len)
1364 {
1365     int rc;
1366
1367     if( fprint_len == 20 || fprint_len == 16 ) {
1368         struct getkey_ctx_s ctx;
1369         KBNODE kb = NULL;
1370
1371         memset( &ctx, 0, sizeof ctx );
1372         ctx.exact = 1 ;
1373         ctx.not_allocated = 1;
1374         ctx.kr_handle = keydb_new (1);
1375         ctx.nitems = 1;
1376         ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1377                                           : KEYDB_SEARCH_MODE_FPR20;
1378         memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1379         rc = lookup( &ctx, &kb, 1 );
1380         if (!rc && sk )
1381             sk_from_block ( &ctx, sk, kb );
1382         release_kbnode ( kb );
1383         get_seckey_end( &ctx );
1384     }
1385     else
1386         rc = G10ERR_GENERAL; /* Oops */
1387     return rc;
1388 }
1389
1390
1391 /* Search for a secret key with the given fingerprint and return the
1392    complete keyblock which may have more than only this key. */
1393 int
1394 get_seckeyblock_byfprint (KBNODE *ret_keyblock, const byte *fprint,
1395                           size_t fprint_len )
1396 {
1397   int rc;
1398   struct getkey_ctx_s ctx;
1399
1400   if (fprint_len != 20 && fprint_len == 16)
1401     return G10ERR_GENERAL; /* Oops */
1402
1403   memset (&ctx, 0, sizeof ctx);
1404   ctx.not_allocated = 1;
1405   ctx.kr_handle = keydb_new (1);
1406   ctx.nitems = 1;
1407   ctx.items[0].mode = (fprint_len==16
1408                        ? KEYDB_SEARCH_MODE_FPR16
1409                        : KEYDB_SEARCH_MODE_FPR20);
1410   memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1411   rc = lookup (&ctx, ret_keyblock, 1);
1412   get_seckey_end (&ctx);
1413
1414   return rc;
1415 }
1416
1417
1418 \f
1419 /************************************************
1420  ************* Merging stuff ********************
1421  ************************************************/
1422
1423 /****************
1424  * merge all selfsignatures with the keys.
1425  * FIXME: replace this at least for the public key parts
1426  *        by merge_selfsigs.
1427  *        It is still used in keyedit.c and
1428  *        at 2 or 3 other places - check whether it is really needed.
1429  *        It might be needed by the key edit and import stuff because
1430  *        the keylock is changed.
1431  */
1432 void
1433 merge_keys_and_selfsig( KBNODE keyblock )
1434 {
1435     PKT_public_key *pk = NULL;
1436     PKT_secret_key *sk = NULL;
1437     PKT_signature *sig;
1438     KBNODE k;
1439     u32 kid[2] = { 0, 0 };
1440     u32 sigdate = 0;
1441
1442     if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
1443         /* divert to our new function */
1444         merge_selfsigs (keyblock);
1445         return;
1446     }
1447     /* still need the old one because the new one can't handle secret keys */
1448
1449     for(k=keyblock; k; k = k->next ) {
1450         if( k->pkt->pkttype == PKT_PUBLIC_KEY
1451             || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1452             pk = k->pkt->pkt.public_key; sk = NULL;
1453             if( pk->version < 4 )
1454                 pk = NULL; /* not needed for old keys */
1455             else if( k->pkt->pkttype == PKT_PUBLIC_KEY )
1456                 keyid_from_pk( pk, kid );
1457             else if( !pk->expiredate ) { /* and subkey */
1458                 /* insert the expiration date here */
1459                 /*FIXME!!! pk->expiredate = subkeys_expiretime( k, kid );*/
1460             }
1461             sigdate = 0;
1462         }
1463         else if( k->pkt->pkttype == PKT_SECRET_KEY
1464             || k->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1465             pk = NULL; sk = k->pkt->pkt.secret_key;
1466             if( sk->version < 4 )
1467                 sk = NULL;
1468             else if( k->pkt->pkttype == PKT_SECRET_KEY )
1469                 keyid_from_sk( sk, kid );
1470             sigdate = 0;
1471         }
1472         else if( (pk || sk ) && k->pkt->pkttype == PKT_SIGNATURE
1473                  && (sig=k->pkt->pkt.signature)->sig_class >= 0x10
1474                  && sig->sig_class <= 0x30 && sig->version > 3
1475                  && !(sig->sig_class == 0x18 || sig->sig_class == 0x28)
1476                  && sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1] ) {
1477             /* okay this is a self-signature which can be used.
1478              * This is not used for subkey binding signature, becuase this
1479              * is done above.
1480              * FIXME: We should only use this if the signature is valid
1481              *        but this is time consuming - we must provide another
1482              *        way to handle this
1483              */
1484             const byte *p;
1485             u32 ed;
1486
1487             p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
1488             if( pk ) {
1489                 ed = p? pk->timestamp + buffer_to_u32(p):0;
1490                 if( sig->timestamp > sigdate ) {
1491                     pk->expiredate = ed;
1492                     sigdate = sig->timestamp;
1493                 }
1494             }
1495             else {
1496                 ed = p? sk->timestamp + buffer_to_u32(p):0;
1497                 if( sig->timestamp > sigdate ) {
1498                     sk->expiredate = ed;
1499                     sigdate = sig->timestamp;
1500                 }
1501             }
1502         }
1503
1504         if(pk && (pk->expiredate==0 ||
1505                   (pk->max_expiredate && pk->expiredate>pk->max_expiredate)))
1506           pk->expiredate=pk->max_expiredate;
1507
1508         if(sk && (sk->expiredate==0 ||
1509                   (sk->max_expiredate && sk->expiredate>sk->max_expiredate)))
1510           sk->expiredate=sk->max_expiredate;
1511     }
1512 }
1513
1514 static int
1515 parse_key_usage(PKT_signature *sig)
1516 {
1517   int key_usage=0;
1518   const byte *p;
1519   size_t n;
1520   byte flags;
1521
1522   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_KEY_FLAGS,&n);
1523   if(p && n)
1524     {
1525       /* first octet of the keyflags */
1526       flags=*p;
1527
1528       if(flags & 1)
1529         {
1530           key_usage |= PUBKEY_USAGE_CERT;
1531           flags&=~1;
1532         }
1533
1534       if(flags & 2)
1535         {
1536           key_usage |= PUBKEY_USAGE_SIG;
1537           flags&=~2;
1538         }
1539
1540       /* We do not distinguish between encrypting communications and
1541          encrypting storage. */
1542       if(flags & (0x04|0x08))
1543         {
1544           key_usage |= PUBKEY_USAGE_ENC;
1545           flags&=~(0x04|0x08);
1546         }
1547
1548       if(flags & 0x20)
1549         {
1550           key_usage |= PUBKEY_USAGE_AUTH;
1551           flags&=~0x20;
1552         }
1553
1554       if(flags)
1555         key_usage |= PUBKEY_USAGE_UNKNOWN;
1556
1557       if (!key_usage)
1558         key_usage |= PUBKEY_USAGE_NONE;
1559     }
1560   else if (p) /* Key flags of length zero.  */
1561     key_usage |= PUBKEY_USAGE_NONE;
1562
1563   /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1564      capability that we do not handle.  This serves to distinguish
1565      between a zero key usage which we handle as the default
1566      capabilities for that algorithm, and a usage that we do not
1567      handle.  Likewise we use PUBKEY_USAGE_NONE to indicate that
1568      key_flags have been given but they do not specify any usage.  */
1569
1570   return key_usage;
1571 }
1572
1573 /*
1574  * Apply information from SIGNODE (which is the valid self-signature
1575  * associated with that UID) to the UIDNODE:
1576  * - wether the UID has been revoked
1577  * - assumed creation date of the UID
1578  * - temporary store the keyflags here
1579  * - temporary store the key expiration time here
1580  * - mark whether the primary user ID flag hat been set.
1581  * - store the preferences
1582  */
1583 static void
1584 fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
1585 {
1586     PKT_user_id   *uid = uidnode->pkt->pkt.user_id;
1587     PKT_signature *sig = signode->pkt->pkt.signature;
1588     const byte *p, *sym, *hash, *zip;
1589     size_t n, nsym, nhash, nzip;
1590
1591     sig->flags.chosen_selfsig = 1; /* we chose this one */
1592     uid->created = 0; /* not created == invalid */
1593     if ( IS_UID_REV ( sig ) )
1594       {
1595         uid->is_revoked = 1;
1596         return; /* has been revoked */
1597       }
1598     else
1599       uid->is_revoked = 0;
1600
1601     uid->expiredate = sig->expiredate;
1602
1603     if (sig->flags.expired)
1604       {
1605         uid->is_expired = 1;
1606         return; /* has expired */
1607       }
1608     else
1609       uid->is_expired = 0;
1610
1611     uid->created = sig->timestamp; /* this one is okay */
1612     uid->selfsigversion = sig->version;
1613     /* If we got this far, it's not expired :) */
1614     uid->is_expired = 0;
1615
1616     /* store the key flags in the helper variable for later processing */
1617     uid->help_key_usage=parse_key_usage(sig);
1618
1619     /* ditto for the key expiration */
1620     p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1621     if( p && buffer_to_u32(p) )
1622       uid->help_key_expire = keycreated + buffer_to_u32(p);
1623     else
1624       uid->help_key_expire = 0;
1625
1626     /* Set the primary user ID flag - we will later wipe out some
1627      * of them to only have one in our keyblock */
1628     uid->is_primary = 0;
1629     p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
1630     if ( p && *p )
1631         uid->is_primary = 2;
1632     /* We could also query this from the unhashed area if it is not in
1633      * the hased area and then later try to decide which is the better
1634      * there should be no security problem with this.
1635      * For now we only look at the hashed one.
1636      */
1637
1638     /* Now build the preferences list.  These must come from the
1639        hashed section so nobody can modify the ciphers a key is
1640        willing to accept. */
1641     p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
1642     sym = p; nsym = p?n:0;
1643     p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
1644     hash = p; nhash = p?n:0;
1645     p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
1646     zip = p; nzip = p?n:0;
1647     if (uid->prefs)
1648         xfree (uid->prefs);
1649     n = nsym + nhash + nzip;
1650     if (!n)
1651         uid->prefs = NULL;
1652     else {
1653         uid->prefs = xmalloc (sizeof (*uid->prefs) * (n+1));
1654         n = 0;
1655         for (; nsym; nsym--, n++) {
1656             uid->prefs[n].type = PREFTYPE_SYM;
1657             uid->prefs[n].value = *sym++;
1658         }
1659         for (; nhash; nhash--, n++) {
1660             uid->prefs[n].type = PREFTYPE_HASH;
1661             uid->prefs[n].value = *hash++;
1662         }
1663         for (; nzip; nzip--, n++) {
1664             uid->prefs[n].type = PREFTYPE_ZIP;
1665             uid->prefs[n].value = *zip++;
1666         }
1667         uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
1668         uid->prefs[n].value = 0;
1669     }
1670
1671     /* see whether we have the MDC feature */
1672     uid->flags.mdc = 0;
1673     p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1674     if (p && n && (p[0] & 0x01))
1675         uid->flags.mdc = 1;
1676
1677     /* and the keyserver modify flag */
1678     uid->flags.ks_modify = 1;
1679     p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1680     if (p && n && (p[0] & 0x80))
1681         uid->flags.ks_modify = 0;
1682 }
1683
1684 static void
1685 sig_to_revoke_info(PKT_signature *sig,struct revoke_info *rinfo)
1686 {
1687   rinfo->date = sig->timestamp;
1688   rinfo->algo = sig->pubkey_algo;
1689   rinfo->keyid[0] = sig->keyid[0];
1690   rinfo->keyid[1] = sig->keyid[1];
1691 }
1692
1693 static void
1694 merge_selfsigs_main(KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo)
1695 {
1696     PKT_public_key *pk = NULL;
1697     KBNODE k;
1698     u32 kid[2];
1699     u32 sigdate, uiddate, uiddate2;
1700     KBNODE signode, uidnode, uidnode2;
1701     u32 curtime = make_timestamp ();
1702     unsigned int key_usage = 0;
1703     u32 keytimestamp = 0;
1704     u32 key_expire = 0;
1705     int key_expire_seen = 0;
1706     byte sigversion = 0;
1707
1708     *r_revoked = 0;
1709     memset(rinfo,0,sizeof(*rinfo));
1710
1711     if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
1712         BUG ();
1713     pk = keyblock->pkt->pkt.public_key;
1714     keytimestamp = pk->timestamp;
1715
1716     keyid_from_pk( pk, kid );
1717     pk->main_keyid[0] = kid[0];
1718     pk->main_keyid[1] = kid[1];
1719
1720     if ( pk->version < 4 ) {
1721         /* before v4 the key packet itself contains the expiration
1722          * date and there was no way to change it, so we start with
1723          * the one from the key packet */
1724         key_expire = pk->max_expiredate;
1725         key_expire_seen = 1;
1726     }
1727
1728     /* first pass: find the latest direct key self-signature.
1729      * We assume that the newest one overrides all others
1730      */
1731
1732     /* In case this key was already merged */
1733     xfree(pk->revkey);
1734     pk->revkey=NULL;
1735     pk->numrevkeys=0;
1736
1737     signode = NULL;
1738     sigdate = 0; /* helper to find the latest signature */
1739     for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next ) {
1740         if ( k->pkt->pkttype == PKT_SIGNATURE ) {
1741             PKT_signature *sig = k->pkt->pkt.signature;
1742             if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1743                 if ( check_key_signature( keyblock, k, NULL ) )
1744                     ; /* signature did not verify */
1745                 else if ( IS_KEY_REV (sig) ){
1746                     /* key has been revoked - there is no way to override
1747                      * such a revocation, so we theoretically can stop now.
1748                      * We should not cope with expiration times for revocations
1749                      * here because we have to assume that an attacker can
1750                      * generate all kinds of signatures.  However due to the
1751                      * fact that the key has been revoked it does not harm
1752                      * either and by continuing we gather some more info on
1753                      * that key.
1754                      */
1755                     *r_revoked = 1;
1756                     sig_to_revoke_info(sig,rinfo);
1757                 }
1758                 else if ( IS_KEY_SIG (sig) ) {
1759                   /* Add any revocation keys onto the pk.  This is
1760                      particularly interesting since we normally only
1761                      get data from the most recent 1F signature, but
1762                      you need multiple 1F sigs to properly handle
1763                      revocation keys (PGP does it this way, and a
1764                      revocation key could be sensitive and hence in a
1765                      different signature). */
1766                   if(sig->revkey) {
1767                     int i;
1768
1769                     pk->revkey=
1770                       xrealloc(pk->revkey,sizeof(struct revocation_key)*
1771                                 (pk->numrevkeys+sig->numrevkeys));
1772
1773                     for(i=0;i<sig->numrevkeys;i++)
1774                       memcpy(&pk->revkey[pk->numrevkeys++],
1775                              sig->revkey[i],
1776                              sizeof(struct revocation_key));
1777                   }
1778
1779                   if( sig->timestamp >= sigdate ) {
1780                     if(sig->flags.expired)
1781                         ; /* signature has expired - ignore it */
1782                     else {
1783                         sigdate = sig->timestamp;
1784                         signode = k;
1785                         if( sig->version > sigversion )
1786                           sigversion = sig->version;
1787
1788                     }
1789                   }
1790                 }
1791             }
1792         }
1793     }
1794
1795     /* Remove dupes from the revocation keys */
1796
1797     if(pk->revkey)
1798       {
1799         int i,j,x,changed=0;
1800
1801         for(i=0;i<pk->numrevkeys;i++)
1802           {
1803             for(j=i+1;j<pk->numrevkeys;j++)
1804               {
1805                 if(memcmp(&pk->revkey[i],&pk->revkey[j],
1806                           sizeof(struct revocation_key))==0)
1807                   {
1808                     /* remove j */
1809
1810                     for(x=j;x<pk->numrevkeys-1;x++)
1811                       pk->revkey[x]=pk->revkey[x+1];
1812
1813                     pk->numrevkeys--;
1814                     j--;
1815                     changed=1;
1816                   }
1817               }
1818           }
1819
1820         if(changed)
1821           pk->revkey=xrealloc(pk->revkey,
1822                                pk->numrevkeys*sizeof(struct revocation_key));
1823       }
1824
1825     if ( signode )
1826       {
1827         /* some information from a direct key signature take precedence
1828          * over the same information given in UID sigs.
1829          */
1830         PKT_signature *sig = signode->pkt->pkt.signature;
1831         const byte *p;
1832
1833         key_usage=parse_key_usage(sig);
1834
1835         p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1836         if( p && buffer_to_u32(p) )
1837           {
1838             key_expire = keytimestamp + buffer_to_u32(p);
1839             key_expire_seen = 1;
1840           }
1841
1842         /* mark that key as valid: one direct key signature should
1843          * render a key as valid */
1844         pk->is_valid = 1;
1845       }
1846
1847     /* pass 1.5: look for key revocation signatures that were not made
1848        by the key (i.e. did a revocation key issue a revocation for
1849        us?).  Only bother to do this if there is a revocation key in
1850        the first place and we're not revoked already. */
1851
1852     if(!*r_revoked && pk->revkey)
1853       for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
1854         {
1855           if ( k->pkt->pkttype == PKT_SIGNATURE )
1856             {
1857               PKT_signature *sig = k->pkt->pkt.signature;
1858
1859               if(IS_KEY_REV(sig) &&
1860                  (sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
1861                 {
1862                   int rc=check_revocation_keys(pk,sig);
1863                   if(rc==0)
1864                     {
1865                       *r_revoked=2;
1866                       sig_to_revoke_info(sig,rinfo);
1867                       /* don't continue checking since we can't be any
1868                          more revoked than this */
1869                       break;
1870                     }
1871                   else if(rc==G10ERR_NO_PUBKEY)
1872                     pk->maybe_revoked=1;
1873
1874                   /* A failure here means the sig did not verify, was
1875                      not issued by a revocation key, or a revocation
1876                      key loop was broken.  If a revocation key isn't
1877                      findable, however, the key might be revoked and
1878                      we don't know it. */
1879
1880                   /* TODO: In the future handle subkey and cert
1881                      revocations?  PGP doesn't, but it's in 2440. */
1882                 }
1883             }
1884         }
1885
1886     /* second pass: look at the self-signature of all user IDs */
1887     signode = uidnode = NULL;
1888     sigdate = 0; /* helper to find the latest signature in one user ID */
1889     for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1890         if ( k->pkt->pkttype == PKT_USER_ID ) {
1891             if ( uidnode && signode )
1892               {
1893                 fixup_uidnode ( uidnode, signode, keytimestamp );
1894                 pk->is_valid=1;
1895               }
1896             uidnode = k;
1897             signode = NULL;
1898             sigdate = 0;
1899         }
1900         else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
1901             PKT_signature *sig = k->pkt->pkt.signature;
1902             if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1903                 if ( check_key_signature( keyblock, k, NULL ) )
1904                     ; /* signature did not verify */
1905                 else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
1906                           && sig->timestamp >= sigdate )
1907                   {
1908                     /* Note: we allow to invalidate cert revocations
1909                      * by a newer signature.  An attacker can't use this
1910                      * because a key should be revoced with a key revocation.
1911                      * The reason why we have to allow for that is that at
1912                      * one time an email address may become invalid but later
1913                      * the same email address may become valid again (hired,
1914                      * fired, hired again).
1915                      */
1916
1917                     sigdate = sig->timestamp;
1918                     signode = k;
1919                     signode->pkt->pkt.signature->flags.chosen_selfsig=0;
1920                     if( sig->version > sigversion )
1921                       sigversion = sig->version;
1922                   }
1923             }
1924         }
1925     }
1926     if ( uidnode && signode ) {
1927         fixup_uidnode ( uidnode, signode, keytimestamp );
1928         pk->is_valid = 1;
1929     }
1930
1931     /* If the key isn't valid yet, and we have
1932        --allow-non-selfsigned-uid set, then force it valid. */
1933     if(!pk->is_valid && opt.allow_non_selfsigned_uid)
1934       {
1935         if(opt.verbose)
1936           log_info(_("Invalid key %s made valid by"
1937                      " --allow-non-selfsigned-uid\n"),keystr_from_pk(pk));
1938         pk->is_valid = 1;
1939       }
1940
1941     /* The key STILL isn't valid, so try and find an ultimately
1942        trusted signature. */
1943     if(!pk->is_valid)
1944       {
1945         uidnode=NULL;
1946
1947         for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
1948           {
1949             if ( k->pkt->pkttype == PKT_USER_ID )
1950               uidnode = k;
1951             else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
1952               {
1953                 PKT_signature *sig = k->pkt->pkt.signature;
1954
1955                 if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
1956                   {
1957                     PKT_public_key *ultimate_pk;
1958
1959                     ultimate_pk=xmalloc_clear(sizeof(*ultimate_pk));
1960
1961                     /* We don't want to use the full get_pubkey to
1962                        avoid infinite recursion in certain cases.
1963                        There is no reason to check that an ultimately
1964                        trusted key is still valid - if it has been
1965                        revoked or the user should also renmove the
1966                        ultimate trust flag.  */
1967                     if(get_pubkey_fast(ultimate_pk,sig->keyid)==0
1968                        && check_key_signature2(keyblock,k,ultimate_pk,
1969                                                NULL,NULL,NULL,NULL)==0
1970                        && get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
1971                       {
1972                         free_public_key(ultimate_pk);
1973                         pk->is_valid=1;
1974                         break;
1975                       }
1976
1977                     free_public_key(ultimate_pk);
1978                   }
1979               }
1980           }
1981       }
1982
1983     /* Record the highest selfsig version so we know if this is a v3
1984        key through and through, or a v3 key with a v4 selfsig
1985        somewhere.  This is useful in a few places to know if the key
1986        must be treated as PGP2-style or OpenPGP-style.  Note that a
1987        selfsig revocation with a higher version number will also raise
1988        this value.  This is okay since such a revocation must be
1989        issued by the user (i.e. it cannot be issued by someone else to
1990        modify the key behavior.) */
1991
1992     pk->selfsigversion=sigversion;
1993
1994     /* Now that we had a look at all user IDs we can now get some information
1995      * from those user IDs.
1996      */
1997
1998     if ( !key_usage ) {
1999         /* find the latest user ID with key flags set */
2000         uiddate = 0; /* helper to find the latest user ID */
2001         for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2002             k = k->next ) {
2003             if ( k->pkt->pkttype == PKT_USER_ID ) {
2004                 PKT_user_id *uid = k->pkt->pkt.user_id;
2005                 if ( uid->help_key_usage && uid->created > uiddate ) {
2006                     key_usage = uid->help_key_usage;
2007                     uiddate = uid->created;
2008                 }
2009             }
2010         }
2011     }
2012     if ( !key_usage ) { /* no key flags at all: get it from the algo */
2013         key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
2014     }
2015     else { /* check that the usage matches the usage as given by the algo */
2016         int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
2017         if ( x ) /* mask it down to the actual allowed usage */
2018             key_usage &= x;
2019     }
2020
2021     /* Whatever happens, it's a primary key, so it can certify. */
2022     pk->pubkey_usage = key_usage|PUBKEY_USAGE_CERT;
2023
2024     if ( !key_expire_seen ) {
2025         /* find the latest valid user ID with a key expiration set
2026          * Note, that this may be a different one from the above because
2027          * some user IDs may have no expiration date set */
2028         uiddate = 0;
2029         for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2030             k = k->next ) {
2031             if ( k->pkt->pkttype == PKT_USER_ID ) {
2032                 PKT_user_id *uid = k->pkt->pkt.user_id;
2033                 if ( uid->help_key_expire && uid->created > uiddate ) {
2034                     key_expire = uid->help_key_expire;
2035                     uiddate = uid->created;
2036                 }
2037             }
2038         }
2039     }
2040
2041     /* Currently only v3 keys have a maximum expiration date, but I'll
2042        bet v5 keys get this feature again. */
2043     if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
2044       key_expire=pk->max_expiredate;
2045
2046     pk->has_expired = key_expire >= curtime? 0 : key_expire;
2047     pk->expiredate = key_expire;
2048
2049     /* Fixme: we should see how to get rid of the expiretime fields  but
2050      * this needs changes at other places too. */
2051
2052     /* and now find the real primary user ID and delete all others */
2053     uiddate = uiddate2 = 0;
2054     uidnode = uidnode2 = NULL;
2055     for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
2056         if ( k->pkt->pkttype == PKT_USER_ID &&
2057              !k->pkt->pkt.user_id->attrib_data) {
2058             PKT_user_id *uid = k->pkt->pkt.user_id;
2059             if (uid->is_primary)
2060               {
2061                 if(uid->created > uiddate)
2062                   {
2063                     uiddate = uid->created;
2064                     uidnode = k;
2065                   }
2066                 else if(uid->created==uiddate && uidnode)
2067                   {
2068                     /* The dates are equal, so we need to do a
2069                        different (and arbitrary) comparison.  This
2070                        should rarely, if ever, happen.  It's good to
2071                        try and guarantee that two different GnuPG
2072                        users with two different keyrings at least pick
2073                        the same primary. */
2074                     if(cmp_user_ids(uid,uidnode->pkt->pkt.user_id)>0)
2075                       uidnode=k;
2076                   }
2077               }
2078             else
2079               {
2080                 if(uid->created > uiddate2)
2081                   {
2082                     uiddate2 = uid->created;
2083                     uidnode2 = k;
2084                   }
2085                 else if(uid->created==uiddate2 && uidnode2)
2086                   {
2087                     if(cmp_user_ids(uid,uidnode2->pkt->pkt.user_id)>0)
2088                       uidnode2=k;
2089                   }
2090               }
2091         }
2092     }
2093     if ( uidnode ) {
2094         for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2095             k = k->next ) {
2096             if ( k->pkt->pkttype == PKT_USER_ID &&
2097                  !k->pkt->pkt.user_id->attrib_data) {
2098                 PKT_user_id *uid = k->pkt->pkt.user_id;
2099                 if ( k != uidnode )
2100                     uid->is_primary = 0;
2101             }
2102         }
2103     }
2104     else if( uidnode2 ) {
2105         /* none is flagged primary - use the latest user ID we have,
2106            and disambiguate with the arbitrary packet comparison. */
2107         uidnode2->pkt->pkt.user_id->is_primary = 1;
2108     }
2109     else
2110       {
2111         /* None of our uids were self-signed, so pick the one that
2112            sorts first to be the primary.  This is the best we can do
2113            here since there are no self sigs to date the uids. */
2114
2115         uidnode = NULL;
2116
2117         for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2118             k = k->next )
2119           {
2120             if(k->pkt->pkttype==PKT_USER_ID
2121                && !k->pkt->pkt.user_id->attrib_data)
2122               {
2123                 if(!uidnode)
2124                   {
2125                     uidnode=k;
2126                     uidnode->pkt->pkt.user_id->is_primary=1;
2127                     continue;
2128                   }
2129                 else
2130                   {
2131                     if(cmp_user_ids(k->pkt->pkt.user_id,
2132                                     uidnode->pkt->pkt.user_id)>0)
2133                       {
2134                         uidnode->pkt->pkt.user_id->is_primary=0;
2135                         uidnode=k;
2136                         uidnode->pkt->pkt.user_id->is_primary=1;
2137                       }
2138                     else
2139                       k->pkt->pkt.user_id->is_primary=0; /* just to be
2140                                                             safe */
2141                   }
2142               }
2143           }
2144       }
2145 }
2146
2147 /* Convert a buffer to a signature.  Useful for 0x19 embedded sigs.
2148    Caller must free the signature when they are done. */
2149 static PKT_signature *
2150 buf_to_sig(const byte *buf,size_t len)
2151 {
2152   PKT_signature *sig=xmalloc_clear(sizeof(PKT_signature));
2153   IOBUF iobuf=iobuf_temp_with_content(buf,len);
2154   int save_mode=set_packet_list_mode(0);
2155
2156   if(parse_signature(iobuf,PKT_SIGNATURE,len,sig)!=0)
2157     {
2158       xfree(sig);
2159       sig=NULL;
2160     }
2161
2162   set_packet_list_mode(save_mode);
2163   iobuf_close(iobuf);
2164
2165   return sig;
2166 }
2167
2168 static void
2169 merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
2170 {
2171     PKT_public_key *mainpk = NULL, *subpk = NULL;
2172     PKT_signature *sig;
2173     KBNODE k;
2174     u32 mainkid[2];
2175     u32 sigdate = 0;
2176     KBNODE signode;
2177     u32 curtime = make_timestamp ();
2178     unsigned int key_usage = 0;
2179     u32 keytimestamp = 0;
2180     u32 key_expire = 0;
2181     const byte *p;
2182
2183     if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2184         BUG ();
2185     mainpk = keyblock->pkt->pkt.public_key;
2186     if ( mainpk->version < 4 )
2187         return; /* (actually this should never happen) */
2188     keyid_from_pk( mainpk, mainkid );
2189     subpk = subnode->pkt->pkt.public_key;
2190     keytimestamp = subpk->timestamp;
2191
2192     subpk->is_valid = 0;
2193     subpk->main_keyid[0] = mainpk->main_keyid[0];
2194     subpk->main_keyid[1] = mainpk->main_keyid[1];
2195
2196     /* find the latest key binding self-signature. */
2197     signode = NULL;
2198     sigdate = 0; /* helper to find the latest signature */
2199     for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2200                                                         k = k->next ) {
2201         if ( k->pkt->pkttype == PKT_SIGNATURE ) {
2202             sig = k->pkt->pkt.signature;
2203             if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
2204                 if ( check_key_signature( keyblock, k, NULL ) )
2205                     ; /* signature did not verify */
2206                 else if ( IS_SUBKEY_REV (sig) ) {
2207                   /* Note that this means that the date on a
2208                      revocation sig does not matter - even if the
2209                      binding sig is dated after the revocation sig,
2210                      the subkey is still marked as revoked.  This
2211                      seems ok, as it is just as easy to make new
2212                      subkeys rather than re-sign old ones as the
2213                      problem is in the distribution.  Plus, PGP (7)
2214                      does this the same way.  */
2215                     subpk->is_revoked = 1;
2216                     sig_to_revoke_info(sig,&subpk->revoked);
2217                     /* although we could stop now, we continue to
2218                      * figure out other information like the old expiration
2219                      * time */
2220                 }
2221                 else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate )
2222                   {
2223                     if(sig->flags.expired)
2224                       ; /* signature has expired - ignore it */
2225                     else
2226                       {
2227                         sigdate = sig->timestamp;
2228                         signode = k;
2229                         signode->pkt->pkt.signature->flags.chosen_selfsig=0;
2230                       }
2231                   }
2232             }
2233         }
2234     }
2235
2236     /* no valid key binding */
2237     if ( !signode )
2238       return;
2239
2240     sig = signode->pkt->pkt.signature;
2241     sig->flags.chosen_selfsig=1; /* so we know which selfsig we chose later */
2242
2243     key_usage=parse_key_usage(sig);
2244     if ( !key_usage )
2245       {
2246         /* no key flags at all: get it from the algo */
2247         key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2248       }
2249     else
2250       {
2251         /* check that the usage matches the usage as given by the algo */
2252         int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2253         if ( x ) /* mask it down to the actual allowed usage */
2254           key_usage &= x;
2255       }
2256
2257     subpk->pubkey_usage = key_usage;
2258
2259     p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2260     if ( p && buffer_to_u32(p) )
2261         key_expire = keytimestamp + buffer_to_u32(p);
2262     else
2263         key_expire = 0;
2264     subpk->has_expired = key_expire >= curtime? 0 : key_expire;
2265     subpk->expiredate = key_expire;
2266
2267     /* algo doesn't exist */
2268     if(openpgp_pk_test_algo(subpk->pubkey_algo))
2269       return;
2270
2271     subpk->is_valid = 1;
2272
2273     /* Find the most recent 0x19 embedded signature on our self-sig. */
2274     if(subpk->backsig==0)
2275       {
2276         int seq=0;
2277         size_t n;
2278         PKT_signature *backsig=NULL;
2279
2280         sigdate=0;
2281
2282         /* We do this while() since there may be other embedded
2283            signatures in the future.  We only want 0x19 here. */
2284
2285         while((p=enum_sig_subpkt(sig->hashed,
2286                                  SIGSUBPKT_SIGNATURE,&n,&seq,NULL)))
2287           if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2288             {
2289               PKT_signature *tempsig=buf_to_sig(p,n);
2290               if(tempsig)
2291                 {
2292                   if(tempsig->timestamp>sigdate)
2293                     {
2294                       if(backsig)
2295                         free_seckey_enc(backsig);
2296
2297                       backsig=tempsig;
2298                       sigdate=backsig->timestamp;
2299                     }
2300                   else
2301                     free_seckey_enc(tempsig);
2302                 }
2303             }
2304
2305         seq=0;
2306
2307         /* It is safe to have this in the unhashed area since the 0x19
2308            is located on the selfsig for convenience, not security. */
2309
2310         while((p=enum_sig_subpkt(sig->unhashed,SIGSUBPKT_SIGNATURE,
2311                                  &n,&seq,NULL)))
2312           if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2313             {
2314               PKT_signature *tempsig=buf_to_sig(p,n);
2315               if(tempsig)
2316                 {
2317                   if(tempsig->timestamp>sigdate)
2318                     {
2319                       if(backsig)
2320                         free_seckey_enc(backsig);
2321
2322                       backsig=tempsig;
2323                       sigdate=backsig->timestamp;
2324                     }
2325                   else
2326                     free_seckey_enc(tempsig);
2327                 }
2328             }
2329
2330         if(backsig)
2331           {
2332             /* At ths point, backsig contains the most recent 0x19 sig.
2333                Let's see if it is good. */
2334
2335             /* 2==valid, 1==invalid, 0==didn't check */
2336             if(check_backsig(mainpk,subpk,backsig)==0)
2337               subpk->backsig=2;
2338             else
2339               subpk->backsig=1;
2340
2341             free_seckey_enc(backsig);
2342           }
2343       }
2344 }
2345
2346
2347 /*
2348  * Merge information from the self-signatures with the key, so that
2349  * we can later use them more easy.
2350  * The function works by first applying the self signatures to the
2351  * primary key and the to each subkey.
2352  * Here are the rules we use to decide which inormation from which
2353  * self-signature is used:
2354  * We check all self signatures or validity and ignore all invalid signatures.
2355  * All signatures are then ordered by their creation date ....
2356  * For the primary key:
2357  *   FIXME the docs
2358  */
2359 static void
2360 merge_selfsigs( KBNODE keyblock )
2361 {
2362     KBNODE k;
2363     int revoked;
2364     struct revoke_info rinfo;
2365     PKT_public_key *main_pk;
2366     prefitem_t *prefs;
2367     int mdc_feature;
2368
2369     if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
2370         if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
2371             log_error ("expected public key but found secret key "
2372                        "- must stop\n");
2373             /* we better exit here becuase a public key is expected at
2374                other places too.  FIXME: Figure this out earlier and
2375                don't get to here at all */
2376             g10_exit (1);
2377         }
2378         BUG ();
2379     }
2380
2381     merge_selfsigs_main ( keyblock, &revoked, &rinfo );
2382
2383     /* now merge in the data from each of the subkeys */
2384     for(k=keyblock; k; k = k->next ) {
2385         if (  k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2386             merge_selfsigs_subkey ( keyblock, k );
2387         }
2388     }
2389
2390     main_pk = keyblock->pkt->pkt.public_key;
2391     if ( revoked || main_pk->has_expired || !main_pk->is_valid ) {
2392         /* if the primary key is revoked, expired, or invalid we
2393          * better set the appropriate flags on that key and all
2394          * subkeys */
2395         for(k=keyblock; k; k = k->next ) {
2396             if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2397                 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2398                 PKT_public_key *pk = k->pkt->pkt.public_key;
2399                 if(!main_pk->is_valid)
2400                   pk->is_valid = 0;
2401                 if(revoked && !pk->is_revoked)
2402                   {
2403                     pk->is_revoked = revoked;
2404                     memcpy(&pk->revoked,&rinfo,sizeof(rinfo));
2405                   }
2406                 if(main_pk->has_expired)
2407                   pk->has_expired = main_pk->has_expired;
2408             }
2409         }
2410         return;
2411     }
2412
2413     /* set the preference list of all keys to those of the primary real
2414      * user ID.  Note: we use these preferences when we don't know by
2415      * which user ID the key has been selected.
2416      * fixme: we should keep atoms of commonly used preferences or
2417      * use reference counting to optimize the preference lists storage.
2418      * FIXME: it might be better to use the intersection of
2419      * all preferences.
2420      * Do a similar thing for the MDC feature flag.
2421      */
2422     prefs = NULL;
2423     mdc_feature = 0;
2424     for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
2425         if (k->pkt->pkttype == PKT_USER_ID
2426             && !k->pkt->pkt.user_id->attrib_data
2427             && k->pkt->pkt.user_id->is_primary) {
2428             prefs = k->pkt->pkt.user_id->prefs;
2429             mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2430             break;
2431         }
2432     }
2433     for(k=keyblock; k; k = k->next ) {
2434         if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2435              || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2436             PKT_public_key *pk = k->pkt->pkt.public_key;
2437             if (pk->prefs)
2438                 xfree (pk->prefs);
2439             pk->prefs = copy_prefs (prefs);
2440             pk->mdc_feature = mdc_feature;
2441         }
2442     }
2443 }
2444
2445
2446 /*
2447  * Merge the secret keys from secblock into the pubblock thereby
2448  * replacing the public (sub)keys with their secret counterparts Hmmm:
2449  * It might be better to get away from the concept of entire secret
2450  * keys at all and have a way to store just the real secret parts
2451  * from the key.
2452  */
2453 static void
2454 merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2455 {
2456     KBNODE pub;
2457
2458     assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2459     assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2460
2461     for (pub=pubblock; pub; pub = pub->next ) {
2462         if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
2463              PKT_public_key *pk = pub->pkt->pkt.public_key;
2464              PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
2465              assert ( pub == pubblock ); /* only in the first node */
2466              /* there is nothing to compare in this case, so just replace
2467               * some information */
2468              copy_public_parts_to_secret_key ( pk, sk );
2469              free_public_key ( pk );
2470              pub->pkt->pkttype = PKT_SECRET_KEY;
2471              pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2472         }
2473         else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2474             KBNODE sec;
2475             PKT_public_key *pk = pub->pkt->pkt.public_key;
2476
2477             /* this is more complicated: it may happen that the sequence
2478              * of the subkeys dosn't match, so we have to find the
2479              * appropriate secret key */
2480             for (sec=secblock->next; sec; sec = sec->next ) {
2481                 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2482                     PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2483                     if ( !cmp_public_secret_key ( pk, sk ) ) {
2484                         copy_public_parts_to_secret_key ( pk, sk );
2485                         free_public_key ( pk );
2486                         pub->pkt->pkttype = PKT_SECRET_SUBKEY;
2487                         pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2488                         break;
2489                     }
2490                 }
2491             }
2492             if ( !sec )
2493                 BUG(); /* already checked in premerge */
2494         }
2495     }
2496 }
2497
2498 /* This function checks that for every public subkey a corresponding
2499  * secret subkey is available and deletes the public subkey otherwise.
2500  * We need this function because we can't delete it later when we
2501  * actually merge the secret parts into the pubring.
2502  * The function also plays some games with the node flags.
2503  */
2504 static void
2505 premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2506 {
2507     KBNODE last, pub;
2508
2509     assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2510     assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2511
2512     for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
2513         pub->flag &= ~3; /* reset bits 0 and 1 */
2514         if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2515             KBNODE sec;
2516             PKT_public_key *pk = pub->pkt->pkt.public_key;
2517
2518             for (sec=secblock->next; sec; sec = sec->next ) {
2519                 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2520                     PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2521                     if ( !cmp_public_secret_key ( pk, sk ) ) {
2522                         if ( sk->protect.s2k.mode == 1001 ) {
2523                             /* The secret parts are not available so
2524                                we can't use that key for signing etc.
2525                                Fix the pubkey usage */
2526                             pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
2527                                                   |PUBKEY_USAGE_AUTH);
2528                         }
2529                         /* transfer flag bits 0 and 1 to the pubblock */
2530                         pub->flag |= (sec->flag &3);
2531                         break;
2532                     }
2533                 }
2534             }
2535             if ( !sec ) {
2536                 KBNODE next, ll;
2537
2538                 if (opt.verbose)
2539                   log_info (_("no secret subkey"
2540                               " for public subkey %s - ignoring\n"),
2541                             keystr_from_pk (pk));
2542                 /* we have to remove the subkey in this case */
2543                 assert ( last );
2544                 /* find the next subkey */
2545                 for (next=pub->next,ll=pub;
2546                      next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2547                      ll = next, next = next->next )
2548                     ;
2549                 /* make new link */
2550                 last->next = next;
2551                 /* release this public subkey with all sigs */
2552                 ll->next = NULL;
2553                 release_kbnode( pub );
2554                 /* let the loop continue */
2555                 pub = last;
2556             }
2557         }
2558     }
2559     /* We need to copy the found bits (0 and 1) from the secret key to
2560        the public key.  This has already been done for the subkeys but
2561        got lost on the primary key - fix it here *. */
2562     pubblock->flag |= (secblock->flag & 3);
2563 }
2564
2565
2566
2567 \f
2568 /* See see whether the key fits
2569  * our requirements and in case we do not
2570  * request the primary key, we should select
2571  * a suitable subkey.
2572  * FIXME: Check against PGP 7 whether we still need a kludge
2573  *        to favor type 16 keys over type 20 keys when type 20
2574  *        has not been explitely requested.
2575  * Returns: True when a suitable key has been found.
2576  *
2577  * We have to distinguish four cases:  FIXME!
2578  *  1. No usage and no primary key requested
2579  *     Examples for this case are that we have a keyID to be used
2580  *     for decrytion or verification.
2581  *  2. No usage but primary key requested
2582  *     This is the case for all functions which work on an
2583  *     entire keyblock, e.g. for editing or listing
2584  *  3. Usage and primary key requested
2585  *     FXME
2586  *  4. Usage but no primary key requested
2587  *     FIXME
2588  * FIXME: Tell what is going to happen here and something about the rationale
2589  * Note: We don't use this function if no specific usage is requested;
2590  *       This way the getkey functions can be used for plain key listings.
2591  *
2592  * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2593  * is the key we actually found by looking at the keyid or a fingerprint and
2594  * may eitehr point to the primary or one of the subkeys.
2595  */
2596
2597 static int
2598 finish_lookup (GETKEY_CTX ctx)
2599 {
2600     KBNODE keyblock = ctx->keyblock;
2601     KBNODE k;
2602     KBNODE foundk = NULL;
2603     PKT_user_id *foundu = NULL;
2604 #define USAGE_MASK  (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2605     unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
2606     /* Request the primary if we're certifying another key, and also
2607        if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2608        do not understand signatures made by a signing subkey.  PGP 8
2609        does. */
2610     int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2611       ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2612     u32 latest_date;
2613     KBNODE latest_key;
2614     u32 curtime = make_timestamp ();
2615
2616     assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
2617
2618     ctx->found_key = NULL;
2619
2620     if (ctx->exact) {
2621         for (k=keyblock; k; k = k->next) {
2622             if ( (k->flag & 1) ) {
2623                 assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
2624                          || k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
2625                 foundk = k;
2626                 break;
2627             }
2628         }
2629     }
2630
2631     for (k=keyblock; k; k = k->next) {
2632         if ( (k->flag & 2) ) {
2633             assert (k->pkt->pkttype == PKT_USER_ID);
2634             foundu = k->pkt->pkt.user_id;
2635             break;
2636         }
2637     }
2638
2639     if ( DBG_CACHE )
2640         log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2641                    (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
2642                    foundk? "one":"all", req_usage);
2643
2644     if (!req_usage) {
2645         latest_key = foundk? foundk:keyblock;
2646         goto found;
2647     }
2648
2649     latest_date = 0;
2650     latest_key  = NULL;
2651     /* do not look at subkeys if a certification key is requested */
2652     if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
2653         KBNODE nextk;
2654         /* either start a loop or check just this one subkey */
2655         for (k=foundk?foundk:keyblock; k; k = nextk ) {
2656             PKT_public_key *pk;
2657             nextk = k->next;
2658             if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2659                 continue;
2660             if ( foundk )
2661                 nextk = NULL;  /* what a hack */
2662             pk = k->pkt->pkt.public_key;
2663             if (DBG_CACHE)
2664                 log_debug( "\tchecking subkey %08lX\n",
2665                            (ulong)keyid_from_pk( pk, NULL));
2666             if ( !pk->is_valid ) {
2667                 if (DBG_CACHE)
2668                     log_debug( "\tsubkey not valid\n");
2669                 continue;
2670             }
2671             if ( pk->is_revoked ) {
2672                 if (DBG_CACHE)
2673                     log_debug( "\tsubkey has been revoked\n");
2674                 continue;
2675             }
2676             if ( pk->has_expired ) {
2677                 if (DBG_CACHE)
2678                     log_debug( "\tsubkey has expired\n");
2679                 continue;
2680             }
2681             if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
2682                 if (DBG_CACHE)
2683                     log_debug( "\tsubkey not yet valid\n");
2684                 continue;
2685             }
2686
2687             if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2688                 if (DBG_CACHE)
2689                     log_debug( "\tusage does not match: want=%x have=%x\n",
2690                                req_usage, pk->pubkey_usage );
2691                 continue;
2692             }
2693
2694             if (DBG_CACHE)
2695                 log_debug( "\tsubkey might be fine\n");
2696             /* In case a key has a timestamp of 0 set, we make sure
2697                that it is used.  A better change would be to compare
2698                ">=" but that might also change the selected keys and
2699                is as such a more intrusive change.  */
2700             if ( pk->timestamp > latest_date
2701                  || (!pk->timestamp && !latest_date)) {
2702                 latest_date = pk->timestamp;
2703                 latest_key  = k;
2704             }
2705         }
2706     }
2707
2708     /* Okay now try the primary key unless we want an exact
2709      * key ID match on a subkey */
2710     if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
2711         PKT_public_key *pk;
2712         if (DBG_CACHE && !foundk && !req_prim )
2713             log_debug( "\tno suitable subkeys found - trying primary\n");
2714         pk = keyblock->pkt->pkt.public_key;
2715         if ( !pk->is_valid ) {
2716             if (DBG_CACHE)
2717                 log_debug( "\tprimary key not valid\n");
2718         }
2719         else if ( pk->is_revoked ) {
2720             if (DBG_CACHE)
2721                 log_debug( "\tprimary key has been revoked\n");
2722         }
2723         else if ( pk->has_expired ) {
2724             if (DBG_CACHE)
2725                 log_debug( "\tprimary key has expired\n");
2726         }
2727         else  if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2728             if (DBG_CACHE)
2729                 log_debug( "\tprimary key usage does not match: "
2730                            "want=%x have=%x\n",
2731                            req_usage, pk->pubkey_usage );
2732         }
2733         else { /* okay */
2734             if (DBG_CACHE)
2735                 log_debug( "\tprimary key may be used\n");
2736             latest_key = keyblock;
2737             latest_date = pk->timestamp;
2738         }
2739     }
2740
2741     if ( !latest_key ) {
2742         if (DBG_CACHE)
2743             log_debug("\tno suitable key found -  giving up\n");
2744         return 0;
2745     }
2746
2747  found:
2748     if (DBG_CACHE)
2749         log_debug( "\tusing key %08lX\n",
2750                 (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
2751
2752     if (latest_key) {
2753         PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2754         if (pk->user_id)
2755             free_user_id (pk->user_id);
2756         pk->user_id = scopy_user_id (foundu);
2757     }
2758
2759     ctx->found_key = latest_key;
2760
2761     if (latest_key != keyblock && opt.verbose)
2762       {
2763         char *tempkeystr=
2764           xstrdup(keystr_from_pk(latest_key->pkt->pkt.public_key));
2765         log_info(_("using subkey %s instead of primary key %s\n"),
2766                  tempkeystr, keystr_from_pk(keyblock->pkt->pkt.public_key));
2767         xfree(tempkeystr);
2768       }
2769
2770     cache_user_id( keyblock );
2771
2772     return 1; /* found */
2773 }
2774
2775
2776 static int
2777 lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
2778 {
2779     int rc;
2780     KBNODE secblock = NULL; /* helper */
2781     int no_suitable_key = 0;
2782
2783     rc = 0;
2784     while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
2785         /* If we are searching for the first key we have to make sure
2786            that the next iteration does not do an implicit reset.
2787            This can be triggered by an empty key ring. */
2788         if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2789             ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2790
2791         rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2792         if (rc) {
2793             log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
2794             rc = 0;
2795             goto skip;
2796         }
2797
2798         if ( secmode ) {
2799             /* find the correspondig public key and use this
2800              * this one for the selection process */
2801             u32 aki[2];
2802             KBNODE k = ctx->keyblock;
2803
2804             if (k->pkt->pkttype != PKT_SECRET_KEY)
2805                 BUG();
2806
2807             keyid_from_sk (k->pkt->pkt.secret_key, aki);
2808             k = get_pubkeyblock (aki);
2809             if( !k )
2810               {
2811                 if (!opt.quiet)
2812                   log_info(_("key %s: secret key without public key"
2813                              " - skipped\n"), keystr(aki));
2814                 goto skip;
2815               }
2816             secblock = ctx->keyblock;
2817             ctx->keyblock = k;
2818
2819             premerge_public_with_secret ( ctx->keyblock, secblock );
2820         }
2821
2822         /* warning: node flag bits 0 and 1 should be preserved by
2823          * merge_selfsigs.  For secret keys, premerge did tranfer the
2824          * keys to the keyblock */
2825         merge_selfsigs ( ctx->keyblock );
2826         if ( finish_lookup (ctx) ) {
2827             no_suitable_key = 0;
2828             if ( secmode ) {
2829                 merge_public_with_secret ( ctx->keyblock,
2830                                            secblock);
2831                 release_kbnode (secblock);
2832                 secblock = NULL;
2833             }
2834             goto found;
2835         }
2836         else
2837             no_suitable_key = 1;
2838
2839       skip:
2840         /* release resources and continue search */
2841         if ( secmode ) {
2842             release_kbnode( secblock );
2843             secblock = NULL;
2844         }
2845         release_kbnode( ctx->keyblock );
2846         ctx->keyblock = NULL;
2847     }
2848
2849   found:
2850     if( rc && rc != -1 )
2851         log_error("keydb_search failed: %s\n", g10_errstr(rc));
2852
2853     if( !rc ) {
2854         *ret_keyblock = ctx->keyblock; /* return the keyblock */
2855         ctx->keyblock = NULL;
2856     }
2857     else if (rc == -1 && no_suitable_key)
2858         rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
2859     else if( rc == -1 )
2860         rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
2861
2862     if ( secmode ) {
2863         release_kbnode( secblock );
2864         secblock = NULL;
2865     }
2866     release_kbnode( ctx->keyblock );
2867     ctx->keyblock = NULL;
2868
2869     ctx->last_rc = rc;
2870     return rc;
2871 }
2872
2873
2874
2875
2876 /****************
2877  * FIXME: Replace by the generic function
2878  *        It does not work as it is right now - it is used at
2879  *        2 places:  a) to get the key for an anonyous recipient
2880  *                   b) to get the ultimately trusted keys.
2881  *        The a) usage might have some problems.
2882  *
2883  * set with_subkeys true to include subkeys
2884  * set with_spm true to include secret-parts-missing keys
2885  *
2886  * Enumerate all primary secret keys.  Caller must use these procedure:
2887  *  1) create a void pointer and initialize it to NULL
2888  *  2) pass this void pointer by reference to this function
2889  *     and provide space for the secret key (pass a buffer for sk)
2890  *  3) call this function as long as it does not return -1
2891  *     to indicate EOF.
2892  *  4) Always call this function a last time with SK set to NULL,
2893  *     so that can free it's context.
2894  */
2895 int
2896 enum_secret_keys( void **context, PKT_secret_key *sk,
2897                   int with_subkeys, int with_spm )
2898 {
2899     int rc=0;
2900     struct {
2901         int eof;
2902         int first;
2903         KEYDB_HANDLE hd;
2904         KBNODE keyblock;
2905         KBNODE node;
2906     } *c = *context;
2907
2908
2909     if( !c ) { /* make a new context */
2910         c = xmalloc_clear( sizeof *c );
2911         *context = c;
2912         c->hd = keydb_new (1);
2913         c->first = 1;
2914         c->keyblock = NULL;
2915         c->node = NULL;
2916     }
2917
2918     if( !sk ) { /* free the context */
2919         keydb_release (c->hd);
2920         release_kbnode (c->keyblock);
2921         xfree( c );
2922         *context = NULL;
2923         return 0;
2924     }
2925
2926     if( c->eof )
2927         return -1;
2928
2929     do {
2930         /* get the next secret key from the current keyblock */
2931         for (; c->node; c->node = c->node->next) {
2932             if ((c->node->pkt->pkttype == PKT_SECRET_KEY
2933                 || (with_subkeys
2934                     && c->node->pkt->pkttype == PKT_SECRET_SUBKEY) )
2935                 && !(c->node->pkt->pkt.secret_key->protect.s2k.mode==1001
2936                      && !with_spm)) {
2937                 copy_secret_key (sk, c->node->pkt->pkt.secret_key );
2938                 c->node = c->node->next;
2939                 return 0; /* found */
2940             }
2941         }
2942         release_kbnode (c->keyblock);
2943         c->keyblock = c->node = NULL;
2944
2945         rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
2946         c->first = 0;
2947         if (rc) {
2948             keydb_release (c->hd); c->hd = NULL;
2949             c->eof = 1;
2950             return -1; /* eof */
2951         }
2952
2953         rc = keydb_get_keyblock (c->hd, &c->keyblock);
2954         c->node = c->keyblock;
2955     } while (!rc);
2956
2957     return rc; /* error */
2958 }
2959
2960
2961 \f
2962 /*********************************************
2963  ***********  user ID printing helpers *******
2964  *********************************************/
2965
2966 /****************
2967  * Return a string with a printable representation of the user_id.
2968  * this string must be freed by xfree.
2969  */
2970 char*
2971 get_user_id_string( u32 *keyid )
2972 {
2973   user_id_db_t r;
2974   char *p;
2975   int pass=0;
2976   /* try it two times; second pass reads from key resources */
2977   do
2978     {
2979       for(r=user_id_db; r; r = r->next )
2980         {
2981           keyid_list_t a;
2982           for (a=r->keyids; a; a= a->next )
2983             {
2984               if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] )
2985                 {
2986                   p = xmalloc( keystrlen() + 1 + r->len + 1 );
2987                   sprintf(p, "%s %.*s", keystr(keyid), r->len, r->name );
2988                   return p;
2989                 }
2990             }
2991         }
2992     } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2993   p = xmalloc( keystrlen() + 5 );
2994   sprintf(p, "%s [?]", keystr(keyid));
2995   return p;
2996 }
2997
2998
2999 char*
3000 get_user_id_string_native ( u32 *keyid )
3001 {
3002   char *p = get_user_id_string( keyid );
3003   char *p2 = utf8_to_native( p, strlen(p), 0 );
3004   xfree(p);
3005   return p2;
3006 }
3007
3008
3009 char*
3010 get_long_user_id_string( u32 *keyid )
3011 {
3012     user_id_db_t r;
3013     char *p;
3014     int pass=0;
3015     /* try it two times; second pass reads from key resources */
3016     do {
3017         for(r=user_id_db; r; r = r->next ) {
3018             keyid_list_t a;
3019             for (a=r->keyids; a; a= a->next ) {
3020                 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
3021                     p = xmalloc( r->len + 20 );
3022                     sprintf(p, "%08lX%08lX %.*s",
3023                             (ulong)keyid[0], (ulong)keyid[1],
3024                             r->len, r->name );
3025                     return p;
3026                 }
3027             }
3028         }
3029     } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
3030     p = xmalloc( 25 );
3031     sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
3032     return p;
3033 }
3034
3035 char*
3036 get_user_id( u32 *keyid, size_t *rn )
3037 {
3038   user_id_db_t r;
3039   char *p;
3040   int pass = 0;
3041
3042   /* Try it two times; second pass reads from key resources.  */
3043   do
3044     {
3045       for (r = user_id_db; r; r = r->next)
3046         {
3047           keyid_list_t a;
3048           for (a = r->keyids; a; a = a->next)
3049             {
3050               if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
3051                 {
3052                   /* An empty string as user id is possible.  Make
3053                      sure that the malloc allocates one byte and does
3054                      not bail out.  */
3055                   p = xmalloc (r->len? r->len : 1);
3056                   memcpy (p, r->name, r->len);
3057                   *rn = r->len;
3058                   return p;
3059                 }
3060             }
3061         }
3062     }
3063   while (++pass < 2 && !get_pubkey (NULL, keyid));
3064   p = xstrdup (user_id_not_found_utf8 ());
3065   *rn = strlen (p);
3066   return p;
3067 }
3068
3069 char*
3070 get_user_id_native( u32 *keyid )
3071 {
3072   size_t rn;
3073   char *p = get_user_id( keyid, &rn );
3074   char *p2 = utf8_to_native( p, rn, 0 );
3075   xfree(p);
3076   return p2;
3077 }
3078
3079 KEYDB_HANDLE
3080 get_ctx_handle(GETKEY_CTX ctx)
3081 {
3082   return ctx->kr_handle;
3083 }
3084
3085 static void
3086 free_akl(struct akl *akl)
3087 {
3088   if(akl->spec)
3089     free_keyserver_spec(akl->spec);
3090
3091   xfree(akl);
3092 }
3093
3094 void
3095 release_akl(void)
3096 {
3097   while(opt.auto_key_locate)
3098     {
3099       struct akl *akl2=opt.auto_key_locate;
3100       opt.auto_key_locate=opt.auto_key_locate->next;
3101       free_akl(akl2);
3102     }
3103 }
3104
3105 /* Returns false on error. */
3106 int
3107 parse_auto_key_locate(char *options)
3108 {
3109   char *tok;
3110
3111   while((tok=optsep(&options)))
3112     {
3113       struct akl *akl,*check,*last=NULL;
3114       int dupe=0;
3115
3116       if(tok[0]=='\0')
3117         continue;
3118
3119       akl=xmalloc_clear(sizeof(*akl));
3120
3121       if(ascii_strcasecmp(tok,"nodefault")==0)
3122         akl->type=AKL_NODEFAULT;
3123       else if(ascii_strcasecmp(tok,"local")==0)
3124         akl->type=AKL_LOCAL;
3125       else if(ascii_strcasecmp(tok,"ldap")==0)
3126         akl->type=AKL_LDAP;
3127       else if(ascii_strcasecmp(tok,"keyserver")==0)
3128         akl->type=AKL_KEYSERVER;
3129 #ifdef USE_DNS_CERT
3130       else if(ascii_strcasecmp(tok,"cert")==0)
3131         akl->type=AKL_CERT;
3132 #endif
3133 #ifdef USE_DNS_PKA
3134       else if(ascii_strcasecmp(tok,"pka")==0)
3135         akl->type=AKL_PKA;
3136 #endif
3137       else if((akl->spec=parse_keyserver_uri(tok,1,NULL,0)))
3138         akl->type=AKL_SPEC;
3139       else
3140         {
3141           free_akl(akl);
3142           return 0;
3143         }
3144
3145       /* We must maintain the order the user gave us */
3146       for(check=opt.auto_key_locate;check;last=check,check=check->next)
3147         {
3148           /* Check for duplicates */
3149           if(check->type==akl->type
3150              && (akl->type!=AKL_SPEC
3151                  || (akl->type==AKL_SPEC
3152                      && strcmp(check->spec->uri,akl->spec->uri)==0)))
3153             {
3154               dupe=1;
3155               free_akl(akl);
3156               break;
3157             }
3158         }
3159
3160       if(!dupe)
3161         {
3162           if(last)
3163             last->next=akl;
3164           else
3165             opt.auto_key_locate=akl;
3166         }
3167     }
3168
3169   return 1;
3170 }