Avoid catch-22 with README.main not being distributed but having the
[gnupg.git] / g10 / keyserver.c
blob36c52f0a70b1f52d17adfc326beca52fdf9b1e8d
1 /* keyserver.c - generic keyserver code
2 * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
3 * 2009 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 3 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, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <ctype.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <assert.h>
27 #include <errno.h>
29 #include "gpg.h"
30 #include "iobuf.h"
31 #include "filter.h"
32 #include "keydb.h"
33 #include "status.h"
34 #include "exec.h"
35 #include "main.h"
36 #include "i18n.h"
37 #include "ttyio.h"
38 #include "options.h"
39 #include "packet.h"
40 #include "trustdb.h"
41 #include "keyserver-internal.h"
42 #include "util.h"
43 #include "dns-cert.h"
44 #include "pka.h"
45 #ifdef USE_DNS_SRV
46 #include "srv.h"
47 #endif
49 #ifdef HAVE_W32_SYSTEM
50 /* It seems Vista doesn't grok X_OK and so fails access() tests.
51 Previous versions interpreted X_OK as F_OK anyway, so we'll just
52 use F_OK directly. */
53 #undef X_OK
54 #define X_OK F_OK
55 #endif /* HAVE_W32_SYSTEM */
57 struct keyrec
59 KEYDB_SEARCH_DESC desc;
60 u32 createtime,expiretime;
61 int size,flags;
62 byte type;
63 IOBUF uidbuf;
64 unsigned int lines;
67 enum ks_action {KS_UNKNOWN=0,KS_GET,KS_GETNAME,KS_SEND,KS_SEARCH};
69 static struct parse_options keyserver_opts[]=
71 /* some of these options are not real - just for the help
72 message */
73 {"max-cert-size",0,NULL,NULL},
74 {"include-revoked",0,NULL,N_("include revoked keys in search results")},
75 {"include-subkeys",0,NULL,N_("include subkeys when searching by key ID")},
76 {"use-temp-files",0,NULL,
77 N_("use temporary files to pass data to keyserver helpers")},
78 {"keep-temp-files",KEYSERVER_KEEP_TEMP_FILES,NULL,
79 N_("do not delete temporary files after using them")},
80 {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL,
81 NULL},
82 {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL,
83 N_("automatically retrieve keys when verifying signatures")},
84 {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL,
85 N_("honor the preferred keyserver URL set on the key")},
86 {"honor-pka-record",KEYSERVER_HONOR_PKA_RECORD,NULL,
87 N_("honor the PKA record set on a key when retrieving keys")},
88 {NULL,0,NULL,NULL}
91 static int keyserver_work(enum ks_action action,strlist_t list,
92 KEYDB_SEARCH_DESC *desc,int count,
93 unsigned char **fpr,size_t *fpr_len,
94 struct keyserver_spec *keyserver);
96 /* Reasonable guess */
97 #define DEFAULT_MAX_CERT_SIZE 16384
99 static size_t max_cert_size=DEFAULT_MAX_CERT_SIZE;
101 static void
102 add_canonical_option(char *option,strlist_t *list)
104 char *arg=argsplit(option);
106 if(arg)
108 char *joined;
110 joined=xmalloc(strlen(option)+1+strlen(arg)+1);
111 /* Make a canonical name=value form with no spaces */
112 strcpy(joined,option);
113 strcat(joined,"=");
114 strcat(joined,arg);
115 append_to_strlist(list,joined);
116 xfree(joined);
118 else
119 append_to_strlist(list,option);
123 parse_keyserver_options(char *options)
125 int ret=1;
126 char *tok;
127 char *max_cert=NULL;
129 keyserver_opts[0].value=&max_cert;
131 while((tok=optsep(&options)))
133 if(tok[0]=='\0')
134 continue;
136 /* For backwards compatibility. 1.2.x used honor-http-proxy and
137 there are a good number of documents published that recommend
138 it. */
139 if(ascii_strcasecmp(tok,"honor-http-proxy")==0)
140 tok="http-proxy";
141 else if(ascii_strcasecmp(tok,"no-honor-http-proxy")==0)
142 tok="no-http-proxy";
144 /* We accept quite a few possible options here - some options to
145 handle specially, the keyserver_options list, and import and
146 export options that pertain to keyserver operations. Note
147 that you must use strncasecmp here as there might be an
148 =argument attached which will foil the use of strcasecmp. */
150 #ifdef EXEC_TEMPFILE_ONLY
151 if(ascii_strncasecmp(tok,"use-temp-files",14)==0 ||
152 ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
153 log_info(_("WARNING: keyserver option `%s' is not used"
154 " on this platform\n"),tok);
155 #else
156 if(ascii_strncasecmp(tok,"use-temp-files",14)==0)
157 opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
158 else if(ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
159 opt.keyserver_options.options&=~KEYSERVER_USE_TEMP_FILES;
160 #endif
161 else if(!parse_options(tok,&opt.keyserver_options.options,
162 keyserver_opts,0)
163 && !parse_import_options(tok,
164 &opt.keyserver_options.import_options,0)
165 && !parse_export_options(tok,
166 &opt.keyserver_options.export_options,0))
168 /* All of the standard options have failed, so the option is
169 destined for a keyserver plugin. */
170 add_canonical_option(tok,&opt.keyserver_options.other);
174 if(max_cert)
176 max_cert_size=strtoul(max_cert,(char **)NULL,10);
178 if(max_cert_size==0)
179 max_cert_size=DEFAULT_MAX_CERT_SIZE;
182 return ret;
185 void
186 free_keyserver_spec(struct keyserver_spec *keyserver)
188 xfree(keyserver->uri);
189 xfree(keyserver->scheme);
190 xfree(keyserver->auth);
191 xfree(keyserver->host);
192 xfree(keyserver->port);
193 xfree(keyserver->path);
194 xfree(keyserver->opaque);
195 free_strlist(keyserver->options);
196 xfree(keyserver);
199 /* Return 0 for match */
200 static int
201 cmp_keyserver_spec(struct keyserver_spec *one,struct keyserver_spec *two)
203 if(ascii_strcasecmp(one->scheme,two->scheme)==0)
205 if(one->host && two->host && ascii_strcasecmp(one->host,two->host)==0)
207 if((one->port && two->port
208 && ascii_strcasecmp(one->port,two->port)==0)
209 || (!one->port && !two->port))
210 return 0;
212 else if(one->opaque && two->opaque
213 && ascii_strcasecmp(one->opaque,two->opaque)==0)
214 return 0;
217 return 1;
220 /* Try and match one of our keyservers. If we can, return that. If
221 we can't, return our input. */
222 struct keyserver_spec *
223 keyserver_match(struct keyserver_spec *spec)
225 struct keyserver_spec *ks;
227 for(ks=opt.keyserver;ks;ks=ks->next)
228 if(cmp_keyserver_spec(spec,ks)==0)
229 return ks;
231 return spec;
234 /* TODO: once we cut over to an all-curl world, we don't need this
235 parser any longer so it can be removed, or at least moved to
236 keyserver/ksutil.c for limited use in gpgkeys_ldap or the like. */
238 struct keyserver_spec *
239 parse_keyserver_uri(const char *string,int require_scheme,
240 const char *configname,unsigned int configlineno)
242 int assume_hkp=0;
243 struct keyserver_spec *keyserver;
244 const char *idx;
245 int count;
246 char *uri,*options;
248 assert(string!=NULL);
250 keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
252 uri=xstrdup(string);
254 options=strchr(uri,' ');
255 if(options)
257 char *tok;
259 *options='\0';
260 options++;
262 while((tok=optsep(&options)))
263 add_canonical_option(tok,&keyserver->options);
266 /* Get the scheme */
268 for(idx=uri,count=0;*idx && *idx!=':';idx++)
270 count++;
272 /* Do we see the start of an RFC-2732 ipv6 address here? If so,
273 there clearly isn't a scheme so get out early. */
274 if(*idx=='[')
276 /* Was the '[' the first thing in the string? If not, we
277 have a mangled scheme with a [ in it so fail. */
278 if(count==1)
279 break;
280 else
281 goto fail;
285 if(count==0)
286 goto fail;
288 if(*idx=='\0' || *idx=='[')
290 if(require_scheme)
291 return NULL;
293 /* Assume HKP if there is no scheme */
294 assume_hkp=1;
295 keyserver->scheme=xstrdup("hkp");
297 keyserver->uri=xmalloc(strlen(keyserver->scheme)+3+strlen(uri)+1);
298 strcpy(keyserver->uri,keyserver->scheme);
299 strcat(keyserver->uri,"://");
300 strcat(keyserver->uri,uri);
302 else
304 int i;
306 keyserver->uri=xstrdup(uri);
308 keyserver->scheme=xmalloc(count+1);
310 /* Force to lowercase */
311 for(i=0;i<count;i++)
312 keyserver->scheme[i]=ascii_tolower(uri[i]);
314 keyserver->scheme[i]='\0';
316 /* Skip past the scheme and colon */
317 uri+=count+1;
320 if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
322 deprecated_warning(configname,configlineno,"x-broken-hkp",
323 "--keyserver-options ","broken-http-proxy");
324 xfree(keyserver->scheme);
325 keyserver->scheme=xstrdup("hkp");
326 append_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
328 else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
330 /* Canonicalize this to "hkp" so it works with both the internal
331 and external keyserver interface. */
332 xfree(keyserver->scheme);
333 keyserver->scheme=xstrdup("hkp");
336 if (uri[0]=='/' && uri[1]=='/' && uri[2] == '/')
338 /* Three slashes means network path with a default host name.
339 This is a hack because it does not crok all possible
340 combiantions. We should better repalce all code bythe parser
341 from http.c. */
342 keyserver->path = xstrdup (uri+2);
344 else if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
346 /* Two slashes means network path. */
348 /* Skip over the "//", if any */
349 if(!assume_hkp)
350 uri+=2;
352 /* Do we have userinfo auth data present? */
353 for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++)
354 count++;
356 /* We found a @ before the slash, so that means everything
357 before the @ is auth data. */
358 if(*idx=='@')
360 if(count==0)
361 goto fail;
363 keyserver->auth=xmalloc(count+1);
364 strncpy(keyserver->auth,uri,count);
365 keyserver->auth[count]='\0';
366 uri+=count+1;
369 /* Is it an RFC-2732 ipv6 [literal address] ? */
370 if(*uri=='[')
372 for(idx=uri+1,count=1;*idx
373 && ((isascii (*idx) && isxdigit(*idx))
374 || *idx==':' || *idx=='.');idx++)
375 count++;
377 /* Is the ipv6 literal address terminated? */
378 if(*idx==']')
379 count++;
380 else
381 goto fail;
383 else
384 for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
385 count++;
387 if(count==0)
388 goto fail;
390 keyserver->host=xmalloc(count+1);
391 strncpy(keyserver->host,uri,count);
392 keyserver->host[count]='\0';
394 /* Skip past the host */
395 uri+=count;
397 if(*uri==':')
399 /* It would seem to be reasonable to limit the range of the
400 ports to values between 1-65535, but RFC 1738 and 1808
401 imply there is no limit. Of course, the real world has
402 limits. */
404 for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
406 count++;
408 /* Ports are digits only */
409 if(!digitp(idx))
410 goto fail;
413 keyserver->port=xmalloc(count+1);
414 strncpy(keyserver->port,uri+1,count);
415 keyserver->port[count]='\0';
417 /* Skip past the colon and port number */
418 uri+=1+count;
421 /* Everything else is the path */
422 if(*uri)
423 keyserver->path=xstrdup(uri);
424 else
425 keyserver->path=xstrdup("/");
427 if(keyserver->path[1])
428 keyserver->flags.direct_uri=1;
430 else if(uri[0]!='/')
432 /* No slash means opaque. Just record the opaque blob and get
433 out. */
434 keyserver->opaque=xstrdup(uri);
436 else
438 /* One slash means absolute path. We don't need to support that
439 yet. */
440 goto fail;
443 return keyserver;
445 fail:
446 free_keyserver_spec(keyserver);
448 return NULL;
451 struct keyserver_spec *
452 parse_preferred_keyserver(PKT_signature *sig)
454 struct keyserver_spec *spec=NULL;
455 const byte *p;
456 size_t plen;
458 p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
459 if(p && plen)
461 byte *dupe=xmalloc(plen+1);
463 memcpy(dupe,p,plen);
464 dupe[plen]='\0';
465 spec=parse_keyserver_uri(dupe,1,NULL,0);
466 xfree(dupe);
469 return spec;
472 static void
473 print_keyrec(int number,struct keyrec *keyrec)
475 int i;
477 iobuf_writebyte(keyrec->uidbuf,0);
478 iobuf_flush_temp(keyrec->uidbuf);
479 printf("(%d)\t%s ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
481 if(keyrec->size>0)
482 printf("%d bit ",keyrec->size);
484 if(keyrec->type)
486 const char *str = gcry_pk_algo_name (keyrec->type);
488 if(str)
489 printf("%s ",str);
490 else
491 printf("unknown ");
494 switch(keyrec->desc.mode)
496 /* If the keyserver helper gave us a short keyid, we have no
497 choice but to use it. Do check --keyid-format to add a 0x if
498 needed. */
499 case KEYDB_SEARCH_MODE_SHORT_KID:
500 printf("key %s%08lX",
501 (opt.keyid_format==KF_0xSHORT
502 || opt.keyid_format==KF_0xLONG)?"0x":"",
503 (ulong)keyrec->desc.u.kid[1]);
504 break;
506 /* However, if it gave us a long keyid, we can honor
507 --keyid-format */
508 case KEYDB_SEARCH_MODE_LONG_KID:
509 printf("key %s",keystr(keyrec->desc.u.kid));
510 break;
512 case KEYDB_SEARCH_MODE_FPR16:
513 printf("key ");
514 for(i=0;i<16;i++)
515 printf("%02X",keyrec->desc.u.fpr[i]);
516 break;
518 case KEYDB_SEARCH_MODE_FPR20:
519 printf("key ");
520 for(i=0;i<20;i++)
521 printf("%02X",keyrec->desc.u.fpr[i]);
522 break;
524 default:
525 BUG();
526 break;
529 if(keyrec->createtime>0)
531 printf(", ");
532 printf(_("created: %s"),strtimestamp(keyrec->createtime));
535 if(keyrec->expiretime>0)
537 printf(", ");
538 printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
541 if(keyrec->flags&1)
542 printf(" (%s)",_("revoked"));
543 if(keyrec->flags&2)
544 printf(" (%s)",_("disabled"));
545 if(keyrec->flags&4)
546 printf(" (%s)",_("expired"));
548 printf("\n");
551 /* Returns a keyrec (which must be freed) once a key is complete, and
552 NULL otherwise. Call with a NULL keystring once key parsing is
553 complete to return any unfinished keys. */
554 static struct keyrec *
555 parse_keyrec(char *keystring)
557 static struct keyrec *work=NULL;
558 struct keyrec *ret=NULL;
559 char *record;
560 int i;
562 if(keystring==NULL)
564 if(work==NULL)
565 return NULL;
566 else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
568 xfree(work);
569 return NULL;
571 else
573 ret=work;
574 work=NULL;
575 return ret;
579 if(work==NULL)
581 work=xmalloc_clear(sizeof(struct keyrec));
582 work->uidbuf=iobuf_temp();
585 /* Remove trailing whitespace */
586 for(i=strlen(keystring);i>0;i--)
587 if(ascii_isspace(keystring[i-1]))
588 keystring[i-1]='\0';
589 else
590 break;
592 if((record=strsep(&keystring,":"))==NULL)
593 return ret;
595 if(ascii_strcasecmp("pub",record)==0)
597 char *tok;
599 if(work->desc.mode)
601 ret=work;
602 work=xmalloc_clear(sizeof(struct keyrec));
603 work->uidbuf=iobuf_temp();
606 if((tok=strsep(&keystring,":"))==NULL)
607 return ret;
609 classify_user_id(tok,&work->desc);
610 if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
611 && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
612 && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
613 && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
615 work->desc.mode=KEYDB_SEARCH_MODE_NONE;
616 return ret;
619 /* Note all items after this are optional. This allows us to
620 have a pub line as simple as pub:keyid and nothing else. */
622 work->lines++;
624 if((tok=strsep(&keystring,":"))==NULL)
625 return ret;
627 work->type=atoi(tok);
629 if((tok=strsep(&keystring,":"))==NULL)
630 return ret;
632 work->size=atoi(tok);
634 if((tok=strsep(&keystring,":"))==NULL)
635 return ret;
637 if(atoi(tok)<=0)
638 work->createtime=0;
639 else
640 work->createtime=atoi(tok);
642 if((tok=strsep(&keystring,":"))==NULL)
643 return ret;
645 if(atoi(tok)<=0)
646 work->expiretime=0;
647 else
649 work->expiretime=atoi(tok);
650 /* Force the 'e' flag on if this key is expired. */
651 if(work->expiretime<=make_timestamp())
652 work->flags|=4;
655 if((tok=strsep(&keystring,":"))==NULL)
656 return ret;
658 while(*tok)
659 switch(*tok++)
661 case 'r':
662 case 'R':
663 work->flags|=1;
664 break;
666 case 'd':
667 case 'D':
668 work->flags|=2;
669 break;
671 case 'e':
672 case 'E':
673 work->flags|=4;
674 break;
677 else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
679 char *userid,*tok,*decoded;
681 if((tok=strsep(&keystring,":"))==NULL)
682 return ret;
684 if(strlen(tok)==0)
685 return ret;
687 userid=tok;
689 /* By definition, de-%-encoding is always smaller than the
690 original string so we can decode in place. */
692 i=0;
694 while(*tok)
695 if(tok[0]=='%' && tok[1] && tok[2])
697 int c;
699 userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c;
700 i++;
701 tok+=3;
703 else
704 userid[i++]=*tok++;
706 /* We don't care about the other info provided in the uid: line
707 since no keyserver supports marking userids with timestamps
708 or revoked/expired/disabled yet. */
710 /* No need to check for control characters, as utf8_to_native
711 does this for us. */
713 decoded=utf8_to_native(userid,i,0);
714 if(strlen(decoded)>opt.screen_columns-10)
715 decoded[opt.screen_columns-10]='\0';
716 iobuf_writestr(work->uidbuf,decoded);
717 xfree(decoded);
718 iobuf_writestr(work->uidbuf,"\n\t");
719 work->lines++;
722 /* Ignore any records other than "pri" and "uid" for easy future
723 growth. */
725 return ret;
728 /* TODO: do this as a list sent to keyserver_work rather than calling
729 it once for each key to get the correct counts after the import
730 (cosmetics, really) and to better take advantage of the keyservers
731 that can do multiple fetches in one go (LDAP). */
732 static int
733 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
735 char *answer;
737 fflush (stdout);
739 if(count && opt.command_fd==-1)
741 static int from=1;
742 tty_printf("Keys %d-%d of %d for \"%s\". ",from,numdesc,count,search);
743 from=numdesc+1;
746 answer=cpr_get_no_help("keysearch.prompt",
747 _("Enter number(s), N)ext, or Q)uit > "));
748 /* control-d */
749 if(answer[0]=='\x04')
751 printf("Q\n");
752 answer[0]='q';
755 if(answer[0]=='q' || answer[0]=='Q')
757 xfree(answer);
758 return 1;
760 else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
762 char *split=answer,*num;
764 while((num=strsep(&split," ,"))!=NULL)
765 if(atoi(num)>=1 && atoi(num)<=numdesc)
766 keyserver_work(KS_GET,NULL,&desc[atoi(num)-1],1,
767 NULL,NULL,opt.keyserver);
769 xfree(answer);
770 return 1;
773 return 0;
776 /* Count and searchstr are just for cosmetics. If the count is too
777 small, it will grow safely. If negative it disables the "Key x-y
778 of z" messages. searchstr should be UTF-8 (rather than native). */
779 static void
780 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
782 int i=0,validcount=0,started=0,header=0,count=1;
783 unsigned int maxlen,buflen,numlines=0;
784 KEYDB_SEARCH_DESC *desc;
785 byte *line=NULL;
786 char *localstr=NULL;
788 if(searchstr)
789 localstr=utf8_to_native(searchstr,strlen(searchstr),0);
791 desc=xmalloc(count*sizeof(KEYDB_SEARCH_DESC));
793 for(;;)
795 struct keyrec *keyrec;
796 int rl;
798 maxlen=1024;
799 rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
801 if(opt.with_colons)
803 if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
804 && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
806 header=1;
807 continue;
809 else if(ascii_strncasecmp("SEARCH ",line,7)==0
810 && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
811 continue;
813 printf("%s",line);
816 /* Look for an info: line. The only current info: values
817 defined are the version and key count. */
818 if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
820 char *tok,*str=&line[5];
822 if((tok=strsep(&str,":"))!=NULL)
824 int version;
826 if(sscanf(tok,"%d",&version)!=1)
827 version=1;
829 if(version!=1)
831 log_error(_("invalid keyserver protocol "
832 "(us %d!=handler %d)\n"),1,version);
833 break;
837 if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
839 if(count==0)
840 goto notfound;
841 else if(count<0)
842 count=10;
843 else
844 validcount=1;
846 desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
849 started=1;
850 continue;
853 if(rl==0)
855 keyrec=parse_keyrec(NULL);
857 if(keyrec==NULL)
859 if(i==0)
861 count=0;
862 break;
865 if(i!=count)
866 validcount=0;
868 if (opt.with_colons && opt.batch)
869 break;
871 for(;;)
873 if(show_prompt(desc,i,validcount?count:0,localstr))
874 break;
875 validcount=0;
878 break;
881 else
882 keyrec=parse_keyrec(line);
884 if(i==count)
886 /* keyserver helper sent more keys than they claimed in the
887 info: line. */
888 count+=10;
889 desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
890 validcount=0;
893 if(keyrec)
895 desc[i]=keyrec->desc;
897 if(!opt.with_colons)
899 /* screen_lines - 1 for the prompt. */
900 if(numlines+keyrec->lines>opt.screen_lines-1)
902 if(show_prompt(desc,i,validcount?count:0,localstr))
903 break;
904 else
905 numlines=0;
908 print_keyrec(i+1,keyrec);
911 numlines+=keyrec->lines;
912 iobuf_close(keyrec->uidbuf);
913 xfree(keyrec);
915 started=1;
916 i++;
920 notfound:
921 /* Leave this commented out or now, and perhaps for a very long
922 time. All HKPish servers return HTML error messages for
923 no-key-found. */
925 if(!started)
926 log_info(_("keyserver does not support searching\n"));
927 else
929 if(count==0)
931 if(localstr)
932 log_info(_("key \"%s\" not found on keyserver\n"),localstr);
933 else
934 log_info(_("key not found on keyserver\n"));
937 xfree(localstr);
938 xfree(desc);
939 xfree(line);
942 /* We sometimes want to use a different gpgkeys_xxx for a given
943 protocol (for example, ldaps is handled by gpgkeys_ldap). Map
944 these here. */
945 static const char *
946 keyserver_typemap(const char *type)
948 if(strcmp(type,"ldaps")==0)
949 return "ldap";
950 else if(strcmp(type,"hkps")==0)
951 return "hkp";
952 else
953 return type;
956 /* The PGP LDAP and the curl fetch-a-LDAP-object methodologies are
957 sufficiently different that we can't use curl to do LDAP. */
958 static int
959 direct_uri_map(const char *scheme,unsigned int is_direct)
961 if(is_direct && strcmp(scheme,"ldap")==0)
962 return 1;
964 return 0;
967 #if GNUPG_MAJOR_VERSION == 2
968 #define GPGKEYS_PREFIX "gpg2keys_"
969 #else
970 #define GPGKEYS_PREFIX "gpgkeys_"
971 #endif
972 #define GPGKEYS_CURL GPGKEYS_PREFIX "curl" EXEEXT
973 #define GPGKEYS_PREFIX_LEN (strlen(GPGKEYS_CURL))
974 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
975 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
977 static int
978 keyserver_spawn(enum ks_action action,strlist_t list,KEYDB_SEARCH_DESC *desc,
979 int count,int *prog,unsigned char **fpr,size_t *fpr_len,
980 struct keyserver_spec *keyserver)
982 int ret=0,i,gotversion=0,outofband=0;
983 strlist_t temp;
984 unsigned int maxlen,buflen;
985 char *command,*end,*searchstr=NULL;
986 byte *line=NULL;
987 struct exec_info *spawn;
988 const char *scheme;
989 const char *libexecdir = gnupg_libexecdir ();
991 assert(keyserver);
993 #ifdef EXEC_TEMPFILE_ONLY
994 opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
995 #endif
997 /* Build the filename for the helper to execute */
998 scheme=keyserver_typemap(keyserver->scheme);
1000 #ifdef DISABLE_KEYSERVER_PATH
1001 /* Destroy any path we might have. This is a little tricky,
1002 portability-wise. It's not correct to delete the PATH
1003 environment variable, as that may fall back to a system built-in
1004 PATH. Similarly, it is not correct to set PATH to the null
1005 string (PATH="") since this actually deletes the PATH environment
1006 variable under MinGW. The safest thing to do here is to force
1007 PATH to be GNUPG_LIBEXECDIR. All this is not that meaningful on
1008 Unix-like systems (since we're going to give a full path to
1009 gpgkeys_foo), but on W32 it prevents loading any DLLs from
1010 directories in %PATH%.
1012 After some more thinking about this we came to the conclusion
1013 that it is better to load the helpers from the directory where
1014 the program of this process lives. Fortunately Windows provides
1015 a way to retrieve this and our gnupg_libexecdir function has been
1016 modified to return just this. Setting the exec-path is not
1017 anymore required.
1018 set_exec_path(libexecdir);
1020 #else
1021 if(opt.exec_path_set)
1023 /* If exec-path was set, and DISABLE_KEYSERVER_PATH is
1024 undefined, then don't specify a full path to gpgkeys_foo, so
1025 that the PATH can work. */
1026 command=xmalloc(GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1027 command[0]='\0';
1029 else
1030 #endif
1032 /* Specify a full path to gpgkeys_foo. */
1033 command=xmalloc(strlen(libexecdir)+strlen(DIRSEP_S)+
1034 GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1035 strcpy(command,libexecdir);
1036 strcat(command,DIRSEP_S);
1039 end=command+strlen(command);
1041 /* Build a path for the keyserver helper. If it is direct_uri
1042 (i.e. an object fetch and not a keyserver), then add "_uri" to
1043 the end to distinguish the keyserver helper from an object
1044 fetcher that can speak that protocol (this is a problem for
1045 LDAP). */
1047 strcat(command,GPGKEYS_PREFIX);
1048 strcat(command,scheme);
1050 /* This "_uri" thing is in case we need to call a direct handler
1051 instead of the keyserver handler. This lets us use gpgkeys_curl
1052 or gpgkeys_ldap_uri (we don't provide it, but a user might)
1053 instead of gpgkeys_ldap to fetch things like
1054 ldap://keyserver.pgp.com/o=PGP%20keys?pgpkey?sub?pgpkeyid=99242560 */
1056 if(direct_uri_map(scheme,keyserver->flags.direct_uri))
1057 strcat(command,"_uri");
1059 strcat(command,EXEEXT);
1061 /* Can we execute it? If not, try curl as our catchall. */
1062 if(path_access(command,X_OK)!=0)
1063 strcpy(end,GPGKEYS_CURL);
1065 if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
1067 if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
1069 command=xrealloc(command,strlen(command)+
1070 strlen(KEYSERVER_ARGS_KEEP)+1);
1071 strcat(command,KEYSERVER_ARGS_KEEP);
1073 else
1075 command=xrealloc(command,strlen(command)+
1076 strlen(KEYSERVER_ARGS_NOKEEP)+1);
1077 strcat(command,KEYSERVER_ARGS_NOKEEP);
1080 ret=exec_write(&spawn,NULL,command,NULL,0,0);
1082 else
1083 ret=exec_write(&spawn,command,NULL,NULL,0,0);
1085 xfree(command);
1087 if(ret)
1088 return ret;
1090 fprintf(spawn->tochild,
1091 "# This is a GnuPG %s keyserver communications file\n",VERSION);
1092 fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1093 fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
1094 fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
1096 if(keyserver->opaque)
1097 fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
1098 else
1100 if(keyserver->auth)
1101 fprintf(spawn->tochild,"AUTH %s\n",keyserver->auth);
1103 if(keyserver->host)
1104 fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
1106 if(keyserver->port)
1107 fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
1109 if(keyserver->path)
1110 fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
1113 /* Write global options */
1115 for(temp=opt.keyserver_options.other;temp;temp=temp->next)
1116 fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1118 /* Write per-keyserver options */
1120 for(temp=keyserver->options;temp;temp=temp->next)
1121 fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1123 switch(action)
1125 case KS_GET:
1127 fprintf(spawn->tochild,"COMMAND GET\n\n");
1129 /* Which keys do we want? */
1131 for(i=0;i<count;i++)
1133 int quiet=0;
1135 if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
1137 int f;
1139 fprintf(spawn->tochild,"0x");
1141 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
1142 fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1144 fprintf(spawn->tochild,"\n");
1146 else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
1148 int f;
1150 fprintf(spawn->tochild,"0x");
1152 for(f=0;f<16;f++)
1153 fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1155 fprintf(spawn->tochild,"\n");
1157 else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
1158 fprintf(spawn->tochild,"0x%08lX%08lX\n",
1159 (ulong)desc[i].u.kid[0],
1160 (ulong)desc[i].u.kid[1]);
1161 else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
1162 fprintf(spawn->tochild,"0x%08lX\n",
1163 (ulong)desc[i].u.kid[1]);
1164 else if(desc[i].mode==KEYDB_SEARCH_MODE_EXACT)
1166 fprintf(spawn->tochild,"0x0000000000000000\n");
1167 quiet=1;
1169 else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
1170 continue;
1171 else
1172 BUG();
1174 if(!quiet)
1176 if(keyserver->host)
1177 log_info(_("requesting key %s from %s server %s\n"),
1178 keystr_from_desc(&desc[i]),
1179 keyserver->scheme,keyserver->host);
1180 else
1181 log_info(_("requesting key %s from %s\n"),
1182 keystr_from_desc(&desc[i]),keyserver->uri);
1186 fprintf(spawn->tochild,"\n");
1188 break;
1191 case KS_GETNAME:
1193 strlist_t key;
1195 fprintf(spawn->tochild,"COMMAND GETNAME\n\n");
1197 /* Which names do we want? */
1199 for(key=list;key!=NULL;key=key->next)
1200 fprintf(spawn->tochild,"%s\n",key->d);
1202 fprintf(spawn->tochild,"\n");
1204 if(keyserver->host)
1205 log_info(_("searching for names from %s server %s\n"),
1206 keyserver->scheme,keyserver->host);
1207 else
1208 log_info(_("searching for names from %s\n"),keyserver->uri);
1210 break;
1213 case KS_SEND:
1215 strlist_t key;
1217 /* Note the extra \n here to send an empty keylist block */
1218 fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
1220 for(key=list;key!=NULL;key=key->next)
1222 armor_filter_context_t *afx;
1223 IOBUF buffer = iobuf_temp ();
1224 KBNODE block;
1226 temp=NULL;
1227 add_to_strlist(&temp,key->d);
1229 afx = new_armor_context ();
1230 afx->what = 1;
1231 /* Tell the armor filter to use Unix-style \n line
1232 endings, since we're going to fprintf this to a file
1233 that (on Win32) is open in text mode. The win32 stdio
1234 will transform the \n to \r\n and we'll end up with the
1235 proper line endings on win32. This is a no-op on
1236 Unix. */
1237 afx->eol[0] = '\n';
1238 push_armor_filter (afx, buffer);
1239 release_armor_context (afx);
1241 /* TODO: Remove Comment: lines from keys exported this
1242 way? */
1244 if(export_pubkeys_stream(buffer,temp,&block,
1245 opt.keyserver_options.export_options)==-1)
1246 iobuf_close(buffer);
1247 else
1249 KBNODE node;
1251 iobuf_flush_temp(buffer);
1253 merge_keys_and_selfsig(block);
1255 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
1256 (ulong)block->pkt->pkt.public_key->keyid[0],
1257 (ulong)block->pkt->pkt.public_key->keyid[1]);
1259 for(node=block;node;node=node->next)
1261 switch(node->pkt->pkttype)
1263 default:
1264 continue;
1266 case PKT_PUBLIC_KEY:
1267 case PKT_PUBLIC_SUBKEY:
1269 PKT_public_key *pk=node->pkt->pkt.public_key;
1271 keyid_from_pk(pk,NULL);
1273 fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
1274 node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
1275 (ulong)pk->keyid[0],(ulong)pk->keyid[1],
1276 pk->pubkey_algo,
1277 nbits_from_pk(pk),
1278 pk->timestamp,
1279 pk->expiredate);
1281 if(pk->is_revoked)
1282 fprintf(spawn->tochild,"r");
1283 if(pk->has_expired)
1284 fprintf(spawn->tochild,"e");
1286 fprintf(spawn->tochild,"\n");
1288 break;
1290 case PKT_USER_ID:
1292 PKT_user_id *uid=node->pkt->pkt.user_id;
1293 int r;
1295 if(uid->attrib_data)
1296 continue;
1298 fprintf(spawn->tochild,"uid:");
1300 /* Quote ':', '%', and any 8-bit
1301 characters */
1302 for(r=0;r<uid->len;r++)
1304 if(uid->name[r]==':' || uid->name[r]=='%'
1305 || uid->name[r]&0x80)
1306 fprintf(spawn->tochild,"%%%02X",
1307 (byte)uid->name[r]);
1308 else
1309 fprintf(spawn->tochild,"%c",uid->name[r]);
1312 fprintf(spawn->tochild,":%u:%u:",
1313 uid->created,uid->expiredate);
1315 if(uid->is_revoked)
1316 fprintf(spawn->tochild,"r");
1317 if(uid->is_expired)
1318 fprintf(spawn->tochild,"e");
1320 fprintf(spawn->tochild,"\n");
1322 break;
1324 /* This bit is really for the benefit of
1325 people who store their keys in LDAP
1326 servers. It makes it easy to do queries
1327 for things like "all keys signed by
1328 Isabella". */
1329 case PKT_SIGNATURE:
1331 PKT_signature *sig=node->pkt->pkt.signature;
1333 if(!IS_UID_SIG(sig))
1334 continue;
1336 fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1337 (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1338 sig->sig_class,sig->timestamp,
1339 sig->expiredate);
1341 break;
1345 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1346 (ulong)block->pkt->pkt.public_key->keyid[0],
1347 (ulong)block->pkt->pkt.public_key->keyid[1]);
1349 fprintf(spawn->tochild,"KEY %08lX%08lX BEGIN\n",
1350 (ulong)block->pkt->pkt.public_key->keyid[0],
1351 (ulong)block->pkt->pkt.public_key->keyid[1]);
1352 fwrite(iobuf_get_temp_buffer(buffer),
1353 iobuf_get_temp_length(buffer),1,spawn->tochild);
1354 fprintf(spawn->tochild,"KEY %08lX%08lX END\n",
1355 (ulong)block->pkt->pkt.public_key->keyid[0],
1356 (ulong)block->pkt->pkt.public_key->keyid[1]);
1358 iobuf_close(buffer);
1360 if(keyserver->host)
1361 log_info(_("sending key %s to %s server %s\n"),
1362 keystr(block->pkt->pkt.public_key->keyid),
1363 keyserver->scheme,keyserver->host);
1364 else
1365 log_info(_("sending key %s to %s\n"),
1366 keystr(block->pkt->pkt.public_key->keyid),
1367 keyserver->uri);
1369 release_kbnode(block);
1372 free_strlist(temp);
1375 break;
1378 case KS_SEARCH:
1380 strlist_t key;
1382 fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1384 /* Which keys do we want? Remember that the gpgkeys_ program
1385 is going to lump these together into a search string. */
1387 for(key=list;key!=NULL;key=key->next)
1389 fprintf(spawn->tochild,"%s\n",key->d);
1390 if(key!=list)
1392 searchstr=xrealloc(searchstr,
1393 strlen(searchstr)+strlen(key->d)+2);
1394 strcat(searchstr," ");
1396 else
1398 searchstr=xmalloc(strlen(key->d)+1);
1399 searchstr[0]='\0';
1402 strcat(searchstr,key->d);
1405 fprintf(spawn->tochild,"\n");
1407 if(keyserver->host)
1408 log_info(_("searching for \"%s\" from %s server %s\n"),
1409 searchstr,keyserver->scheme,keyserver->host);
1410 else
1411 log_info(_("searching for \"%s\" from %s\n"),
1412 searchstr,keyserver->uri);
1414 break;
1417 default:
1418 log_fatal(_("no keyserver action!\n"));
1419 break;
1422 /* Done sending, so start reading. */
1423 ret=exec_read(spawn);
1424 if(ret)
1425 goto fail;
1427 /* Now handle the response */
1429 for(;;)
1431 int plen;
1432 char *ptr;
1434 maxlen=1024;
1435 if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1437 ret = gpg_error_from_syserror ();
1438 goto fail; /* i.e. EOF */
1441 ptr=line;
1443 /* remove trailing whitespace */
1444 plen=strlen(ptr);
1445 while(plen>0 && ascii_isspace(ptr[plen-1]))
1446 plen--;
1447 plen[ptr]='\0';
1449 if(*ptr=='\0')
1450 break;
1452 if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1454 gotversion=1;
1456 if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1458 log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1459 KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1460 goto fail;
1463 else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1465 if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1466 log_info(_("WARNING: keyserver handler from a different"
1467 " version of GnuPG (%s)\n"),&ptr[8]);
1469 else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1470 outofband=1; /* Currently the only OPTION */
1473 if(!gotversion)
1475 log_error(_("keyserver did not send VERSION\n"));
1476 goto fail;
1479 if(!outofband)
1480 switch(action)
1482 case KS_GET:
1483 case KS_GETNAME:
1485 void *stats_handle;
1487 stats_handle=import_new_stats_handle();
1489 /* Slurp up all the key data. In the future, it might be
1490 nice to look for KEY foo OUTOFBAND and FAILED indicators.
1491 It's harmless to ignore them, but ignoring them does make
1492 gpg complain about "no valid OpenPGP data found". One
1493 way to do this could be to continue parsing this
1494 line-by-line and make a temp iobuf for each key. */
1496 import_keys_stream(spawn->fromchild,stats_handle,fpr,fpr_len,
1497 opt.keyserver_options.import_options);
1499 import_print_stats(stats_handle);
1500 import_release_stats_handle(stats_handle);
1502 break;
1505 /* Nothing to do here */
1506 case KS_SEND:
1507 break;
1509 case KS_SEARCH:
1510 keyserver_search_prompt(spawn->fromchild,searchstr);
1511 break;
1513 default:
1514 log_fatal(_("no keyserver action!\n"));
1515 break;
1518 fail:
1519 xfree(line);
1520 xfree(searchstr);
1523 *prog=exec_finish(spawn);
1525 return ret;
1528 static int
1529 keyserver_work(enum ks_action action,strlist_t list,KEYDB_SEARCH_DESC *desc,
1530 int count,unsigned char **fpr,size_t *fpr_len,
1531 struct keyserver_spec *keyserver)
1533 int rc=0,ret=0;
1535 if(!keyserver)
1537 log_error(_("no keyserver known (use option --keyserver)\n"));
1538 return G10ERR_BAD_URI;
1541 #ifdef DISABLE_KEYSERVER_HELPERS
1543 log_error(_("external keyserver calls are not supported in this build\n"));
1544 return G10ERR_KEYSERVER;
1546 #else
1547 /* Spawn a handler */
1549 rc=keyserver_spawn(action,list,desc,count,&ret,fpr,fpr_len,keyserver);
1550 if(ret)
1552 switch(ret)
1554 case KEYSERVER_SCHEME_NOT_FOUND:
1555 log_error(_("no handler for keyserver scheme `%s'\n"),
1556 keyserver->scheme);
1557 break;
1559 case KEYSERVER_NOT_SUPPORTED:
1560 log_error(_("action `%s' not supported with keyserver "
1561 "scheme `%s'\n"),
1562 action==KS_GET?"get":action==KS_SEND?"send":
1563 action==KS_SEARCH?"search":"unknown",
1564 keyserver->scheme);
1565 break;
1567 case KEYSERVER_VERSION_ERROR:
1568 log_error(_(GPGKEYS_PREFIX "%s does not support"
1569 " handler version %d\n"),
1570 keyserver_typemap(keyserver->scheme),
1571 KEYSERVER_PROTO_VERSION);
1572 break;
1574 case KEYSERVER_TIMEOUT:
1575 log_error(_("keyserver timed out\n"));
1576 break;
1578 case KEYSERVER_INTERNAL_ERROR:
1579 default:
1580 log_error(_("keyserver internal error\n"));
1581 break;
1584 return G10ERR_KEYSERVER;
1587 if(rc)
1589 log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1591 return rc;
1594 return 0;
1595 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1598 int
1599 keyserver_export(strlist_t users)
1601 strlist_t sl=NULL;
1602 KEYDB_SEARCH_DESC desc;
1603 int rc=0;
1605 /* Weed out descriptors that we don't support sending */
1606 for(;users;users=users->next)
1608 classify_user_id (users->d, &desc);
1609 if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1610 desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1611 desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1612 desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1614 log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1615 continue;
1617 else
1618 append_to_strlist(&sl,users->d);
1621 if(sl)
1623 rc=keyserver_work(KS_SEND,sl,NULL,0,NULL,NULL,opt.keyserver);
1624 free_strlist(sl);
1627 return rc;
1630 int
1631 keyserver_import(strlist_t users)
1633 KEYDB_SEARCH_DESC *desc;
1634 int num=100,count=0;
1635 int rc=0;
1637 /* Build a list of key ids */
1638 desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1640 for(;users;users=users->next)
1642 classify_user_id (users->d, &desc[count]);
1643 if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1644 desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1645 desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1646 desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1648 log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1649 continue;
1652 count++;
1653 if(count==num)
1655 num+=100;
1656 desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1660 if(count>0)
1661 rc=keyserver_work(KS_GET,NULL,desc,count,NULL,NULL,opt.keyserver);
1663 xfree(desc);
1665 return rc;
1669 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1670 struct keyserver_spec *keyserver)
1672 KEYDB_SEARCH_DESC desc;
1674 memset(&desc,0,sizeof(desc));
1676 if(fprint_len==16)
1677 desc.mode=KEYDB_SEARCH_MODE_FPR16;
1678 else if(fprint_len==20)
1679 desc.mode=KEYDB_SEARCH_MODE_FPR20;
1680 else
1681 return -1;
1683 memcpy(desc.u.fpr,fprint,fprint_len);
1685 /* TODO: Warn here if the fingerprint we got doesn't match the one
1686 we asked for? */
1687 return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1690 int
1691 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1693 KEYDB_SEARCH_DESC desc;
1695 memset(&desc,0,sizeof(desc));
1697 desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1698 desc.u.kid[0]=keyid[0];
1699 desc.u.kid[1]=keyid[1];
1701 return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1704 /* code mostly stolen from do_export_stream */
1705 static int
1706 keyidlist(strlist_t users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1708 int rc=0,ndesc,num=100;
1709 KBNODE keyblock=NULL,node;
1710 KEYDB_HANDLE kdbhd;
1711 KEYDB_SEARCH_DESC *desc;
1712 strlist_t sl;
1714 *count=0;
1716 *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1718 kdbhd=keydb_new(0);
1720 if(!users)
1722 ndesc = 1;
1723 desc = xmalloc_clear ( ndesc * sizeof *desc);
1724 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1726 else
1728 for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1730 desc = xmalloc ( ndesc * sizeof *desc);
1732 for (ndesc=0, sl=users; sl; sl = sl->next)
1734 if(classify_user_id (sl->d, desc+ndesc))
1735 ndesc++;
1736 else
1737 log_error (_("key \"%s\" not found: %s\n"),
1738 sl->d, g10_errstr (G10ERR_INV_USER_ID));
1742 while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1744 if (!users)
1745 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1747 /* read the keyblock */
1748 rc = keydb_get_keyblock (kdbhd, &keyblock );
1749 if( rc )
1751 log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1752 goto leave;
1755 if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1757 /* This is to work around a bug in some keyservers (pksd and
1758 OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1759 The answer is to refresh both the correct v4 keyid
1760 (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1761 This only happens for key refresh using the HKP scheme
1762 and if the refresh-add-fake-v3-keyids keyserver option is
1763 set. */
1764 if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1765 node->pkt->pkt.public_key->version>=4)
1767 (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1768 v3_keyid (node->pkt->pkt.public_key->pkey[0],
1769 (*klist)[*count].u.kid);
1770 (*count)++;
1772 if(*count==num)
1774 num+=100;
1775 *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1779 /* v4 keys get full fingerprints. v3 keys get long keyids.
1780 This is because it's easy to calculate any sort of keyid
1781 from a v4 fingerprint, but not a v3 fingerprint. */
1783 if(node->pkt->pkt.public_key->version<4)
1785 (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1786 keyid_from_pk(node->pkt->pkt.public_key,
1787 (*klist)[*count].u.kid);
1789 else
1791 size_t dummy;
1793 (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1794 fingerprint_from_pk(node->pkt->pkt.public_key,
1795 (*klist)[*count].u.fpr,&dummy);
1798 /* This is a little hackish, using the skipfncvalue as a
1799 void* pointer to the keyserver spec, but we don't need
1800 the skipfnc here, and it saves having an additional field
1801 for this (which would be wasted space most of the
1802 time). */
1804 (*klist)[*count].skipfncvalue=NULL;
1806 /* Are we honoring preferred keyservers? */
1807 if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1809 PKT_user_id *uid=NULL;
1810 PKT_signature *sig=NULL;
1812 merge_keys_and_selfsig(keyblock);
1814 for(node=node->next;node;node=node->next)
1816 if(node->pkt->pkttype==PKT_USER_ID
1817 && node->pkt->pkt.user_id->is_primary)
1818 uid=node->pkt->pkt.user_id;
1819 else if(node->pkt->pkttype==PKT_SIGNATURE
1820 && node->pkt->pkt.signature->
1821 flags.chosen_selfsig && uid)
1823 sig=node->pkt->pkt.signature;
1824 break;
1828 /* Try and parse the keyserver URL. If it doesn't work,
1829 then we end up writing NULL which indicates we are
1830 the same as any other key. */
1831 if(sig)
1832 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1835 (*count)++;
1837 if(*count==num)
1839 num+=100;
1840 *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1845 if(rc==-1)
1846 rc=0;
1848 leave:
1849 if(rc)
1850 xfree(*klist);
1851 xfree(desc);
1852 keydb_release(kdbhd);
1853 release_kbnode(keyblock);
1855 return rc;
1858 /* Note this is different than the original HKP refresh. It allows
1859 usernames to refresh only part of the keyring. */
1862 keyserver_refresh(strlist_t users)
1864 int rc,count,numdesc,fakev3=0;
1865 KEYDB_SEARCH_DESC *desc;
1866 unsigned int options=opt.keyserver_options.import_options;
1868 /* We switch merge-only on during a refresh, as 'refresh' should
1869 never import new keys, even if their keyids match. */
1870 opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY;
1872 /* Similarly, we switch on fast-import, since refresh may make
1873 multiple import sets (due to preferred keyserver URLs). We don't
1874 want each set to rebuild the trustdb. Instead we do it once at
1875 the end here. */
1876 opt.keyserver_options.import_options|=IMPORT_FAST;
1878 /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1879 scheme, then enable fake v3 keyid generation. */
1880 if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1881 && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1882 ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1883 fakev3=1;
1885 rc=keyidlist(users,&desc,&numdesc,fakev3);
1886 if(rc)
1887 return rc;
1889 count=numdesc;
1890 if(count>0)
1892 int i;
1894 /* Try to handle preferred keyserver keys first */
1895 for(i=0;i<numdesc;i++)
1897 if(desc[i].skipfncvalue)
1899 struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1901 /* We use the keyserver structure we parsed out before.
1902 Note that a preferred keyserver without a scheme://
1903 will be interpreted as hkp:// */
1905 rc=keyserver_work(KS_GET,NULL,&desc[i],1,NULL,NULL,keyserver);
1906 if(rc)
1907 log_info(_("WARNING: unable to refresh key %s"
1908 " via %s: %s\n"),keystr_from_desc(&desc[i]),
1909 keyserver->uri,g10_errstr(rc));
1910 else
1912 /* We got it, so mark it as NONE so we don't try and
1913 get it again from the regular keyserver. */
1915 desc[i].mode=KEYDB_SEARCH_MODE_NONE;
1916 count--;
1919 free_keyserver_spec(keyserver);
1924 if(count>0)
1926 if(opt.keyserver)
1928 if(count==1)
1929 log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
1930 else
1931 log_info(_("refreshing %d keys from %s\n"),
1932 count,opt.keyserver->uri);
1935 rc=keyserver_work(KS_GET,NULL,desc,numdesc,NULL,NULL,opt.keyserver);
1938 xfree(desc);
1940 opt.keyserver_options.import_options=options;
1942 /* If the original options didn't have fast import, and the trustdb
1943 is dirty, rebuild. */
1944 if(!(opt.keyserver_options.import_options&IMPORT_FAST))
1945 trustdb_check_or_update();
1947 return rc;
1951 keyserver_search(strlist_t tokens)
1953 if(tokens)
1954 return keyserver_work(KS_SEARCH,tokens,NULL,0,NULL,NULL,opt.keyserver);
1955 else
1956 return 0;
1960 keyserver_fetch(strlist_t urilist)
1962 KEYDB_SEARCH_DESC desc;
1963 strlist_t sl;
1964 unsigned int options=opt.keyserver_options.import_options;
1966 /* Switch on fast-import, since fetch can handle more than one
1967 import and we don't want each set to rebuild the trustdb.
1968 Instead we do it once at the end. */
1969 opt.keyserver_options.import_options|=IMPORT_FAST;
1971 /* A dummy desc since we're not actually fetching a particular key
1972 ID */
1973 memset(&desc,0,sizeof(desc));
1974 desc.mode=KEYDB_SEARCH_MODE_EXACT;
1976 for(sl=urilist;sl;sl=sl->next)
1978 struct keyserver_spec *spec;
1980 spec=parse_keyserver_uri(sl->d,1,NULL,0);
1981 if(spec)
1983 int rc;
1985 rc=keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,spec);
1986 if(rc)
1987 log_info (_("WARNING: unable to fetch URI %s: %s\n"),
1988 sl->d,g10_errstr(rc));
1990 free_keyserver_spec(spec);
1992 else
1993 log_info (_("WARNING: unable to parse URI %s\n"),sl->d);
1996 opt.keyserver_options.import_options=options;
1998 /* If the original options didn't have fast import, and the trustdb
1999 is dirty, rebuild. */
2000 if(!(opt.keyserver_options.import_options&IMPORT_FAST))
2001 trustdb_check_or_update();
2003 return 0;
2006 /* Import key in a CERT or pointed to by a CERT */
2008 keyserver_import_cert(const char *name,unsigned char **fpr,size_t *fpr_len)
2010 char *domain,*look,*url;
2011 IOBUF key;
2012 int type,rc=G10ERR_GENERAL;
2014 look=xstrdup(name);
2016 domain=strrchr(look,'@');
2017 if(domain)
2018 *domain='.';
2020 type=get_dns_cert(look,max_cert_size,&key,fpr,fpr_len,&url);
2021 if (!type || type == -1)
2023 /* There might be an error in res_query which leads to an error
2024 return (-1) in the case that nothing was found. Thus we take
2025 all errors as key not found. */
2026 rc = G10ERR_NO_PUBKEY;
2028 else if (type==1)
2030 int armor_status=opt.no_armor;
2032 /* CERTs are always in binary format */
2033 opt.no_armor=1;
2035 rc=import_keys_stream(key,NULL,fpr,fpr_len,
2036 opt.keyserver_options.import_options);
2038 opt.no_armor=armor_status;
2040 iobuf_close(key);
2042 else if(type==2 && *fpr)
2044 /* We only consider the IPGP type if a fingerprint was provided.
2045 This lets us select the right key regardless of what a URL
2046 points to, or get the key from a keyserver. */
2047 if(url)
2049 struct keyserver_spec *spec;
2051 spec=parse_keyserver_uri(url,1,NULL,0);
2052 if(spec)
2054 rc=keyserver_import_fprint(*fpr,*fpr_len,spec);
2055 free_keyserver_spec(spec);
2058 else if(opt.keyserver)
2060 /* If only a fingerprint is provided, try and fetch it from
2061 our --keyserver */
2063 rc=keyserver_import_fprint(*fpr,*fpr_len,opt.keyserver);
2065 else
2066 log_info(_("no keyserver known (use option --keyserver)\n"));
2068 /* Give a better string here? "CERT fingerprint for \"%s\"
2069 found, but no keyserver" " known (use option
2070 --keyserver)\n" ? */
2072 xfree(url);
2075 xfree(look);
2077 return rc;
2080 /* Import key pointed to by a PKA record. Return the requested
2081 fingerprint in fpr. */
2083 keyserver_import_pka(const char *name,unsigned char **fpr,size_t *fpr_len)
2085 char *uri;
2086 int rc = G10ERR_NO_PUBKEY;
2088 *fpr = xmalloc (20);
2089 *fpr_len = 20;
2091 uri = get_pka_info (name, *fpr);
2092 if (uri && *uri)
2094 /* An URI is available. Lookup the key. */
2095 struct keyserver_spec *spec;
2096 spec = parse_keyserver_uri (uri, 1, NULL, 0);
2097 if (spec)
2099 rc = keyserver_import_fprint (*fpr, 20, spec);
2100 free_keyserver_spec (spec);
2102 xfree (uri);
2105 if (rc)
2107 xfree(*fpr);
2108 *fpr = NULL;
2111 return rc;
2114 /* Import all keys that match name */
2116 keyserver_import_name(const char *name,unsigned char **fpr,size_t *fpr_len,
2117 struct keyserver_spec *keyserver)
2119 strlist_t list=NULL;
2120 int rc;
2122 append_to_strlist(&list,name);
2124 rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2126 free_strlist(list);
2128 return rc;
2131 /* Import a key by name using LDAP */
2133 keyserver_import_ldap(const char *name,unsigned char **fpr,size_t *fpr_len)
2135 char *domain;
2136 struct keyserver_spec *keyserver;
2137 strlist_t list=NULL;
2138 int rc,hostlen=1;
2139 #ifdef USE_DNS_SRV
2140 struct srventry *srvlist=NULL;
2141 int srvcount,i;
2142 char srvname[MAXDNAME];
2143 #endif
2145 /* Parse out the domain */
2146 domain=strrchr(name,'@');
2147 if(!domain)
2148 return G10ERR_GENERAL;
2150 domain++;
2152 keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
2153 keyserver->scheme=xstrdup("ldap");
2154 keyserver->host=xmalloc(1);
2155 keyserver->host[0]='\0';
2157 #ifdef USE_DNS_SRV
2158 snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain);
2160 srvcount=getsrv(srvname,&srvlist);
2162 for(i=0;i<srvcount;i++)
2164 hostlen+=strlen(srvlist[i].target)+1;
2165 keyserver->host=xrealloc(keyserver->host,hostlen);
2167 strcat(keyserver->host,srvlist[i].target);
2169 if(srvlist[i].port!=389)
2171 char port[7];
2173 hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */
2174 keyserver->host=xrealloc(keyserver->host,hostlen);
2176 snprintf(port,7,":%u",srvlist[i].port);
2177 strcat(keyserver->host,port);
2180 strcat(keyserver->host," ");
2183 free(srvlist);
2184 #endif
2186 /* If all else fails, do the PGP Universal trick of
2187 ldap://keys.(domain) */
2189 hostlen+=5+strlen(domain);
2190 keyserver->host=xrealloc(keyserver->host,hostlen);
2191 strcat(keyserver->host,"keys.");
2192 strcat(keyserver->host,domain);
2194 append_to_strlist(&list,name);
2196 rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2198 free_strlist(list);
2200 free_keyserver_spec(keyserver);
2202 return rc;