2006-05-19 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / getkey.c
blobbff2a0ddc277b6cd4831289529b2c23848e890a0
1 /* getkey.c - Get a key from the database
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
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.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 #include <ctype.h>
30 #include "gpg.h"
31 #include "util.h"
32 #include "packet.h"
33 #include "iobuf.h"
34 #include "keydb.h"
35 #include "options.h"
36 #include "main.h"
37 #include "trustdb.h"
38 #include "i18n.h"
39 #include "keyserver-internal.h"
41 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
42 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
44 #if MAX_PK_CACHE_ENTRIES < 2
45 #error We need the cache for key creation
46 #endif
48 struct getkey_ctx_s {
49 int exact;
50 KBNODE keyblock;
51 KBPOS kbpos;
52 KBNODE found_key; /* pointer into some keyblock */
53 int last_rc;
54 int req_usage;
55 int req_algo;
56 KEYDB_HANDLE kr_handle;
57 int not_allocated;
58 int nitems;
59 KEYDB_SEARCH_DESC items[1];
62 #if 0
63 static struct {
64 int any;
65 int okay_count;
66 int nokey_count;
67 int error_count;
68 } lkup_stats[21];
69 #endif
71 typedef struct keyid_list {
72 struct keyid_list *next;
73 u32 keyid[2];
74 } *keyid_list_t;
77 #if MAX_PK_CACHE_ENTRIES
78 typedef struct pk_cache_entry {
79 struct pk_cache_entry *next;
80 u32 keyid[2];
81 PKT_public_key *pk;
82 } *pk_cache_entry_t;
83 static pk_cache_entry_t pk_cache;
84 static int pk_cache_entries; /* number of entries in pk cache */
85 static int pk_cache_disabled;
86 #endif
88 #if MAX_UID_CACHE_ENTRIES < 5
89 #error we really need the userid cache
90 #endif
91 typedef struct user_id_db {
92 struct user_id_db *next;
93 keyid_list_t keyids;
94 int len;
95 char name[1];
96 } *user_id_db_t;
97 static user_id_db_t user_id_db;
98 static int uid_cache_entries; /* number of entries in uid cache */
100 static void merge_selfsigs( KBNODE keyblock );
101 static int lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode );
103 #if 0
104 static void
105 print_stats()
107 int i;
108 for(i=0; i < DIM(lkup_stats); i++ ) {
109 if( lkup_stats[i].any )
110 fprintf(stderr,
111 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
113 lkup_stats[i].okay_count,
114 lkup_stats[i].nokey_count,
115 lkup_stats[i].error_count );
118 #endif
121 void
122 cache_public_key( PKT_public_key *pk )
124 #if MAX_PK_CACHE_ENTRIES
125 pk_cache_entry_t ce;
126 u32 keyid[2];
128 if( pk_cache_disabled )
129 return;
131 if( pk->dont_cache )
132 return;
134 if( is_ELGAMAL(pk->pubkey_algo)
135 || pk->pubkey_algo == PUBKEY_ALGO_DSA
136 || is_RSA(pk->pubkey_algo) ) {
137 keyid_from_pk( pk, keyid );
139 else
140 return; /* don't know how to get the keyid */
142 for( ce = pk_cache; ce; ce = ce->next )
143 if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] ) {
144 if( DBG_CACHE )
145 log_debug("cache_public_key: already in cache\n");
146 return;
149 if( pk_cache_entries >= MAX_PK_CACHE_ENTRIES ) {
150 /* fixme: use another algorithm to free some cache slots */
151 pk_cache_disabled=1;
152 if( opt.verbose > 1 )
153 log_info(_("too many entries in pk cache - disabled\n"));
154 return;
156 pk_cache_entries++;
157 ce = xmalloc( sizeof *ce );
158 ce->next = pk_cache;
159 pk_cache = ce;
160 ce->pk = copy_public_key( NULL, pk );
161 ce->keyid[0] = keyid[0];
162 ce->keyid[1] = keyid[1];
163 #endif
167 /* Return a const utf-8 string with the text "[User ID not found]".
168 This fucntion is required so that we don't need to switch gettext's
169 encoding temporary. */
170 static const char *
171 user_id_not_found_utf8 (void)
173 static char *text;
175 if (!text)
176 text = native_to_utf8 (_("[User ID not found]"));
177 return text;
183 * Return the user ID from the given keyblock.
184 * We use the primary uid flag which has been set by the merge_selfsigs
185 * function. The returned value is only valid as long as then given
186 * keyblock is not changed
188 static const char *
189 get_primary_uid ( KBNODE keyblock, size_t *uidlen )
191 KBNODE k;
192 const char *s;
194 for (k=keyblock; k; k=k->next ) {
195 if ( k->pkt->pkttype == PKT_USER_ID
196 && !k->pkt->pkt.user_id->attrib_data
197 && k->pkt->pkt.user_id->is_primary ) {
198 *uidlen = k->pkt->pkt.user_id->len;
199 return k->pkt->pkt.user_id->name;
202 s = user_id_not_found_utf8 ();
203 *uidlen = strlen (s);
204 return s;
208 static void
209 release_keyid_list ( keyid_list_t k )
211 while ( k ) {
212 keyid_list_t k2 = k->next;
213 xfree (k);
214 k = k2;
218 /****************
219 * Store the association of keyid and userid
220 * Feed only public keys to this function.
222 static void
223 cache_user_id( KBNODE keyblock )
225 user_id_db_t r;
226 const char *uid;
227 size_t uidlen;
228 keyid_list_t keyids = NULL;
229 KBNODE k;
231 for (k=keyblock; k; k = k->next ) {
232 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
233 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
234 keyid_list_t a = xmalloc_clear ( sizeof *a );
235 /* Hmmm: For a long list of keyids it might be an advantage
236 * to append the keys */
237 keyid_from_pk( k->pkt->pkt.public_key, a->keyid );
238 /* first check for duplicates */
239 for(r=user_id_db; r; r = r->next ) {
240 keyid_list_t b = r->keyids;
241 for ( b = r->keyids; b; b = b->next ) {
242 if( b->keyid[0] == a->keyid[0]
243 && b->keyid[1] == a->keyid[1] ) {
244 if( DBG_CACHE )
245 log_debug("cache_user_id: already in cache\n");
246 release_keyid_list ( keyids );
247 xfree ( a );
248 return;
252 /* now put it into the cache */
253 a->next = keyids;
254 keyids = a;
257 if ( !keyids )
258 BUG (); /* No key no fun */
261 uid = get_primary_uid ( keyblock, &uidlen );
263 if( uid_cache_entries >= MAX_UID_CACHE_ENTRIES ) {
264 /* fixme: use another algorithm to free some cache slots */
265 r = user_id_db;
266 user_id_db = r->next;
267 release_keyid_list ( r->keyids );
268 xfree(r);
269 uid_cache_entries--;
271 r = xmalloc( sizeof *r + uidlen-1 );
272 r->keyids = keyids;
273 r->len = uidlen;
274 memcpy(r->name, uid, r->len);
275 r->next = user_id_db;
276 user_id_db = r;
277 uid_cache_entries++;
281 void
282 getkey_disable_caches()
284 #if MAX_PK_CACHE_ENTRIES
286 pk_cache_entry_t ce, ce2;
288 for( ce = pk_cache; ce; ce = ce2 ) {
289 ce2 = ce->next;
290 free_public_key( ce->pk );
291 xfree( ce );
293 pk_cache_disabled=1;
294 pk_cache_entries = 0;
295 pk_cache = NULL;
297 #endif
298 /* fixme: disable user id cache ? */
302 static void
303 pk_from_block ( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE keyblock )
305 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
307 assert ( a->pkt->pkttype == PKT_PUBLIC_KEY
308 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY );
310 copy_public_key ( pk, a->pkt->pkt.public_key );
313 static void
314 sk_from_block ( GETKEY_CTX ctx,
315 PKT_secret_key *sk, KBNODE keyblock )
317 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
319 assert ( a->pkt->pkttype == PKT_SECRET_KEY
320 || a->pkt->pkttype == PKT_SECRET_SUBKEY );
322 copy_secret_key( sk, a->pkt->pkt.secret_key);
326 /****************
327 * Get a public key and store it into the allocated pk
328 * can be called with PK set to NULL to just read it into some
329 * internal structures.
332 get_pubkey( PKT_public_key *pk, u32 *keyid )
334 int internal = 0;
335 int rc = 0;
337 #if MAX_PK_CACHE_ENTRIES
338 if(pk)
340 /* Try to get it from the cache. We don't do this when pk is
341 NULL as it does not guarantee that the user IDs are
342 cached. */
343 pk_cache_entry_t ce;
344 for( ce = pk_cache; ce; ce = ce->next )
346 if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] )
348 copy_public_key( pk, ce->pk );
349 return 0;
353 #endif
354 /* more init stuff */
355 if( !pk ) {
356 pk = xmalloc_clear( sizeof *pk );
357 internal++;
361 /* do a lookup */
362 { struct getkey_ctx_s ctx;
363 KBNODE kb = NULL;
364 memset( &ctx, 0, sizeof ctx );
365 ctx.exact = 1; /* use the key ID exactly as given */
366 ctx.not_allocated = 1;
367 ctx.kr_handle = keydb_new (0);
368 ctx.nitems = 1;
369 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
370 ctx.items[0].u.kid[0] = keyid[0];
371 ctx.items[0].u.kid[1] = keyid[1];
372 ctx.req_algo = pk->req_algo;
373 ctx.req_usage = pk->req_usage;
374 rc = lookup( &ctx, &kb, 0 );
375 if ( !rc ) {
376 pk_from_block ( &ctx, pk, kb );
378 get_pubkey_end( &ctx );
379 release_kbnode ( kb );
381 if( !rc )
382 goto leave;
384 rc = G10ERR_NO_PUBKEY;
386 leave:
387 if( !rc )
388 cache_public_key( pk );
389 if( internal )
390 free_public_key(pk);
391 return rc;
395 /* Get a public key and store it into the allocated pk. This function
396 differs from get_pubkey() in that it does not do a check of the key
397 to avoid recursion. It should be used only in very certain cases.
398 It will only retrieve primary keys. */
400 get_pubkey_fast (PKT_public_key *pk, u32 *keyid)
402 int rc = 0;
403 KEYDB_HANDLE hd;
404 KBNODE keyblock;
405 u32 pkid[2];
407 assert (pk);
408 #if MAX_PK_CACHE_ENTRIES
409 { /* Try to get it from the cache */
410 pk_cache_entry_t ce;
412 for (ce = pk_cache; ce; ce = ce->next)
414 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
416 if (pk)
417 copy_public_key (pk, ce->pk);
418 return 0;
422 #endif
424 hd = keydb_new (0);
425 rc = keydb_search_kid (hd, keyid);
426 if (rc == -1)
428 keydb_release (hd);
429 return G10ERR_NO_PUBKEY;
431 rc = keydb_get_keyblock (hd, &keyblock);
432 keydb_release (hd);
433 if (rc)
435 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
436 return G10ERR_NO_PUBKEY;
439 assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
440 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
442 keyid_from_pk(keyblock->pkt->pkt.public_key,pkid);
443 if(keyid[0]==pkid[0] && keyid[1]==pkid[1])
444 copy_public_key (pk, keyblock->pkt->pkt.public_key );
445 else
446 rc=G10ERR_NO_PUBKEY;
448 release_kbnode (keyblock);
450 /* Not caching key here since it won't have all of the fields
451 properly set. */
453 return rc;
457 KBNODE
458 get_pubkeyblock( u32 *keyid )
460 struct getkey_ctx_s ctx;
461 int rc = 0;
462 KBNODE keyblock = NULL;
464 memset( &ctx, 0, sizeof ctx );
465 /* no need to set exact here because we want the entire block */
466 ctx.not_allocated = 1;
467 ctx.kr_handle = keydb_new (0);
468 ctx.nitems = 1;
469 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
470 ctx.items[0].u.kid[0] = keyid[0];
471 ctx.items[0].u.kid[1] = keyid[1];
472 rc = lookup( &ctx, &keyblock, 0 );
473 get_pubkey_end( &ctx );
475 return rc ? NULL : keyblock;
481 /****************
482 * Get a secret key and store it into sk
485 get_seckey( PKT_secret_key *sk, u32 *keyid )
487 int rc;
488 struct getkey_ctx_s ctx;
489 KBNODE kb = NULL;
491 memset( &ctx, 0, sizeof ctx );
492 ctx.exact = 1; /* use the key ID exactly as given */
493 ctx.not_allocated = 1;
494 ctx.kr_handle = keydb_new (1);
495 ctx.nitems = 1;
496 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
497 ctx.items[0].u.kid[0] = keyid[0];
498 ctx.items[0].u.kid[1] = keyid[1];
499 ctx.req_algo = sk->req_algo;
500 ctx.req_usage = sk->req_usage;
501 rc = lookup( &ctx, &kb, 1 );
502 if ( !rc ) {
503 sk_from_block ( &ctx, sk, kb );
505 get_seckey_end( &ctx );
506 release_kbnode ( kb );
508 if( !rc ) {
509 /* check the secret key (this may prompt for a passprase to
510 * unlock the secret key
512 rc = check_secret_key( sk, 0 );
515 return rc;
519 /****************
520 * Check whether the secret key is available. This is just a fast
521 * check and does not tell us whether the secret key is valid. It
522 * merely tells other whether there is some secret key.
523 * Returns: 0 := key is available
524 * G10ERR_NO_SECKEY := not availabe
527 seckey_available( u32 *keyid )
529 int rc;
530 KEYDB_HANDLE hd = keydb_new (1);
532 rc = keydb_search_kid (hd, keyid);
533 if ( rc == -1 )
534 rc = G10ERR_NO_SECKEY;
535 keydb_release (hd);
536 return rc;
540 /****************
541 * Return the type of the user id:
543 * Please use the constants KEYDB_SERCH_MODE_xxx
544 * 0 = Invalid user ID
545 * 1 = exact match
546 * 2 = match a substring
547 * 3 = match an email address
548 * 4 = match a substring of an email address
549 * 5 = match an email address, but compare from end
550 * 6 = word match mode
551 * 10 = it is a short KEYID (don't care about keyid[0])
552 * 11 = it is a long KEYID
553 * 12 = it is a trustdb index (keyid is looked up)
554 * 16 = it is a 16 byte fingerprint
555 * 20 = it is a 20 byte fingerprint
556 * 21 = Unified fingerprint :fpr:pk_algo:
557 * (We don't use pk_algo yet)
559 * Rules used:
560 * - If the username starts with 8,9,16 or 17 hex-digits (the first one
561 * must be in the range 0..9), this is considered a keyid; depending
562 * on the length a short or complete one.
563 * - If the username starts with 32,33,40 or 41 hex-digits (the first one
564 * must be in the range 0..9), this is considered a fingerprint.
565 * - If the username starts with a left angle, we assume it is a complete
566 * email address and look only at this part.
567 * - If the username starts with a colon we assume it is a unified
568 * key specfification.
569 * - If the username starts with a '.', we assume it is the ending
570 * part of an email address
571 * - If the username starts with an '@', we assume it is a part of an
572 * email address
573 * - If the userid start with an '=' an exact compare is done.
574 * - If the userid starts with a '*' a case insensitive substring search is
575 * done (This is the default).
576 * - If the userid starts with a '+' we will compare individual words
577 * and a match requires that all the words are in the userid.
578 * Words are delimited by white space or "()<>[]{}.@-+_,;/&!"
579 * (note that you can't search for these characters). Compare
580 * is not case sensitive.
584 classify_user_id( const char *name, KEYDB_SEARCH_DESC *desc )
586 const char *s;
587 int hexprefix = 0;
588 int hexlength;
589 int mode = 0;
590 KEYDB_SEARCH_DESC dummy_desc;
592 if (!desc)
593 desc = &dummy_desc;
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);
599 /* skip leading spaces. Fixme: what is with trailing spaces? */
600 for(s = name; *s && spacep (s); s++ )
603 switch (*s) {
604 case 0: /* empty string is an error */
605 return 0;
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
615 case '<': /* an email address */
616 mode = KEYDB_SEARCH_MODE_MAIL;
617 desc->u.name = s;
618 break;
620 case '@': /* part of an email address */
621 mode = KEYDB_SEARCH_MODE_MAILSUB;
622 s++;
623 desc->u.name = s;
624 break;
626 case '=': /* exact compare */
627 mode = KEYDB_SEARCH_MODE_EXACT;
628 s++;
629 desc->u.name = s;
630 break;
632 case '*': /* case insensitive substring search */
633 mode = KEYDB_SEARCH_MODE_SUBSTR;
634 s++;
635 desc->u.name = s;
636 break;
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
646 case '#': /* local user id */
647 return 0; /* This is now obsolete and van't not be used anymore*/
649 case ':': /*Unified fingerprint */
651 const char *se, *si;
652 int i;
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 */
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;
670 break;
672 default:
673 if (s[0] == '0' && s[1] == 'x') {
674 hexprefix = 1;
675 s += 2;
678 hexlength = strspn(s, "0123456789abcdefABCDEF");
679 if (hexlength >= 8 && s[hexlength] =='!') {
680 desc->exact = 1;
681 hexlength++; /* just for the following check */
684 /* check if a hexadecimal number is terminated by EOS or blank */
685 if (hexlength && s[hexlength] && !spacep(s+hexlength)) {
686 if (hexprefix) /* a "0x" prefix without correct */
687 return 0; /* termination is an error */
688 else /* The first chars looked like */
689 hexlength = 0; /* a hex number, but really were not. */
692 if (desc->exact)
693 hexlength--;
695 if (hexlength == 8
696 || (!hexprefix && hexlength == 9 && *s == '0')){
697 /* short keyid */
698 if (hexlength == 9)
699 s++;
700 desc->u.kid[0] = 0;
701 desc->u.kid[1] = strtoul( s, NULL, 16 );
702 mode = KEYDB_SEARCH_MODE_SHORT_KID;
704 else if (hexlength == 16
705 || (!hexprefix && hexlength == 17 && *s == '0')) {
706 /* complete keyid */
707 char buf[9];
708 if (hexlength == 17)
709 s++;
710 mem2str(buf, s, 9 );
711 desc->u.kid[0] = strtoul( buf, NULL, 16 );
712 desc->u.kid[1] = strtoul( s+8, NULL, 16 );
713 mode = KEYDB_SEARCH_MODE_LONG_KID;
715 else if (hexlength == 32 || (!hexprefix && hexlength == 33
716 && *s == '0')) {
717 /* md5 fingerprint */
718 int i;
719 if (hexlength == 33)
720 s++;
721 memset(desc->u.fpr+16, 0, 4);
722 for (i=0; i < 16; i++, s+=2) {
723 int c = hextobyte(s);
724 if (c == -1)
725 return 0;
726 desc->u.fpr[i] = c;
728 mode = KEYDB_SEARCH_MODE_FPR16;
730 else if (hexlength == 40 || (!hexprefix && hexlength == 41
731 && *s == '0')) {
732 /* sha1/rmd160 fingerprint */
733 int i;
734 if (hexlength == 41)
735 s++;
736 for (i=0; i < 20; i++, s+=2) {
737 int c = hextobyte(s);
738 if (c == -1)
739 return 0;
740 desc->u.fpr[i] = c;
742 mode = KEYDB_SEARCH_MODE_FPR20;
744 else {
745 if (hexprefix) /* This was a hex number with a prefix */
746 return 0; /* and a wrong length */
748 desc->exact = 0;
749 desc->u.name = s;
750 mode = KEYDB_SEARCH_MODE_SUBSTR; /* default mode */
754 desc->mode = mode;
755 return mode;
759 static int
760 skip_unusable(void *dummy,u32 *keyid,PKT_user_id *uid)
762 int unusable=0;
763 KBNODE keyblock;
765 keyblock=get_pubkeyblock(keyid);
766 if(!keyblock)
768 log_error("error checking usability status of %s\n",keystr(keyid));
769 goto leave;
772 /* Is the user ID in question revoked/expired? */
773 if(uid)
775 KBNODE node;
777 for(node=keyblock;node;node=node->next)
779 if(node->pkt->pkttype==PKT_USER_ID)
781 if(cmp_user_ids(uid,node->pkt->pkt.user_id)==0
782 && (node->pkt->pkt.user_id->is_revoked
783 || node->pkt->pkt.user_id->is_expired))
785 unusable=1;
786 break;
792 if(!unusable)
793 unusable=pk_is_disabled(keyblock->pkt->pkt.public_key);
795 leave:
796 release_kbnode(keyblock);
797 return unusable;
800 /****************
801 * Try to get the pubkey by the userid. This function looks for the
802 * first pubkey certificate which has the given name in a user_id. if
803 * pk/sk has the pubkey algo set, the function will only return a
804 * pubkey with that algo. If namelist is NULL, the first key is
805 * returned. The caller should provide storage for either the pk or
806 * the sk. If ret_kb is not NULL the function will return the
807 * keyblock there.
810 static int
811 key_byname( GETKEY_CTX *retctx, STRLIST namelist,
812 PKT_public_key *pk, PKT_secret_key *sk,
813 int secmode, int include_unusable,
814 KBNODE *ret_kb, KEYDB_HANDLE *ret_kdbhd )
816 int rc = 0;
817 int n;
818 STRLIST r;
819 GETKEY_CTX ctx;
820 KBNODE help_kb = NULL;
822 if( retctx ) {/* reset the returned context in case of error */
823 assert (!ret_kdbhd); /* not allowed because the handle is
824 stored in the context */
825 *retctx = NULL;
827 if (ret_kdbhd)
828 *ret_kdbhd = NULL;
830 if(!namelist)
832 ctx = xmalloc_clear (sizeof *ctx);
833 ctx->nitems = 1;
834 ctx->items[0].mode=KEYDB_SEARCH_MODE_FIRST;
835 if(!include_unusable)
836 ctx->items[0].skipfnc=skip_unusable;
838 else
840 /* build the search context */
841 for(n=0, r=namelist; r; r = r->next )
842 n++;
844 ctx = xmalloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
845 ctx->nitems = n;
847 for(n=0, r=namelist; r; r = r->next, n++ )
849 classify_user_id (r->d, &ctx->items[n]);
851 if (ctx->items[n].exact)
852 ctx->exact = 1;
853 if (!ctx->items[n].mode)
855 xfree (ctx);
856 return G10ERR_INV_USER_ID;
858 if(!include_unusable
859 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_SHORT_KID
860 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_LONG_KID
861 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR16
862 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR20
863 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR)
864 ctx->items[n].skipfnc=skip_unusable;
868 ctx->kr_handle = keydb_new (secmode);
869 if ( !ret_kb )
870 ret_kb = &help_kb;
872 if( secmode ) {
873 if (sk) {
874 ctx->req_algo = sk->req_algo;
875 ctx->req_usage = sk->req_usage;
877 rc = lookup( ctx, ret_kb, 1 );
878 if ( !rc && sk ) {
879 sk_from_block ( ctx, sk, *ret_kb );
882 else {
883 if (pk) {
884 ctx->req_algo = pk->req_algo;
885 ctx->req_usage = pk->req_usage;
887 rc = lookup( ctx, ret_kb, 0 );
888 if ( !rc && pk ) {
889 pk_from_block ( ctx, pk, *ret_kb );
893 release_kbnode ( help_kb );
895 if (retctx) /* caller wants the context */
896 *retctx = ctx;
897 else {
898 if (ret_kdbhd) {
899 *ret_kdbhd = ctx->kr_handle;
900 ctx->kr_handle = NULL;
902 get_pubkey_end (ctx);
905 return rc;
910 /* Find a public key from NAME and return the keyblock or the key. If
911 ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
912 is returned and the caller is responsible for closing it. If a key
913 was not found and NAME is a valid RFC822 mailbox and PKA retrieval
914 has been enabled, we try to import the pkea via the PKA
915 mechanism. */
917 get_pubkey_byname (PKT_public_key *pk,
918 const char *name, KBNODE *ret_keyblock,
919 KEYDB_HANDLE *ret_kdbhd, int include_unusable )
921 int rc;
922 STRLIST namelist = NULL;
924 add_to_strlist( &namelist, name );
926 rc = key_byname( NULL, namelist, pk, NULL, 0,
927 include_unusable, ret_keyblock, ret_kdbhd);
929 /* If the requested name resembles a valid mailbox and automatic
930 retrieval has been enabled, we try to import the key. */
932 if (rc == G10ERR_NO_PUBKEY && is_valid_mailbox(name))
934 struct akl *akl;
936 for(akl=opt.auto_key_locate;akl;akl=akl->next)
938 unsigned char *fpr;
939 size_t fpr_len;
941 switch(akl->type)
943 case AKL_CERT:
944 glo_ctrl.in_auto_key_retrieve++;
945 rc=keyserver_import_cert(name,&fpr,&fpr_len);
946 glo_ctrl.in_auto_key_retrieve--;
948 if(rc==0)
949 log_info(_("automatically retrieved `%s' via %s\n"),
950 name,"DNS CERT");
951 break;
953 case AKL_PKA:
954 glo_ctrl.in_auto_key_retrieve++;
955 rc=keyserver_import_pka(name,&fpr,&fpr_len);
956 glo_ctrl.in_auto_key_retrieve--;
958 if(rc==0)
959 log_info(_("automatically retrieved `%s' via %s\n"),
960 name,"PKA");
961 break;
963 case AKL_LDAP:
964 glo_ctrl.in_auto_key_retrieve++;
965 rc=keyserver_import_ldap(name,&fpr,&fpr_len);
966 glo_ctrl.in_auto_key_retrieve--;
968 if(rc==0)
969 log_info(_("automatically retrieved `%s' via %s\n"),
970 name,"LDAP");
971 break;
973 case AKL_KEYSERVER:
974 /* Strictly speaking, we don't need to only use a valid
975 mailbox for the getname search, but it helps cut down
976 on the problem of searching for something like "john"
977 and getting a whole lot of keys back. */
978 if(opt.keyserver)
980 glo_ctrl.in_auto_key_retrieve++;
981 rc=keyserver_import_name(name,&fpr,&fpr_len,opt.keyserver);
982 glo_ctrl.in_auto_key_retrieve--;
984 if(rc==0)
985 log_info(_("automatically retrieved `%s' via %s\n"),
986 name,opt.keyserver->uri);
988 break;
990 case AKL_SPEC:
992 struct keyserver_spec *keyserver;
994 keyserver=keyserver_match(akl->spec);
995 glo_ctrl.in_auto_key_retrieve++;
996 rc=keyserver_import_name(name,&fpr,&fpr_len,keyserver);
997 glo_ctrl.in_auto_key_retrieve--;
999 if(rc==0)
1000 log_info(_("automatically retrieved `%s' via %s\n"),
1001 name,akl->spec->uri);
1003 break;
1006 /* Use the fingerprint of the key that we actually fetched.
1007 This helps prevent problems where the key that we fetched
1008 doesn't have the same name that we used to fetch it. In
1009 the case of CERT and PKA, this is an actual security
1010 requirement as the URL might point to a key put in by an
1011 attacker. By forcing the use of the fingerprint, we
1012 won't use the attacker's key here. */
1013 if(rc==0 && fpr)
1015 int i;
1016 char fpr_string[MAX_FINGERPRINT_LEN*2+1];
1018 assert(fpr_len<=MAX_FINGERPRINT_LEN);
1020 free_strlist(namelist);
1021 namelist=NULL;
1023 for(i=0;i<fpr_len;i++)
1024 sprintf(fpr_string+2*i,"%02X",fpr[i]);
1026 if(opt.verbose)
1027 log_info("auto-key-locate found fingerprint %s\n",fpr_string);
1029 add_to_strlist( &namelist, fpr_string );
1031 xfree(fpr);
1034 rc = key_byname( NULL, namelist, pk, NULL, 0,
1035 include_unusable, ret_keyblock, ret_kdbhd);
1036 if(rc!=G10ERR_NO_PUBKEY)
1037 break;
1041 free_strlist( namelist );
1042 return rc;
1046 get_pubkey_bynames( GETKEY_CTX *retctx, PKT_public_key *pk,
1047 STRLIST names, KBNODE *ret_keyblock )
1049 return key_byname( retctx, names, pk, NULL, 0, 1, ret_keyblock, NULL);
1053 get_pubkey_next( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE *ret_keyblock )
1055 int rc;
1057 rc = lookup( ctx, ret_keyblock, 0 );
1058 if ( !rc && pk && ret_keyblock )
1059 pk_from_block ( ctx, pk, *ret_keyblock );
1061 return rc;
1064 void
1065 get_pubkey_end( GETKEY_CTX ctx )
1067 if( ctx ) {
1068 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1069 keydb_release (ctx->kr_handle);
1070 if( !ctx->not_allocated )
1071 xfree( ctx );
1076 /****************
1077 * Search for a key with the given fingerprint.
1078 * FIXME:
1079 * We should replace this with the _byname function. Thiscsan be done
1080 * by creating a userID conforming to the unified fingerprint style.
1083 get_pubkey_byfprint( PKT_public_key *pk,
1084 const byte *fprint, size_t fprint_len)
1086 int rc;
1088 if( fprint_len == 20 || fprint_len == 16 ) {
1089 struct getkey_ctx_s ctx;
1090 KBNODE kb = NULL;
1092 memset( &ctx, 0, sizeof ctx );
1093 ctx.exact = 1 ;
1094 ctx.not_allocated = 1;
1095 ctx.kr_handle = keydb_new (0);
1096 ctx.nitems = 1;
1097 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1098 : KEYDB_SEARCH_MODE_FPR20;
1099 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1100 rc = lookup( &ctx, &kb, 0 );
1101 if (!rc && pk )
1102 pk_from_block ( &ctx, pk, kb );
1103 release_kbnode ( kb );
1104 get_pubkey_end( &ctx );
1106 else
1107 rc = G10ERR_GENERAL; /* Oops */
1108 return rc;
1112 /* Get a public key and store it into the allocated pk. This function
1113 differs from get_pubkey_byfprint() in that it does not do a check
1114 of the key to avoid recursion. It should be used only in very
1115 certain cases. PK may be NULL to check just for the existance of
1116 the key. */
1118 get_pubkey_byfprint_fast (PKT_public_key *pk,
1119 const byte *fprint, size_t fprint_len)
1121 int rc = 0;
1122 KEYDB_HANDLE hd;
1123 KBNODE keyblock;
1124 byte fprbuf[MAX_FINGERPRINT_LEN];
1125 int i;
1127 for (i=0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1128 fprbuf[i] = fprint[i];
1129 while (i < MAX_FINGERPRINT_LEN)
1130 fprbuf[i++] = 0;
1132 hd = keydb_new (0);
1133 rc = keydb_search_fpr (hd, fprbuf);
1134 if (rc == -1)
1136 keydb_release (hd);
1137 return G10ERR_NO_PUBKEY;
1139 rc = keydb_get_keyblock (hd, &keyblock);
1140 keydb_release (hd);
1141 if (rc)
1143 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
1144 return G10ERR_NO_PUBKEY;
1147 assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1148 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
1149 if (pk)
1150 copy_public_key (pk, keyblock->pkt->pkt.public_key );
1151 release_kbnode (keyblock);
1153 /* Not caching key here since it won't have all of the fields
1154 properly set. */
1156 return 0;
1159 /****************
1160 * Search for a key with the given fingerprint and return the
1161 * complete keyblock which may have more than only this key.
1164 get_keyblock_byfprint( KBNODE *ret_keyblock, const byte *fprint,
1165 size_t fprint_len )
1167 int rc;
1169 if( fprint_len == 20 || fprint_len == 16 ) {
1170 struct getkey_ctx_s ctx;
1172 memset( &ctx, 0, sizeof ctx );
1173 ctx.not_allocated = 1;
1174 ctx.kr_handle = keydb_new (0);
1175 ctx.nitems = 1;
1176 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1177 : KEYDB_SEARCH_MODE_FPR20;
1178 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1179 rc = lookup( &ctx, ret_keyblock, 0 );
1180 get_pubkey_end( &ctx );
1182 else
1183 rc = G10ERR_GENERAL; /* Oops */
1185 return rc;
1189 /****************
1190 * Get a secret key by name and store it into sk
1191 * If NAME is NULL use the default key
1193 static int
1194 get_seckey_byname2( GETKEY_CTX *retctx,
1195 PKT_secret_key *sk, const char *name, int unprotect,
1196 KBNODE *retblock )
1198 STRLIST namelist = NULL;
1199 int rc,include_unusable=1;
1201 /* If we have no name, try to use the default secret key. If we
1202 have no default, we'll use the first usable one. */
1204 if( !name && opt.def_secret_key && *opt.def_secret_key )
1205 add_to_strlist( &namelist, opt.def_secret_key );
1206 else if(name)
1207 add_to_strlist( &namelist, name );
1208 else
1209 include_unusable=0;
1211 rc = key_byname( retctx, namelist, NULL, sk, 1, include_unusable,
1212 retblock, NULL );
1214 free_strlist( namelist );
1216 if( !rc && unprotect )
1217 rc = check_secret_key( sk, 0 );
1219 return rc;
1222 int
1223 get_seckey_byname( PKT_secret_key *sk, const char *name, int unlock )
1225 return get_seckey_byname2 ( NULL, sk, name, unlock, NULL );
1230 get_seckey_bynames( GETKEY_CTX *retctx, PKT_secret_key *sk,
1231 STRLIST names, KBNODE *ret_keyblock )
1233 return key_byname( retctx, names, NULL, sk, 1, 1, ret_keyblock, NULL );
1238 get_seckey_next( GETKEY_CTX ctx, PKT_secret_key *sk, KBNODE *ret_keyblock )
1240 int rc;
1242 rc = lookup( ctx, ret_keyblock, 1 );
1243 if ( !rc && sk && ret_keyblock )
1244 sk_from_block ( ctx, sk, *ret_keyblock );
1246 return rc;
1250 void
1251 get_seckey_end( GETKEY_CTX ctx )
1253 get_pubkey_end( ctx );
1257 /****************
1258 * Search for a key with the given fingerprint.
1259 * FIXME:
1260 * We should replace this with the _byname function. Thiscsan be done
1261 * by creating a userID conforming to the unified fingerprint style.
1264 get_seckey_byfprint( PKT_secret_key *sk,
1265 const byte *fprint, size_t fprint_len)
1267 int rc;
1269 if( fprint_len == 20 || fprint_len == 16 ) {
1270 struct getkey_ctx_s ctx;
1271 KBNODE kb = NULL;
1273 memset( &ctx, 0, sizeof ctx );
1274 ctx.exact = 1 ;
1275 ctx.not_allocated = 1;
1276 ctx.kr_handle = keydb_new (1);
1277 ctx.nitems = 1;
1278 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1279 : KEYDB_SEARCH_MODE_FPR20;
1280 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1281 rc = lookup( &ctx, &kb, 1 );
1282 if (!rc && sk )
1283 sk_from_block ( &ctx, sk, kb );
1284 release_kbnode ( kb );
1285 get_seckey_end( &ctx );
1287 else
1288 rc = G10ERR_GENERAL; /* Oops */
1289 return rc;
1293 /* Search for a secret key with the given fingerprint and return the
1294 complete keyblock which may have more than only this key. */
1296 get_seckeyblock_byfprint (KBNODE *ret_keyblock, const byte *fprint,
1297 size_t fprint_len )
1299 int rc;
1300 struct getkey_ctx_s ctx;
1302 if (fprint_len != 20 && fprint_len == 16)
1303 return G10ERR_GENERAL; /* Oops */
1305 memset (&ctx, 0, sizeof ctx);
1306 ctx.not_allocated = 1;
1307 ctx.kr_handle = keydb_new (1);
1308 ctx.nitems = 1;
1309 ctx.items[0].mode = (fprint_len==16
1310 ? KEYDB_SEARCH_MODE_FPR16
1311 : KEYDB_SEARCH_MODE_FPR20);
1312 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1313 rc = lookup (&ctx, ret_keyblock, 1);
1314 get_seckey_end (&ctx);
1316 return rc;
1321 /************************************************
1322 ************* Merging stuff ********************
1323 ************************************************/
1325 /****************
1326 * merge all selfsignatures with the keys.
1327 * FIXME: replace this at least for the public key parts
1328 * by merge_selfsigs.
1329 * It is still used in keyedit.c and
1330 * at 2 or 3 other places - check whether it is really needed.
1331 * It might be needed by the key edit and import stuff because
1332 * the keylock is changed.
1334 void
1335 merge_keys_and_selfsig( KBNODE keyblock )
1337 PKT_public_key *pk = NULL;
1338 PKT_secret_key *sk = NULL;
1339 PKT_signature *sig;
1340 KBNODE k;
1341 u32 kid[2] = { 0, 0 };
1342 u32 sigdate = 0;
1344 if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
1345 /* divert to our new function */
1346 merge_selfsigs (keyblock);
1347 return;
1349 /* still need the old one because the new one can't handle secret keys */
1351 for(k=keyblock; k; k = k->next ) {
1352 if( k->pkt->pkttype == PKT_PUBLIC_KEY
1353 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1354 pk = k->pkt->pkt.public_key; sk = NULL;
1355 if( pk->version < 4 )
1356 pk = NULL; /* not needed for old keys */
1357 else if( k->pkt->pkttype == PKT_PUBLIC_KEY )
1358 keyid_from_pk( pk, kid );
1359 else if( !pk->expiredate ) { /* and subkey */
1360 /* insert the expiration date here */
1361 /*FIXME!!! pk->expiredate = subkeys_expiretime( k, kid );*/
1363 sigdate = 0;
1365 else if( k->pkt->pkttype == PKT_SECRET_KEY
1366 || k->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1367 pk = NULL; sk = k->pkt->pkt.secret_key;
1368 if( sk->version < 4 )
1369 sk = NULL;
1370 else if( k->pkt->pkttype == PKT_SECRET_KEY )
1371 keyid_from_sk( sk, kid );
1372 sigdate = 0;
1374 else if( (pk || sk ) && k->pkt->pkttype == PKT_SIGNATURE
1375 && (sig=k->pkt->pkt.signature)->sig_class >= 0x10
1376 && sig->sig_class <= 0x30 && sig->version > 3
1377 && !(sig->sig_class == 0x18 || sig->sig_class == 0x28)
1378 && sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1] ) {
1379 /* okay this is a self-signature which can be used.
1380 * This is not used for subkey binding signature, becuase this
1381 * is done above.
1382 * FIXME: We should only use this if the signature is valid
1383 * but this is time consuming - we must provide another
1384 * way to handle this
1386 const byte *p;
1387 u32 ed;
1389 p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
1390 if( pk ) {
1391 ed = p? pk->timestamp + buffer_to_u32(p):0;
1392 if( sig->timestamp > sigdate ) {
1393 pk->expiredate = ed;
1394 sigdate = sig->timestamp;
1397 else {
1398 ed = p? sk->timestamp + buffer_to_u32(p):0;
1399 if( sig->timestamp > sigdate ) {
1400 sk->expiredate = ed;
1401 sigdate = sig->timestamp;
1406 if(pk && (pk->expiredate==0 ||
1407 (pk->max_expiredate && pk->expiredate>pk->max_expiredate)))
1408 pk->expiredate=pk->max_expiredate;
1410 if(sk && (sk->expiredate==0 ||
1411 (sk->max_expiredate && sk->expiredate>sk->max_expiredate)))
1412 sk->expiredate=sk->max_expiredate;
1416 static int
1417 parse_key_usage(PKT_signature *sig)
1419 int key_usage=0;
1420 const byte *p;
1421 size_t n;
1422 byte flags;
1424 p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_KEY_FLAGS,&n);
1425 if(p && n)
1427 /* first octet of the keyflags */
1428 flags=*p;
1430 if(flags & 1)
1432 key_usage |= PUBKEY_USAGE_CERT;
1433 flags&=~1;
1436 if(flags & 2)
1438 key_usage |= PUBKEY_USAGE_SIG;
1439 flags&=~2;
1442 /* We do not distinguish between encrypting communications and
1443 encrypting storage. */
1444 if(flags & (0x04|0x08))
1446 key_usage |= PUBKEY_USAGE_ENC;
1447 flags&=~(0x04|0x08);
1450 if(flags & 0x20)
1452 key_usage |= PUBKEY_USAGE_AUTH;
1453 flags&=~0x20;
1456 if(flags)
1457 key_usage |= PUBKEY_USAGE_UNKNOWN;
1460 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1461 capability that we do not handle. This serves to distinguish
1462 between a zero key usage which we handle as the default
1463 capabilities for that algorithm, and a usage that we do not
1464 handle. */
1466 return key_usage;
1470 * Apply information from SIGNODE (which is the valid self-signature
1471 * associated with that UID) to the UIDNODE:
1472 * - wether the UID has been revoked
1473 * - assumed creation date of the UID
1474 * - temporary store the keyflags here
1475 * - temporary store the key expiration time here
1476 * - mark whether the primary user ID flag hat been set.
1477 * - store the preferences
1479 static void
1480 fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
1482 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1483 PKT_signature *sig = signode->pkt->pkt.signature;
1484 const byte *p, *sym, *hash, *zip;
1485 size_t n, nsym, nhash, nzip;
1487 sig->flags.chosen_selfsig = 1; /* we chose this one */
1488 uid->created = 0; /* not created == invalid */
1489 if ( IS_UID_REV ( sig ) ) {
1490 uid->is_revoked = 1;
1491 return; /* has been revoked */
1494 uid->expiredate = sig->expiredate;
1496 if(sig->flags.expired)
1498 uid->is_expired = 1;
1499 return; /* has expired */
1502 uid->created = sig->timestamp; /* this one is okay */
1503 uid->selfsigversion = sig->version;
1504 /* If we got this far, it's not expired :) */
1505 uid->is_expired = 0;
1507 /* store the key flags in the helper variable for later processing */
1508 uid->help_key_usage=parse_key_usage(sig);
1510 /* ditto or the key expiration */
1511 uid->help_key_expire = 0;
1512 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1513 if ( p ) {
1514 uid->help_key_expire = keycreated + buffer_to_u32(p);
1517 /* Set the primary user ID flag - we will later wipe out some
1518 * of them to only have one in our keyblock */
1519 uid->is_primary = 0;
1520 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
1521 if ( p && *p )
1522 uid->is_primary = 2;
1523 /* We could also query this from the unhashed area if it is not in
1524 * the hased area and then later try to decide which is the better
1525 * there should be no security problem with this.
1526 * For now we only look at the hashed one.
1529 /* Now build the preferences list. These must come from the
1530 hashed section so nobody can modify the ciphers a key is
1531 willing to accept. */
1532 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
1533 sym = p; nsym = p?n:0;
1534 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
1535 hash = p; nhash = p?n:0;
1536 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
1537 zip = p; nzip = p?n:0;
1538 if (uid->prefs)
1539 xfree (uid->prefs);
1540 n = nsym + nhash + nzip;
1541 if (!n)
1542 uid->prefs = NULL;
1543 else {
1544 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n+1));
1545 n = 0;
1546 for (; nsym; nsym--, n++) {
1547 uid->prefs[n].type = PREFTYPE_SYM;
1548 uid->prefs[n].value = *sym++;
1550 for (; nhash; nhash--, n++) {
1551 uid->prefs[n].type = PREFTYPE_HASH;
1552 uid->prefs[n].value = *hash++;
1554 for (; nzip; nzip--, n++) {
1555 uid->prefs[n].type = PREFTYPE_ZIP;
1556 uid->prefs[n].value = *zip++;
1558 uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
1559 uid->prefs[n].value = 0;
1562 /* see whether we have the MDC feature */
1563 uid->flags.mdc = 0;
1564 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1565 if (p && n && (p[0] & 0x01))
1566 uid->flags.mdc = 1;
1568 /* and the keyserver modify flag */
1569 uid->flags.ks_modify = 1;
1570 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1571 if (p && n && (p[0] & 0x80))
1572 uid->flags.ks_modify = 0;
1575 static void
1576 sig_to_revoke_info(PKT_signature *sig,struct revoke_info *rinfo)
1578 rinfo->date = sig->timestamp;
1579 rinfo->algo = sig->pubkey_algo;
1580 rinfo->keyid[0] = sig->keyid[0];
1581 rinfo->keyid[1] = sig->keyid[1];
1584 static void
1585 merge_selfsigs_main(KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo)
1587 PKT_public_key *pk = NULL;
1588 KBNODE k;
1589 u32 kid[2];
1590 u32 sigdate, uiddate, uiddate2;
1591 KBNODE signode, uidnode, uidnode2;
1592 u32 curtime = make_timestamp ();
1593 unsigned int key_usage = 0;
1594 u32 keytimestamp = 0;
1595 u32 key_expire = 0;
1596 int key_expire_seen = 0;
1597 byte sigversion = 0;
1599 *r_revoked = 0;
1600 memset(rinfo,0,sizeof(*rinfo));
1602 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
1603 BUG ();
1604 pk = keyblock->pkt->pkt.public_key;
1605 keytimestamp = pk->timestamp;
1607 keyid_from_pk( pk, kid );
1608 pk->main_keyid[0] = kid[0];
1609 pk->main_keyid[1] = kid[1];
1611 if ( pk->version < 4 ) {
1612 /* before v4 the key packet itself contains the expiration
1613 * date and there was no way to change it, so we start with
1614 * the one from the key packet */
1615 key_expire = pk->max_expiredate;
1616 key_expire_seen = 1;
1619 /* first pass: find the latest direct key self-signature.
1620 * We assume that the newest one overrides all others
1623 /* In case this key was already merged */
1624 xfree(pk->revkey);
1625 pk->revkey=NULL;
1626 pk->numrevkeys=0;
1628 signode = NULL;
1629 sigdate = 0; /* helper to find the latest signature */
1630 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next ) {
1631 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
1632 PKT_signature *sig = k->pkt->pkt.signature;
1633 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1634 if ( check_key_signature( keyblock, k, NULL ) )
1635 ; /* signature did not verify */
1636 else if ( IS_KEY_REV (sig) ){
1637 /* key has been revoked - there is no way to override
1638 * such a revocation, so we theoretically can stop now.
1639 * We should not cope with expiration times for revocations
1640 * here because we have to assume that an attacker can
1641 * generate all kinds of signatures. However due to the
1642 * fact that the key has been revoked it does not harm
1643 * either and by continuing we gather some more info on
1644 * that key.
1646 *r_revoked = 1;
1647 sig_to_revoke_info(sig,rinfo);
1649 else if ( IS_KEY_SIG (sig) ) {
1650 /* Add any revocation keys onto the pk. This is
1651 particularly interesting since we normally only
1652 get data from the most recent 1F signature, but
1653 you need multiple 1F sigs to properly handle
1654 revocation keys (PGP does it this way, and a
1655 revocation key could be sensitive and hence in a
1656 different signature). */
1657 if(sig->revkey) {
1658 int i;
1660 pk->revkey=
1661 xrealloc(pk->revkey,sizeof(struct revocation_key)*
1662 (pk->numrevkeys+sig->numrevkeys));
1664 for(i=0;i<sig->numrevkeys;i++)
1665 memcpy(&pk->revkey[pk->numrevkeys++],
1666 sig->revkey[i],
1667 sizeof(struct revocation_key));
1670 if( sig->timestamp >= sigdate ) {
1671 if(sig->flags.expired)
1672 ; /* signature has expired - ignore it */
1673 else {
1674 sigdate = sig->timestamp;
1675 signode = k;
1676 if( sig->version > sigversion )
1677 sigversion = sig->version;
1686 /* Remove dupes from the revocation keys */
1688 if(pk->revkey)
1690 int i,j,x,changed=0;
1692 for(i=0;i<pk->numrevkeys;i++)
1694 for(j=i+1;j<pk->numrevkeys;j++)
1696 if(memcmp(&pk->revkey[i],&pk->revkey[j],
1697 sizeof(struct revocation_key))==0)
1699 /* remove j */
1701 for(x=j;x<pk->numrevkeys-1;x++)
1702 pk->revkey[x]=pk->revkey[x+1];
1704 pk->numrevkeys--;
1705 j--;
1706 changed=1;
1711 if(changed)
1712 pk->revkey=xrealloc(pk->revkey,
1713 pk->numrevkeys*sizeof(struct revocation_key));
1716 if ( signode )
1718 /* some information from a direct key signature take precedence
1719 * over the same information given in UID sigs.
1721 PKT_signature *sig = signode->pkt->pkt.signature;
1722 const byte *p;
1724 key_usage=parse_key_usage(sig);
1726 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1727 if ( p )
1729 key_expire = keytimestamp + buffer_to_u32(p);
1730 key_expire_seen = 1;
1733 /* mark that key as valid: one direct key signature should
1734 * render a key as valid */
1735 pk->is_valid = 1;
1738 /* pass 1.5: look for key revocation signatures that were not made
1739 by the key (i.e. did a revocation key issue a revocation for
1740 us?). Only bother to do this if there is a revocation key in
1741 the first place and we're not revoked already. */
1743 if(!*r_revoked && pk->revkey)
1744 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
1746 if ( k->pkt->pkttype == PKT_SIGNATURE )
1748 PKT_signature *sig = k->pkt->pkt.signature;
1750 if(IS_KEY_REV(sig) &&
1751 (sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
1753 int rc=check_revocation_keys(pk,sig);
1754 if(rc==0)
1756 *r_revoked=2;
1757 sig_to_revoke_info(sig,rinfo);
1758 /* don't continue checking since we can't be any
1759 more revoked than this */
1760 break;
1762 else if(rc==G10ERR_NO_PUBKEY)
1763 pk->maybe_revoked=1;
1765 /* A failure here means the sig did not verify, was
1766 not issued by a revocation key, or a revocation
1767 key loop was broken. If a revocation key isn't
1768 findable, however, the key might be revoked and
1769 we don't know it. */
1771 /* TODO: In the future handle subkey and cert
1772 revocations? PGP doesn't, but it's in 2440. */
1777 /* second pass: look at the self-signature of all user IDs */
1778 signode = uidnode = NULL;
1779 sigdate = 0; /* helper to find the latest signature in one user ID */
1780 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1781 if ( k->pkt->pkttype == PKT_USER_ID ) {
1782 if ( uidnode && signode )
1784 fixup_uidnode ( uidnode, signode, keytimestamp );
1785 pk->is_valid=1;
1787 uidnode = k;
1788 signode = NULL;
1789 sigdate = 0;
1791 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
1792 PKT_signature *sig = k->pkt->pkt.signature;
1793 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1794 if ( check_key_signature( keyblock, k, NULL ) )
1795 ; /* signature did not verify */
1796 else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
1797 && sig->timestamp >= sigdate )
1799 /* Note: we allow to invalidate cert revocations
1800 * by a newer signature. An attacker can't use this
1801 * because a key should be revoced with a key revocation.
1802 * The reason why we have to allow for that is that at
1803 * one time an email address may become invalid but later
1804 * the same email address may become valid again (hired,
1805 * fired, hired again).
1808 sigdate = sig->timestamp;
1809 signode = k;
1810 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
1811 if( sig->version > sigversion )
1812 sigversion = sig->version;
1817 if ( uidnode && signode ) {
1818 fixup_uidnode ( uidnode, signode, keytimestamp );
1819 pk->is_valid = 1;
1822 /* If the key isn't valid yet, and we have
1823 --allow-non-selfsigned-uid set, then force it valid. */
1824 if(!pk->is_valid && opt.allow_non_selfsigned_uid)
1826 if(opt.verbose)
1827 log_info(_("Invalid key %s made valid by"
1828 " --allow-non-selfsigned-uid\n"),keystr_from_pk(pk));
1829 pk->is_valid = 1;
1832 /* The key STILL isn't valid, so try and find an ultimately
1833 trusted signature. */
1834 if(!pk->is_valid)
1836 uidnode=NULL;
1838 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
1840 if ( k->pkt->pkttype == PKT_USER_ID )
1841 uidnode = k;
1842 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
1844 PKT_signature *sig = k->pkt->pkt.signature;
1846 if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
1848 PKT_public_key *ultimate_pk;
1850 ultimate_pk=xmalloc_clear(sizeof(*ultimate_pk));
1852 /* We don't want to use the full get_pubkey to
1853 avoid infinite recursion in certain cases.
1854 There is no reason to check that an ultimately
1855 trusted key is still valid - if it has been
1856 revoked or the user should also renmove the
1857 ultimate trust flag. */
1858 if(get_pubkey_fast(ultimate_pk,sig->keyid)==0
1859 && check_key_signature2(keyblock,k,ultimate_pk,
1860 NULL,NULL,NULL,NULL)==0
1861 && get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
1863 free_public_key(ultimate_pk);
1864 pk->is_valid=1;
1865 break;
1868 free_public_key(ultimate_pk);
1874 /* Record the highest selfsig version so we know if this is a v3
1875 key through and through, or a v3 key with a v4 selfsig
1876 somewhere. This is useful in a few places to know if the key
1877 must be treated as PGP2-style or OpenPGP-style. Note that a
1878 selfsig revocation with a higher version number will also raise
1879 this value. This is okay since such a revocation must be
1880 issued by the user (i.e. it cannot be issued by someone else to
1881 modify the key behavior.) */
1883 pk->selfsigversion=sigversion;
1885 /* Now that we had a look at all user IDs we can now get some information
1886 * from those user IDs.
1889 if ( !key_usage ) {
1890 /* find the latest user ID with key flags set */
1891 uiddate = 0; /* helper to find the latest user ID */
1892 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1893 k = k->next ) {
1894 if ( k->pkt->pkttype == PKT_USER_ID ) {
1895 PKT_user_id *uid = k->pkt->pkt.user_id;
1896 if ( uid->help_key_usage && uid->created > uiddate ) {
1897 key_usage = uid->help_key_usage;
1898 uiddate = uid->created;
1903 if ( !key_usage ) { /* no key flags at all: get it from the algo */
1904 key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
1906 else { /* check that the usage matches the usage as given by the algo */
1907 int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
1908 if ( x ) /* mask it down to the actual allowed usage */
1909 key_usage &= x;
1912 /* Whatever happens, it's a primary key, so it can certify. */
1913 pk->pubkey_usage = key_usage|PUBKEY_USAGE_CERT;
1915 if ( !key_expire_seen ) {
1916 /* find the latest valid user ID with a key expiration set
1917 * Note, that this may be a different one from the above because
1918 * some user IDs may have no expiration date set */
1919 uiddate = 0;
1920 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1921 k = k->next ) {
1922 if ( k->pkt->pkttype == PKT_USER_ID ) {
1923 PKT_user_id *uid = k->pkt->pkt.user_id;
1924 if ( uid->help_key_expire && uid->created > uiddate ) {
1925 key_expire = uid->help_key_expire;
1926 uiddate = uid->created;
1932 /* Currently only v3 keys have a maximum expiration date, but I'll
1933 bet v5 keys get this feature again. */
1934 if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
1935 key_expire=pk->max_expiredate;
1937 pk->has_expired = key_expire >= curtime? 0 : key_expire;
1938 pk->expiredate = key_expire;
1940 /* Fixme: we should see how to get rid of the expiretime fields but
1941 * this needs changes at other places too. */
1943 /* and now find the real primary user ID and delete all others */
1944 uiddate = uiddate2 = 0;
1945 uidnode = uidnode2 = NULL;
1946 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1947 if ( k->pkt->pkttype == PKT_USER_ID &&
1948 !k->pkt->pkt.user_id->attrib_data) {
1949 PKT_user_id *uid = k->pkt->pkt.user_id;
1950 if (uid->is_primary)
1952 if(uid->created > uiddate)
1954 uiddate = uid->created;
1955 uidnode = k;
1957 else if(uid->created==uiddate && uidnode)
1959 /* The dates are equal, so we need to do a
1960 different (and arbitrary) comparison. This
1961 should rarely, if ever, happen. It's good to
1962 try and guarantee that two different GnuPG
1963 users with two different keyrings at least pick
1964 the same primary. */
1965 if(cmp_user_ids(uid,uidnode->pkt->pkt.user_id)>0)
1966 uidnode=k;
1969 else
1971 if(uid->created > uiddate2)
1973 uiddate2 = uid->created;
1974 uidnode2 = k;
1976 else if(uid->created==uiddate2 && uidnode2)
1978 if(cmp_user_ids(uid,uidnode2->pkt->pkt.user_id)>0)
1979 uidnode2=k;
1984 if ( uidnode ) {
1985 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1986 k = k->next ) {
1987 if ( k->pkt->pkttype == PKT_USER_ID &&
1988 !k->pkt->pkt.user_id->attrib_data) {
1989 PKT_user_id *uid = k->pkt->pkt.user_id;
1990 if ( k != uidnode )
1991 uid->is_primary = 0;
1995 else if( uidnode2 ) {
1996 /* none is flagged primary - use the latest user ID we have,
1997 and disambiguate with the arbitrary packet comparison. */
1998 uidnode2->pkt->pkt.user_id->is_primary = 1;
2000 else
2002 /* None of our uids were self-signed, so pick the one that
2003 sorts first to be the primary. This is the best we can do
2004 here since there are no self sigs to date the uids. */
2006 uidnode = NULL;
2008 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2009 k = k->next )
2011 if(k->pkt->pkttype==PKT_USER_ID
2012 && !k->pkt->pkt.user_id->attrib_data)
2014 if(!uidnode)
2016 uidnode=k;
2017 uidnode->pkt->pkt.user_id->is_primary=1;
2018 continue;
2020 else
2022 if(cmp_user_ids(k->pkt->pkt.user_id,
2023 uidnode->pkt->pkt.user_id)>0)
2025 uidnode->pkt->pkt.user_id->is_primary=0;
2026 uidnode=k;
2027 uidnode->pkt->pkt.user_id->is_primary=1;
2029 else
2030 k->pkt->pkt.user_id->is_primary=0; /* just to be
2031 safe */
2039 static void
2040 merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
2042 PKT_public_key *mainpk = NULL, *subpk = NULL;
2043 PKT_signature *sig;
2044 KBNODE k;
2045 u32 mainkid[2];
2046 u32 sigdate = 0;
2047 KBNODE signode;
2048 u32 curtime = make_timestamp ();
2049 unsigned int key_usage = 0;
2050 u32 keytimestamp = 0;
2051 u32 key_expire = 0;
2052 const byte *p;
2054 if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2055 BUG ();
2056 mainpk = keyblock->pkt->pkt.public_key;
2057 if ( mainpk->version < 4 )
2058 return; /* (actually this should never happen) */
2059 keyid_from_pk( mainpk, mainkid );
2060 subpk = subnode->pkt->pkt.public_key;
2061 keytimestamp = subpk->timestamp;
2063 subpk->is_valid = 0;
2064 subpk->main_keyid[0] = mainpk->main_keyid[0];
2065 subpk->main_keyid[1] = mainpk->main_keyid[1];
2067 /* find the latest key binding self-signature. */
2068 signode = NULL;
2069 sigdate = 0; /* helper to find the latest signature */
2070 for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2071 k = k->next ) {
2072 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
2073 sig = k->pkt->pkt.signature;
2074 if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
2075 if ( check_key_signature( keyblock, k, NULL ) )
2076 ; /* signature did not verify */
2077 else if ( IS_SUBKEY_REV (sig) ) {
2078 /* Note that this means that the date on a
2079 revocation sig does not matter - even if the
2080 binding sig is dated after the revocation sig,
2081 the subkey is still marked as revoked. This
2082 seems ok, as it is just as easy to make new
2083 subkeys rather than re-sign old ones as the
2084 problem is in the distribution. Plus, PGP (7)
2085 does this the same way. */
2086 subpk->is_revoked = 1;
2087 sig_to_revoke_info(sig,&subpk->revoked);
2088 /* although we could stop now, we continue to
2089 * figure out other information like the old expiration
2090 * time */
2092 else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate )
2094 if(sig->flags.expired)
2095 ; /* signature has expired - ignore it */
2096 else
2098 sigdate = sig->timestamp;
2099 signode = k;
2100 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
2107 /* no valid key binding */
2108 if ( !signode )
2109 return;
2111 sig = signode->pkt->pkt.signature;
2112 sig->flags.chosen_selfsig=1; /* so we know which selfsig we chose later */
2114 key_usage=parse_key_usage(sig);
2115 if ( !key_usage )
2117 /* no key flags at all: get it from the algo */
2118 key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2120 else
2122 /* check that the usage matches the usage as given by the algo */
2123 int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2124 if ( x ) /* mask it down to the actual allowed usage */
2125 key_usage &= x;
2128 subpk->pubkey_usage = key_usage;
2130 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2131 if ( p )
2132 key_expire = keytimestamp + buffer_to_u32(p);
2133 else
2134 key_expire = 0;
2135 subpk->has_expired = key_expire >= curtime? 0 : key_expire;
2136 subpk->expiredate = key_expire;
2138 /* algo doesn't exist */
2139 if(openpgp_pk_test_algo(subpk->pubkey_algo))
2140 return;
2142 subpk->is_valid = 1;
2144 /* Find the first 0x19 embedded signature on our self-sig. */
2145 if(subpk->backsig==0)
2147 int seq=0;
2148 size_t n;
2150 /* We do this while() since there may be other embedded
2151 signatures in the future. We only want 0x19 here. */
2152 while((p=enum_sig_subpkt(sig->hashed,
2153 SIGSUBPKT_SIGNATURE,&n,&seq,NULL)))
2154 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2155 break;
2157 if(p==NULL)
2159 seq=0;
2160 /* It is safe to have this in the unhashed area since the
2161 0x19 is located on the selfsig for convenience, not
2162 security. */
2163 while((p=enum_sig_subpkt(sig->unhashed,SIGSUBPKT_SIGNATURE,
2164 &n,&seq,NULL)))
2165 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2166 break;
2169 if(p)
2171 PKT_signature *backsig=xmalloc_clear(sizeof(PKT_signature));
2172 IOBUF backsig_buf=iobuf_temp_with_content(p,n);
2174 if(parse_signature(backsig_buf,PKT_SIGNATURE,n,backsig)==0)
2176 if(check_backsig(mainpk,subpk,backsig)==0)
2177 subpk->backsig=2;
2178 else
2179 subpk->backsig=1;
2182 iobuf_close(backsig_buf);
2183 free_seckey_enc(backsig);
2190 * Merge information from the self-signatures with the key, so that
2191 * we can later use them more easy.
2192 * The function works by first applying the self signatures to the
2193 * primary key and the to each subkey.
2194 * Here are the rules we use to decide which inormation from which
2195 * self-signature is used:
2196 * We check all self signatures or validity and ignore all invalid signatures.
2197 * All signatures are then ordered by their creation date ....
2198 * For the primary key:
2199 * FIXME the docs
2201 static void
2202 merge_selfsigs( KBNODE keyblock )
2204 KBNODE k;
2205 int revoked;
2206 struct revoke_info rinfo;
2207 PKT_public_key *main_pk;
2208 prefitem_t *prefs;
2209 int mdc_feature;
2211 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
2212 if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
2213 log_error ("expected public key but found secret key "
2214 "- must stop\n");
2215 /* we better exit here becuase a public key is expected at
2216 other places too. FIXME: Figure this out earlier and
2217 don't get to here at all */
2218 g10_exit (1);
2220 BUG ();
2223 merge_selfsigs_main ( keyblock, &revoked, &rinfo );
2225 /* now merge in the data from each of the subkeys */
2226 for(k=keyblock; k; k = k->next ) {
2227 if ( k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2228 merge_selfsigs_subkey ( keyblock, k );
2232 main_pk = keyblock->pkt->pkt.public_key;
2233 if ( revoked || main_pk->has_expired || !main_pk->is_valid ) {
2234 /* if the primary key is revoked, expired, or invalid we
2235 * better set the appropriate flags on that key and all
2236 * subkeys */
2237 for(k=keyblock; k; k = k->next ) {
2238 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2239 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2240 PKT_public_key *pk = k->pkt->pkt.public_key;
2241 if(!main_pk->is_valid)
2242 pk->is_valid = 0;
2243 if(revoked && !pk->is_revoked)
2245 pk->is_revoked = revoked;
2246 memcpy(&pk->revoked,&rinfo,sizeof(rinfo));
2248 if(main_pk->has_expired)
2249 pk->has_expired = main_pk->has_expired;
2252 return;
2255 /* set the preference list of all keys to those of the primary real
2256 * user ID. Note: we use these preferences when we don't know by
2257 * which user ID the key has been selected.
2258 * fixme: we should keep atoms of commonly used preferences or
2259 * use reference counting to optimize the preference lists storage.
2260 * FIXME: it might be better to use the intersection of
2261 * all preferences.
2262 * Do a similar thing for the MDC feature flag.
2264 prefs = NULL;
2265 mdc_feature = 0;
2266 for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
2267 if (k->pkt->pkttype == PKT_USER_ID
2268 && !k->pkt->pkt.user_id->attrib_data
2269 && k->pkt->pkt.user_id->is_primary) {
2270 prefs = k->pkt->pkt.user_id->prefs;
2271 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2272 break;
2275 for(k=keyblock; k; k = k->next ) {
2276 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2277 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2278 PKT_public_key *pk = k->pkt->pkt.public_key;
2279 if (pk->prefs)
2280 xfree (pk->prefs);
2281 pk->prefs = copy_prefs (prefs);
2282 pk->mdc_feature = mdc_feature;
2289 * Merge the secret keys from secblock into the pubblock thereby
2290 * replacing the public (sub)keys with their secret counterparts Hmmm:
2291 * It might be better to get away from the concept of entire secret
2292 * keys at all and have a way to store just the real secret parts
2293 * from the key.
2295 static void
2296 merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2298 KBNODE pub;
2300 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2301 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2303 for (pub=pubblock; pub; pub = pub->next ) {
2304 if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
2305 PKT_public_key *pk = pub->pkt->pkt.public_key;
2306 PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
2307 assert ( pub == pubblock ); /* only in the first node */
2308 /* there is nothing to compare in this case, so just replace
2309 * some information */
2310 copy_public_parts_to_secret_key ( pk, sk );
2311 free_public_key ( pk );
2312 pub->pkt->pkttype = PKT_SECRET_KEY;
2313 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2315 else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2316 KBNODE sec;
2317 PKT_public_key *pk = pub->pkt->pkt.public_key;
2319 /* this is more complicated: it may happen that the sequence
2320 * of the subkeys dosn't match, so we have to find the
2321 * appropriate secret key */
2322 for (sec=secblock->next; sec; sec = sec->next ) {
2323 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2324 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2325 if ( !cmp_public_secret_key ( pk, sk ) ) {
2326 copy_public_parts_to_secret_key ( pk, sk );
2327 free_public_key ( pk );
2328 pub->pkt->pkttype = PKT_SECRET_SUBKEY;
2329 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2330 break;
2334 if ( !sec )
2335 BUG(); /* already checked in premerge */
2340 /* This function checks that for every public subkey a corresponding
2341 * secret subkey is available and deletes the public subkey otherwise.
2342 * We need this function because we can't delete it later when we
2343 * actually merge the secret parts into the pubring.
2344 * The function also plays some games with the node flags.
2346 static void
2347 premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2349 KBNODE last, pub;
2351 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2352 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2354 for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
2355 pub->flag &= ~3; /* reset bits 0 and 1 */
2356 if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2357 KBNODE sec;
2358 PKT_public_key *pk = pub->pkt->pkt.public_key;
2360 for (sec=secblock->next; sec; sec = sec->next ) {
2361 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2362 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2363 if ( !cmp_public_secret_key ( pk, sk ) ) {
2364 if ( sk->protect.s2k.mode == 1001 ) {
2365 /* The secret parts are not available so
2366 we can't use that key for signing etc.
2367 Fix the pubkey usage */
2368 pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
2369 |PUBKEY_USAGE_AUTH);
2371 /* transfer flag bits 0 and 1 to the pubblock */
2372 pub->flag |= (sec->flag &3);
2373 break;
2377 if ( !sec ) {
2378 KBNODE next, ll;
2380 if (opt.verbose)
2381 log_info (_("no secret subkey"
2382 " for public subkey %s - ignoring\n"),
2383 keystr_from_pk (pk));
2384 /* we have to remove the subkey in this case */
2385 assert ( last );
2386 /* find the next subkey */
2387 for (next=pub->next,ll=pub;
2388 next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2389 ll = next, next = next->next )
2391 /* make new link */
2392 last->next = next;
2393 /* release this public subkey with all sigs */
2394 ll->next = NULL;
2395 release_kbnode( pub );
2396 /* let the loop continue */
2397 pub = last;
2401 /* We need to copy the found bits (0 and 1) from the secret key to
2402 the public key. This has already been done for the subkeys but
2403 got lost on the primary key - fix it here *. */
2404 pubblock->flag |= (secblock->flag & 3);
2410 /* See see whether the key fits
2411 * our requirements and in case we do not
2412 * request the primary key, we should select
2413 * a suitable subkey.
2414 * FIXME: Check against PGP 7 whether we still need a kludge
2415 * to favor type 16 keys over type 20 keys when type 20
2416 * has not been explitely requested.
2417 * Returns: True when a suitable key has been found.
2419 * We have to distinguish four cases: FIXME!
2420 * 1. No usage and no primary key requested
2421 * Examples for this case are that we have a keyID to be used
2422 * for decrytion or verification.
2423 * 2. No usage but primary key requested
2424 * This is the case for all functions which work on an
2425 * entire keyblock, e.g. for editing or listing
2426 * 3. Usage and primary key requested
2427 * FXME
2428 * 4. Usage but no primary key requested
2429 * FIXME
2430 * FIXME: Tell what is going to happen here and something about the rationale
2431 * Note: We don't use this function if no specific usage is requested;
2432 * This way the getkey functions can be used for plain key listings.
2434 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2435 * is the key we actually found by looking at the keyid or a fingerprint and
2436 * may eitehr point to the primary or one of the subkeys.
2439 static int
2440 finish_lookup (GETKEY_CTX ctx)
2442 KBNODE keyblock = ctx->keyblock;
2443 KBNODE k;
2444 KBNODE foundk = NULL;
2445 PKT_user_id *foundu = NULL;
2446 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2447 unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
2448 /* Request the primary if we're certifying another key, and also
2449 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2450 do not understand signatures made by a signing subkey. PGP 8
2451 does. */
2452 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2453 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2454 u32 latest_date;
2455 KBNODE latest_key;
2456 u32 curtime = make_timestamp ();
2458 assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
2460 ctx->found_key = NULL;
2462 if (ctx->exact) {
2463 for (k=keyblock; k; k = k->next) {
2464 if ( (k->flag & 1) ) {
2465 assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
2466 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
2467 foundk = k;
2468 break;
2473 for (k=keyblock; k; k = k->next) {
2474 if ( (k->flag & 2) ) {
2475 assert (k->pkt->pkttype == PKT_USER_ID);
2476 foundu = k->pkt->pkt.user_id;
2477 break;
2481 if ( DBG_CACHE )
2482 log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2483 (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
2484 foundk? "one":"all", req_usage);
2486 if (!req_usage) {
2487 latest_key = foundk? foundk:keyblock;
2488 goto found;
2491 if (!req_usage) {
2492 PKT_public_key *pk = foundk->pkt->pkt.public_key;
2493 if (pk->user_id)
2494 free_user_id (pk->user_id);
2495 pk->user_id = scopy_user_id (foundu);
2496 ctx->found_key = foundk;
2497 cache_user_id( keyblock );
2498 return 1; /* found */
2501 latest_date = 0;
2502 latest_key = NULL;
2503 /* do not look at subkeys if a certification key is requested */
2504 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
2505 KBNODE nextk;
2506 /* either start a loop or check just this one subkey */
2507 for (k=foundk?foundk:keyblock; k; k = nextk ) {
2508 PKT_public_key *pk;
2509 nextk = k->next;
2510 if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2511 continue;
2512 if ( foundk )
2513 nextk = NULL; /* what a hack */
2514 pk = k->pkt->pkt.public_key;
2515 if (DBG_CACHE)
2516 log_debug( "\tchecking subkey %08lX\n",
2517 (ulong)keyid_from_pk( pk, NULL));
2518 if ( !pk->is_valid ) {
2519 if (DBG_CACHE)
2520 log_debug( "\tsubkey not valid\n");
2521 continue;
2523 if ( pk->is_revoked ) {
2524 if (DBG_CACHE)
2525 log_debug( "\tsubkey has been revoked\n");
2526 continue;
2528 if ( pk->has_expired ) {
2529 if (DBG_CACHE)
2530 log_debug( "\tsubkey has expired\n");
2531 continue;
2533 if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
2534 if (DBG_CACHE)
2535 log_debug( "\tsubkey not yet valid\n");
2536 continue;
2539 if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2540 if (DBG_CACHE)
2541 log_debug( "\tusage does not match: want=%x have=%x\n",
2542 req_usage, pk->pubkey_usage );
2543 continue;
2546 if (DBG_CACHE)
2547 log_debug( "\tsubkey looks fine\n");
2548 if ( pk->timestamp > latest_date ) {
2549 latest_date = pk->timestamp;
2550 latest_key = k;
2555 /* Okay now try the primary key unless we want an exact
2556 * key ID match on a subkey */
2557 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
2558 PKT_public_key *pk;
2559 if (DBG_CACHE && !foundk && !req_prim )
2560 log_debug( "\tno suitable subkeys found - trying primary\n");
2561 pk = keyblock->pkt->pkt.public_key;
2562 if ( !pk->is_valid ) {
2563 if (DBG_CACHE)
2564 log_debug( "\tprimary key not valid\n");
2566 else if ( pk->is_revoked ) {
2567 if (DBG_CACHE)
2568 log_debug( "\tprimary key has been revoked\n");
2570 else if ( pk->has_expired ) {
2571 if (DBG_CACHE)
2572 log_debug( "\tprimary key has expired\n");
2574 else if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2575 if (DBG_CACHE)
2576 log_debug( "\tprimary key usage does not match: "
2577 "want=%x have=%x\n",
2578 req_usage, pk->pubkey_usage );
2580 else { /* okay */
2581 if (DBG_CACHE)
2582 log_debug( "\tprimary key may be used\n");
2583 latest_key = keyblock;
2584 latest_date = pk->timestamp;
2588 if ( !latest_key ) {
2589 if (DBG_CACHE)
2590 log_debug("\tno suitable key found - giving up\n");
2591 return 0;
2594 found:
2595 if (DBG_CACHE)
2596 log_debug( "\tusing key %08lX\n",
2597 (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
2599 if (latest_key) {
2600 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2601 if (pk->user_id)
2602 free_user_id (pk->user_id);
2603 pk->user_id = scopy_user_id (foundu);
2606 ctx->found_key = latest_key;
2608 if (latest_key != keyblock && opt.verbose)
2610 char *tempkeystr=
2611 xstrdup(keystr_from_pk(latest_key->pkt->pkt.public_key));
2612 log_info(_("using subkey %s instead of primary key %s\n"),
2613 tempkeystr, keystr_from_pk(keyblock->pkt->pkt.public_key));
2614 xfree(tempkeystr);
2617 cache_user_id( keyblock );
2619 return 1; /* found */
2623 static int
2624 lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
2626 int rc;
2627 KBNODE secblock = NULL; /* helper */
2628 int no_suitable_key = 0;
2630 rc = 0;
2631 while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
2632 /* If we are searching for the first key we have to make sure
2633 that the next interation does not no an implicit reset.
2634 This can be triggered by an empty key ring. */
2635 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2636 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2638 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2639 if (rc) {
2640 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
2641 rc = 0;
2642 goto skip;
2645 if ( secmode ) {
2646 /* find the correspondig public key and use this
2647 * this one for the selection process */
2648 u32 aki[2];
2649 KBNODE k = ctx->keyblock;
2651 if (k->pkt->pkttype != PKT_SECRET_KEY)
2652 BUG();
2654 keyid_from_sk (k->pkt->pkt.secret_key, aki);
2655 k = get_pubkeyblock (aki);
2656 if( !k )
2658 if (!opt.quiet)
2659 log_info(_("key %s: secret key without public key"
2660 " - skipped\n"), keystr(aki));
2661 goto skip;
2663 secblock = ctx->keyblock;
2664 ctx->keyblock = k;
2666 premerge_public_with_secret ( ctx->keyblock, secblock );
2669 /* warning: node flag bits 0 and 1 should be preserved by
2670 * merge_selfsigs. For secret keys, premerge did tranfer the
2671 * keys to the keyblock */
2672 merge_selfsigs ( ctx->keyblock );
2673 if ( finish_lookup (ctx) ) {
2674 no_suitable_key = 0;
2675 if ( secmode ) {
2676 merge_public_with_secret ( ctx->keyblock,
2677 secblock);
2678 release_kbnode (secblock);
2679 secblock = NULL;
2681 goto found;
2683 else
2684 no_suitable_key = 1;
2686 skip:
2687 /* release resources and continue search */
2688 if ( secmode ) {
2689 release_kbnode( secblock );
2690 secblock = NULL;
2692 release_kbnode( ctx->keyblock );
2693 ctx->keyblock = NULL;
2696 found:
2697 if( rc && rc != -1 )
2698 log_error("keydb_search failed: %s\n", g10_errstr(rc));
2700 if( !rc ) {
2701 *ret_keyblock = ctx->keyblock; /* return the keyblock */
2702 ctx->keyblock = NULL;
2704 else if (rc == -1 && no_suitable_key)
2705 rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
2706 else if( rc == -1 )
2707 rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
2709 if ( secmode ) {
2710 release_kbnode( secblock );
2711 secblock = NULL;
2713 release_kbnode( ctx->keyblock );
2714 ctx->keyblock = NULL;
2716 ctx->last_rc = rc;
2717 return rc;
2723 /****************
2724 * FIXME: Replace by the generic function
2725 * It does not work as it is right now - it is used at
2726 * 2 places: a) to get the key for an anonyous recipient
2727 * b) to get the ultimately trusted keys.
2728 * The a) usage might have some problems.
2730 * set with_subkeys true to include subkeys
2731 * set with_spm true to include secret-parts-missing keys
2733 * Enumerate all primary secret keys. Caller must use these procedure:
2734 * 1) create a void pointer and initialize it to NULL
2735 * 2) pass this void pointer by reference to this function
2736 * and provide space for the secret key (pass a buffer for sk)
2737 * 3) call this function as long as it does not return -1
2738 * to indicate EOF.
2739 * 4) Always call this function a last time with SK set to NULL,
2740 * so that can free it's context.
2743 enum_secret_keys( void **context, PKT_secret_key *sk,
2744 int with_subkeys, int with_spm )
2746 int rc=0;
2747 struct {
2748 int eof;
2749 int first;
2750 KEYDB_HANDLE hd;
2751 KBNODE keyblock;
2752 KBNODE node;
2753 } *c = *context;
2756 if( !c ) { /* make a new context */
2757 c = xmalloc_clear( sizeof *c );
2758 *context = c;
2759 c->hd = keydb_new (1);
2760 c->first = 1;
2761 c->keyblock = NULL;
2762 c->node = NULL;
2765 if( !sk ) { /* free the context */
2766 keydb_release (c->hd);
2767 release_kbnode (c->keyblock);
2768 xfree( c );
2769 *context = NULL;
2770 return 0;
2773 if( c->eof )
2774 return -1;
2776 do {
2777 /* get the next secret key from the current keyblock */
2778 for (; c->node; c->node = c->node->next) {
2779 if ((c->node->pkt->pkttype == PKT_SECRET_KEY
2780 || (with_subkeys
2781 && c->node->pkt->pkttype == PKT_SECRET_SUBKEY) )
2782 && !(c->node->pkt->pkt.secret_key->protect.s2k.mode==1001
2783 && !with_spm)) {
2784 copy_secret_key (sk, c->node->pkt->pkt.secret_key );
2785 c->node = c->node->next;
2786 return 0; /* found */
2789 release_kbnode (c->keyblock);
2790 c->keyblock = c->node = NULL;
2792 rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
2793 c->first = 0;
2794 if (rc) {
2795 keydb_release (c->hd); c->hd = NULL;
2796 c->eof = 1;
2797 return -1; /* eof */
2800 rc = keydb_get_keyblock (c->hd, &c->keyblock);
2801 c->node = c->keyblock;
2802 } while (!rc);
2804 return rc; /* error */
2809 /*********************************************
2810 *********** user ID printing helpers *******
2811 *********************************************/
2813 /****************
2814 * Return a string with a printable representation of the user_id.
2815 * this string must be freed by xfree.
2817 char*
2818 get_user_id_string( u32 *keyid )
2820 user_id_db_t r;
2821 char *p;
2822 int pass=0;
2823 /* try it two times; second pass reads from key resources */
2826 for(r=user_id_db; r; r = r->next )
2828 keyid_list_t a;
2829 for (a=r->keyids; a; a= a->next )
2831 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] )
2833 p = xmalloc( keystrlen() + 1 + r->len + 1 );
2834 sprintf(p, "%s %.*s", keystr(keyid), r->len, r->name );
2835 return p;
2839 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2840 p = xmalloc( keystrlen() + 5 );
2841 sprintf(p, "%s [?]", keystr(keyid));
2842 return p;
2846 char*
2847 get_user_id_string_native ( u32 *keyid )
2849 char *p = get_user_id_string( keyid );
2850 char *p2 = utf8_to_native( p, strlen(p), 0 );
2851 xfree(p);
2852 return p2;
2856 char*
2857 get_long_user_id_string( u32 *keyid )
2859 user_id_db_t r;
2860 char *p;
2861 int pass=0;
2862 /* try it two times; second pass reads from key resources */
2863 do {
2864 for(r=user_id_db; r; r = r->next ) {
2865 keyid_list_t a;
2866 for (a=r->keyids; a; a= a->next ) {
2867 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
2868 p = xmalloc( r->len + 20 );
2869 sprintf(p, "%08lX%08lX %.*s",
2870 (ulong)keyid[0], (ulong)keyid[1],
2871 r->len, r->name );
2872 return p;
2876 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2877 p = xmalloc( 25 );
2878 sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
2879 return p;
2882 char*
2883 get_user_id( u32 *keyid, size_t *rn )
2885 user_id_db_t r;
2886 char *p;
2887 int pass=0;
2889 /* try it two times; second pass reads from key resources */
2890 do {
2891 for(r=user_id_db; r; r = r->next ) {
2892 keyid_list_t a;
2893 for (a=r->keyids; a; a= a->next ) {
2894 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
2895 p = xmalloc( r->len );
2896 memcpy(p, r->name, r->len );
2897 *rn = r->len;
2898 return p;
2902 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2903 p = xstrdup( user_id_not_found_utf8 () );
2904 *rn = strlen(p);
2905 return p;
2908 char*
2909 get_user_id_native( u32 *keyid )
2911 size_t rn;
2912 char *p = get_user_id( keyid, &rn );
2913 char *p2 = utf8_to_native( p, rn, 0 );
2914 xfree(p);
2915 return p2;
2918 KEYDB_HANDLE
2919 get_ctx_handle(GETKEY_CTX ctx)
2921 return ctx->kr_handle;
2924 static void
2925 free_akl(struct akl *akl)
2927 if(akl->spec)
2928 free_keyserver_spec(akl->spec);
2930 xfree(akl);
2933 void
2934 release_akl(void)
2936 while(opt.auto_key_locate)
2938 struct akl *akl2=opt.auto_key_locate;
2939 opt.auto_key_locate=opt.auto_key_locate->next;
2940 free_akl(akl2);
2945 parse_auto_key_locate(char *options)
2947 char *tok;
2949 while((tok=optsep(&options)))
2951 struct akl *akl,*check,*last=NULL;
2952 int dupe=0;
2954 if(tok[0]=='\0')
2955 continue;
2957 akl=xmalloc_clear(sizeof(*akl));
2959 if(ascii_strcasecmp(tok,"ldap")==0)
2960 akl->type=AKL_LDAP;
2961 else if(ascii_strcasecmp(tok,"keyserver")==0)
2962 akl->type=AKL_KEYSERVER;
2963 #ifdef USE_DNS_CERT
2964 else if(ascii_strcasecmp(tok,"cert")==0)
2965 akl->type=AKL_CERT;
2966 #endif
2967 #ifdef USE_DNS_PKA
2968 else if(ascii_strcasecmp(tok,"pka")==0)
2969 akl->type=AKL_PKA;
2970 #endif
2971 else if((akl->spec=parse_keyserver_uri(tok,1,NULL,0)))
2972 akl->type=AKL_SPEC;
2973 else
2975 free_akl(akl);
2976 return 0;
2979 /* We must maintain the order the user gave us */
2980 for(check=opt.auto_key_locate;check;last=check,check=check->next)
2982 /* Check for duplicates */
2983 if(check->type==akl->type
2984 && (akl->type!=AKL_SPEC
2985 || (akl->type==AKL_SPEC
2986 && strcmp(check->spec->uri,akl->spec->uri)==0)))
2988 dupe=1;
2989 free_akl(akl);
2990 break;
2994 if(!dupe)
2996 if(last)
2997 last->next=akl;
2998 else
2999 opt.auto_key_locate=akl;
3003 return 1;