2005-04-11 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / keyserver.c
blob445c07620d247e7e838b3b1a7c84c038419e7689
1 /* keyserver.c - generic keyserver code
2 * Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
21 #include <config.h>
22 #include <ctype.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <assert.h>
28 #include "gpg.h"
29 #include "filter.h"
30 #include "keydb.h"
31 #include "status.h"
32 #include "exec.h"
33 #include "main.h"
34 #include "i18n.h"
35 #include "iobuf.h"
36 #include "memory.h"
37 #include "ttyio.h"
38 #include "options.h"
39 #include "packet.h"
40 #include "keyserver-internal.h"
41 #include "util.h"
43 #define GET 0
44 #define SEND 1
45 #define SEARCH 2
47 struct keyrec
49 KEYDB_SEARCH_DESC desc;
50 time_t createtime,expiretime;
51 int size,flags;
52 byte type;
53 iobuf_t uidbuf;
54 int lines;
57 struct kopts
59 char *name;
60 int tell; /* tell remote process about this one */
61 int *flag;
62 } keyserver_opts[]=
64 {"include-revoked",1,&opt.keyserver_options.include_revoked},
65 {"include-disabled",1,&opt.keyserver_options.include_disabled},
66 {"include-subkeys",1,&opt.keyserver_options.include_subkeys},
67 {"keep-temp-files",0,&opt.keyserver_options.keep_temp_files},
68 {"honor-http-proxy",1,&opt.keyserver_options.honor_http_proxy},
69 {"broken-http-proxy",1,&opt.keyserver_options.broken_http_proxy},
70 {"refresh-add-fake-v3-keyids",0,&opt.keyserver_options.fake_v3_keyids},
71 {"auto-key-retrieve",0,&opt.keyserver_options.auto_key_retrieve},
72 {"try-dns-srv",1,&opt.keyserver_options.try_dns_srv},
73 {NULL}
76 static int keyserver_work(int action,STRLIST list,
77 KEYDB_SEARCH_DESC *desc,int count);
79 void
80 parse_keyserver_options(char *options)
82 char *tok;
84 while((tok=strsep(&options," ,")))
86 int i,hit=0;
88 if(tok[0]=='\0')
89 continue;
91 for(i=0;keyserver_opts[i].name;i++)
93 if(ascii_strcasecmp(tok,keyserver_opts[i].name)==0)
95 *(keyserver_opts[i].flag)=1;
96 hit=1;
97 break;
99 else if(ascii_strncasecmp("no-",tok,3)==0 &&
100 ascii_strcasecmp(&tok[3],keyserver_opts[i].name)==0)
102 *(keyserver_opts[i].flag)=0;
103 hit=1;
104 break;
108 /* These options need more than just a flag */
109 if(!hit)
111 if(ascii_strcasecmp(tok,"verbose")==0)
112 opt.keyserver_options.verbose++;
113 else if(ascii_strcasecmp(tok,"no-verbose")==0)
114 opt.keyserver_options.verbose--;
115 #ifdef EXEC_TEMPFILE_ONLY
116 else if(ascii_strcasecmp(tok,"use-temp-files")==0 ||
117 ascii_strcasecmp(tok,"no-use-temp-files")==0)
118 log_info(_("WARNING: keyserver option \"%s\" is not used "
119 "on this platform\n"),tok);
120 #else
121 else if(ascii_strcasecmp(tok,"use-temp-files")==0)
122 opt.keyserver_options.use_temp_files=1;
123 else if(ascii_strcasecmp(tok,"no-use-temp-files")==0)
124 opt.keyserver_options.use_temp_files=0;
125 #endif
126 else
127 if(!parse_import_options(tok,
128 &opt.keyserver_options.import_options) &&
129 !parse_export_options(tok,
130 &opt.keyserver_options.export_options))
131 add_to_strlist(&opt.keyserver_options.other,tok);
136 int
137 parse_keyserver_uri(char *uri,const char *configname,unsigned int configlineno)
139 int assume_hkp=0;
141 assert(uri!=NULL);
143 opt.keyserver_host=NULL;
144 opt.keyserver_port=NULL;
145 opt.keyserver_opaque=NULL;
147 /* Get the scheme */
149 opt.keyserver_scheme=strsep(&uri,":");
150 if(uri==NULL)
152 /* Assume HKP if there is no scheme */
153 assume_hkp=1;
154 uri=opt.keyserver_scheme;
155 opt.keyserver_scheme="hkp";
157 else
159 /* Force to lowercase */
160 char *i;
162 for(i=opt.keyserver_scheme;*i!='\0';i++)
163 *i=ascii_tolower(*i);
166 if(ascii_strcasecmp(opt.keyserver_scheme,"x-broken-hkp")==0)
168 deprecated_warning(configname,configlineno,"x-broken-hkp",
169 "--keyserver-options ","broken-http-proxy");
170 opt.keyserver_scheme="hkp";
171 opt.keyserver_options.broken_http_proxy=1;
173 else if(ascii_strcasecmp(opt.keyserver_scheme,"x-hkp")==0
174 || ascii_strcasecmp(opt.keyserver_scheme,"http")==0)
176 /* Canonicalize this to "hkp" so it works with both the internal
177 and external keyserver interface. */
178 opt.keyserver_scheme="hkp";
181 if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
183 /* Two slashes means network path. */
185 /* Skip over the "//", if any */
186 if(!assume_hkp)
187 uri+=2;
189 /* Get the host */
190 opt.keyserver_host=strsep(&uri,":/");
191 if(opt.keyserver_host[0]=='\0')
192 return GPG_ERR_BAD_URI;
194 if(uri==NULL || uri[0]=='\0')
195 opt.keyserver_port=NULL;
196 else
198 char *ch;
200 /* Get the port */
201 opt.keyserver_port=strsep(&uri,"/");
203 /* Ports are digits only */
204 ch=opt.keyserver_port;
205 while(*ch!='\0')
207 if(!digitp(ch))
208 return GPG_ERR_BAD_URI;
210 ch++;
213 /* It would seem to be reasonable to limit the range of the
214 ports to values between 1-65535, but RFC 1738 and 1808
215 imply there is no limit. Of course, the real world has
216 limits. */
219 /* (any path part of the URI is discarded for now as no keyserver
220 uses it yet) */
222 else if(uri[0]!='/')
224 /* No slash means opaque. Just record the opaque blob and get
225 out. */
226 opt.keyserver_opaque=uri;
227 return 0;
229 else
231 /* One slash means absolute path. We don't need to support that
232 yet. */
233 return GPG_ERR_BAD_URI;
236 if(opt.keyserver_scheme[0]=='\0')
237 return GPG_ERR_BAD_URI;
239 return 0;
242 static void
243 print_keyrec(int number,struct keyrec *keyrec)
245 int i;
247 iobuf_writebyte(keyrec->uidbuf,0);
248 iobuf_flush_temp(keyrec->uidbuf);
249 printf("(%d)\t%s ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
251 if(keyrec->size>0)
252 printf("%d bit ",keyrec->size);
254 if(keyrec->type)
256 const char *str = gcry_pk_algo_name (keyrec->type);
258 if(str)
259 printf("%s ",str);
260 else
261 printf("unknown ");
264 switch(keyrec->desc.mode)
266 case KEYDB_SEARCH_MODE_SHORT_KID:
267 printf("key %08lX",(ulong)keyrec->desc.u.kid[1]);
268 break;
270 case KEYDB_SEARCH_MODE_LONG_KID:
271 printf("key %08lX%08lX",(ulong)keyrec->desc.u.kid[0],
272 (ulong)keyrec->desc.u.kid[1]);
273 break;
275 case KEYDB_SEARCH_MODE_FPR16:
276 printf("key ");
277 for(i=0;i<16;i++)
278 printf("%02X",(unsigned char)keyrec->desc.u.fpr[i]);
279 break;
281 case KEYDB_SEARCH_MODE_FPR20:
282 printf("key ");
283 for(i=0;i<20;i++)
284 printf("%02X",(unsigned char)keyrec->desc.u.fpr[i]);
285 break;
287 default:
288 BUG();
289 break;
292 if(keyrec->createtime>0)
293 printf(", created %s",strtimestamp(keyrec->createtime));
295 if(keyrec->expiretime>0)
296 printf(", expires %s",strtimestamp(keyrec->expiretime));
298 if(keyrec->flags&1)
299 printf(" (%s)",("revoked"));
300 if(keyrec->flags&2)
301 printf(" (%s)",("disabled"));
302 if(keyrec->flags&4)
303 printf(" (%s)",("expired"));
305 printf("\n");
308 /* Returns a keyrec (which must be freed) once a key is complete, and
309 NULL otherwise. Call with a NULL keystring once key parsing is
310 complete to return any unfinished keys. */
311 static struct keyrec *
312 parse_keyrec(char *keystring)
314 static struct keyrec *work=NULL;
315 struct keyrec *ret=NULL;
316 char *record;
317 int i;
319 if(keystring==NULL)
321 if(work==NULL)
322 return NULL;
323 else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
325 xfree (work);
326 return NULL;
328 else
330 ret=work;
331 work=NULL;
332 return ret;
336 if(work==NULL)
338 work=xcalloc (1,sizeof(struct keyrec));
339 work->uidbuf=iobuf_temp();
342 /* Remove trailing whitespace */
343 for(i=strlen(keystring);i>0;i--)
344 if(ascii_isspace(keystring[i-1]))
345 keystring[i-1]='\0';
346 else
347 break;
349 if((record=strsep(&keystring,":"))==NULL)
350 return ret;
352 if(ascii_strcasecmp("pub",record)==0)
354 char *tok;
356 if(work->desc.mode)
358 ret=work;
359 work=xcalloc (1,sizeof(struct keyrec));
360 work->uidbuf=iobuf_temp();
363 if((tok=strsep(&keystring,":"))==NULL)
364 return ret;
366 classify_user_id(tok,&work->desc);
367 if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
368 && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
369 && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
370 && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
372 work->desc.mode=KEYDB_SEARCH_MODE_NONE;
373 return ret;
376 /* Note all items after this are optional. This allows us to
377 have a pub line as simple as pub:keyid and nothing else. */
379 work->lines++;
381 if((tok=strsep(&keystring,":"))==NULL)
382 return ret;
384 work->type=atoi(tok);
386 if((tok=strsep(&keystring,":"))==NULL)
387 return ret;
389 work->size=atoi(tok);
391 if((tok=strsep(&keystring,":"))==NULL)
392 return ret;
394 work->createtime=atoi(tok);
396 if((tok=strsep(&keystring,":"))==NULL)
397 return ret;
399 work->expiretime=atoi(tok);
401 if((tok=strsep(&keystring,":"))==NULL)
402 return ret;
404 while(*tok)
405 switch(*tok++)
407 case 'r':
408 case 'R':
409 work->flags|=1;
410 break;
412 case 'd':
413 case 'D':
414 work->flags|=2;
415 break;
417 case 'e':
418 case 'E':
419 work->flags|=4;
420 break;
423 if(work->expiretime && work->expiretime<=make_timestamp())
424 work->flags|=4;
426 else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
428 char *userid,*tok,*decoded;
430 if((tok=strsep(&keystring,":"))==NULL)
431 return ret;
433 if(strlen(tok)==0)
434 return ret;
436 userid=tok;
438 /* By definition, de-%-encoding is always smaller than the
439 original string so we can decode in place. */
441 i=0;
443 while(*tok)
444 if(tok[0]=='%' && tok[1] && tok[2])
446 if((userid[i]=hextobyte(&tok[1]))==-1)
447 userid[i]='?';
449 i++;
450 tok+=3;
452 else
453 userid[i++]=*tok++;
455 /* We don't care about the other info provided in the uid: line
456 since no keyserver supports marking userids with timestamps
457 or revoked/expired/disabled yet. */
459 /* No need to check for control characters, as utf8_to_native
460 does this for us. */
462 decoded=utf8_to_native(userid,i,0);
463 iobuf_writestr(work->uidbuf,decoded);
464 xfree (decoded);
465 iobuf_writestr(work->uidbuf,"\n\t");
466 work->lines++;
469 /* Ignore any records other than "pri" and "uid" for easy future
470 growth. */
472 return ret;
475 /* TODO: do this as a list sent to keyserver_work rather than calling
476 it once for each key to get the correct counts after the import
477 (cosmetics, really) and to better take advantage of the keyservers
478 that can do multiple fetches in one go (LDAP). */
479 static int
480 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
482 char *answer;
484 if(count && opt.command_fd==-1)
486 static int from=1;
487 tty_printf("Keys %d-%d of %d for \"%s\". ",from,numdesc,count,search);
488 from=numdesc+1;
491 answer=cpr_get_no_help("keysearch.prompt",
492 _("Enter number(s), N)ext, or Q)uit > "));
493 /* control-d */
494 if(answer[0]=='\x04')
496 printf("Q\n");
497 answer[0]='q';
500 if(answer[0]=='q' || answer[0]=='Q')
502 xfree (answer);
503 return 1;
505 else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
507 char *split=answer,*num;
509 while((num=strsep(&split," ,"))!=NULL)
510 if(atoi(num)>=1 && atoi(num)<=numdesc)
511 keyserver_work(GET,NULL,&desc[atoi(num)-1],1);
513 xfree (answer);
514 return 1;
517 return 0;
520 /* Count and searchstr are just for cosmetics. If the count is too
521 small, it will grow safely. If negative it disables the "Key x-y
522 of z" messages. */
523 static void
524 keyserver_search_prompt(iobuf_t buffer,const char *searchstr)
526 int i=0,validcount=0,started=0,header=0,count=1;
527 unsigned int maxlen,buflen;
528 KEYDB_SEARCH_DESC *desc;
529 byte *line=NULL;
530 /* TODO: Something other than 23? That's 24-1 (the prompt). */
531 int maxlines=23,numlines=0;
533 desc=xmalloc (count*sizeof(KEYDB_SEARCH_DESC));
535 for(;;)
537 struct keyrec *keyrec;
538 int rl;
540 maxlen=1024;
541 rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
543 if(opt.with_colons)
545 if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
546 && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
548 header=1;
549 continue;
551 else if(ascii_strncasecmp("SEARCH ",line,7)==0
552 && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
553 continue;
555 printf("%s",line);
558 /* Look for an info: line. The only current info: values
559 defined are the version and key count. */
560 if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
562 char *tok,*str=&line[5];
564 if((tok=strsep(&str,":"))!=NULL)
566 int version;
568 if(sscanf(tok,"%d",&version)!=1)
569 version=1;
571 if(version!=1)
573 log_error(_("invalid keyserver protocol "
574 "(us %d!=handler %d)\n"),1,version);
575 break;
579 if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
581 if(count==0)
582 goto notfound;
583 else if(count<0)
584 count=10;
585 else
586 validcount=1;
588 desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
591 started=1;
592 continue;
595 if(rl==0)
597 keyrec=parse_keyrec(NULL);
599 if(keyrec==NULL)
601 if(i==0)
603 count=0;
604 break;
607 if(i!=count)
608 validcount=0;
610 for(;;)
612 if(show_prompt(desc,i,validcount?count:0,searchstr))
613 break;
614 validcount=0;
617 break;
620 else
621 keyrec=parse_keyrec(line);
623 if(i==count)
625 /* keyserver helper sent more keys than they claimed in the
626 info: line. */
627 count+=10;
628 desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
629 validcount=0;
632 if(keyrec)
634 desc[i]=keyrec->desc;
636 if(!opt.with_colons)
638 if(numlines+keyrec->lines>maxlines)
640 if(show_prompt(desc,i,validcount?count:0,searchstr))
641 break;
642 else
643 numlines=0;
646 print_keyrec(i+1,keyrec);
649 numlines+=keyrec->lines;
650 iobuf_close(keyrec->uidbuf);
651 xfree (keyrec);
653 started=1;
654 i++;
658 xfree (desc);
659 xfree (line);
661 notfound:
662 if(count==0)
664 if(searchstr)
665 log_info(_("key \"%s\" not found on keyserver\n"),searchstr);
666 else
667 log_info(_("key not found on keyserver\n"));
668 return;
672 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
673 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
675 static int
676 keyserver_spawn(int action,STRLIST list,
677 KEYDB_SEARCH_DESC *desc,int count,int *prog)
679 int ret=0,i,gotversion=0,outofband=0;
680 STRLIST temp;
681 unsigned int maxlen,buflen;
682 char *command=NULL,*searchstr=NULL;
683 byte *line=NULL;
684 struct kopts *kopts;
685 struct exec_info *spawn;
687 #ifdef EXEC_TEMPFILE_ONLY
688 opt.keyserver_options.use_temp_files=1;
689 #endif
691 /* Push the libexecdir into path. If DISABLE_KEYSERVER_PATH is set,
692 use the 0 arg to replace the path. */
693 #ifdef DISABLE_KEYSERVER_PATH
694 set_exec_path(GNUPG_LIBEXECDIR,0);
695 #else
696 set_exec_path(GNUPG_LIBEXECDIR,opt.exec_path_set);
697 #endif
699 /* Build the filename for the helper to execute */
700 command=xmalloc (strlen("gpgkeys_")+strlen(opt.keyserver_scheme)+1);
701 strcpy(command,"gpgkeys_");
702 strcat(command,opt.keyserver_scheme);
704 if(opt.keyserver_options.use_temp_files)
706 if(opt.keyserver_options.keep_temp_files)
708 command=xrealloc(command,strlen(command)+
709 strlen(KEYSERVER_ARGS_KEEP)+1);
710 strcat(command,KEYSERVER_ARGS_KEEP);
712 else
714 command=xrealloc(command,strlen(command)+
715 strlen(KEYSERVER_ARGS_NOKEEP)+1);
716 strcat(command,KEYSERVER_ARGS_NOKEEP);
719 ret=exec_write(&spawn,NULL,command,NULL,0,0);
721 else
722 ret=exec_write(&spawn,command,NULL,NULL,0,0);
724 if(ret)
725 return ret;
727 fprintf(spawn->tochild,"# This is a gpg keyserver communications file\n");
728 fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
729 fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
731 if(opt.keyserver_opaque)
732 fprintf(spawn->tochild,"OPAQUE %s\n",opt.keyserver_opaque);
733 else
735 if(opt.keyserver_host)
736 fprintf(spawn->tochild,"HOST %s\n",opt.keyserver_host);
738 if(opt.keyserver_port)
739 fprintf(spawn->tochild,"PORT %s\n",opt.keyserver_port);
742 /* Write options */
744 for(i=0,kopts=keyserver_opts;kopts[i].name;i++)
745 if(*(kopts[i].flag) && kopts[i].tell)
746 fprintf(spawn->tochild,"OPTION %s\n",kopts[i].name);
748 for(i=0;i<opt.keyserver_options.verbose;i++)
749 fprintf(spawn->tochild,"OPTION verbose\n");
751 temp=opt.keyserver_options.other;
753 for(;temp;temp=temp->next)
754 fprintf(spawn->tochild,"OPTION %s\n",temp->d);
756 switch(action)
758 case GET:
760 fprintf(spawn->tochild,"COMMAND GET\n\n");
762 /* Which keys do we want? */
764 for(i=0;i<count;i++)
766 if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
768 int f;
770 fprintf(spawn->tochild,"0x");
772 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
773 fprintf(spawn->tochild,"%02X",(byte)desc[i].u.fpr[f]);
775 fprintf(spawn->tochild,"\n");
777 else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
779 int f;
781 fprintf(spawn->tochild,"0x");
783 for(f=0;f<16;f++)
784 fprintf(spawn->tochild,"%02X",(byte)desc[i].u.fpr[f]);
786 fprintf(spawn->tochild,"\n");
788 else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
789 fprintf(spawn->tochild,"0x%08lX%08lX\n",
790 (ulong)desc[i].u.kid[0],
791 (ulong)desc[i].u.kid[1]);
792 else
793 fprintf(spawn->tochild,"0x%08lX\n",
794 (ulong)desc[i].u.kid[1]);
797 fprintf(spawn->tochild,"\n");
799 break;
802 case SEND:
804 STRLIST key;
806 /* Note the extra \n here to send an empty keylist block */
807 fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
809 for(key=list;key!=NULL;key=key->next)
811 armor_filter_context_t afx;
812 iobuf_t buffer=iobuf_temp();
813 KBNODE block;
815 temp=NULL;
816 add_to_strlist(&temp,key->d);
818 memset(&afx,0,sizeof(afx));
819 afx.what=1;
820 iobuf_push_filter(buffer,armor_filter,&afx);
822 /* TODO: Don't use the keyblock hack here - instead,
823 output each key as a different ascii armored blob with
824 its own INFO section. */
826 if(export_pubkeys_stream(buffer,temp,&block,
827 opt.keyserver_options.export_options)==-1)
828 iobuf_close(buffer);
829 else
831 KBNODE node;
833 iobuf_flush_temp(buffer);
835 merge_keys_and_selfsig(block);
837 fprintf(spawn->tochild,"INFO %s BEGIN\n",key->d);
839 for(node=block;node;node=node->next)
841 switch(node->pkt->pkttype)
843 default:
844 continue;
846 case PKT_PUBLIC_KEY:
847 case PKT_PUBLIC_SUBKEY:
849 PKT_public_key *pk=node->pkt->pkt.public_key;
851 keyid_from_pk(pk,NULL);
853 fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
854 node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
855 (ulong)pk->keyid[0],(ulong)pk->keyid[1],
856 pk->pubkey_algo,
857 nbits_from_pk(pk),
858 pk->timestamp,
859 pk->expiredate);
861 if(pk->is_revoked)
862 fprintf(spawn->tochild,"r");
863 if(pk->has_expired)
864 fprintf(spawn->tochild,"e");
866 fprintf(spawn->tochild,"\n");
868 break;
871 case PKT_USER_ID:
873 PKT_user_id *uid=node->pkt->pkt.user_id;
874 int r;
876 if(uid->attrib_data)
877 continue;
879 fprintf(spawn->tochild,"uid:");
881 /* Quote ':', '%', and any 8-bit
882 characters */
883 for(r=0;r<uid->len;r++)
885 if(uid->name[r]==':' || uid->name[r]=='%'
886 || uid->name[r]&0x80)
887 fprintf(spawn->tochild,"%%%02X",uid->name[r]);
888 else
889 fprintf(spawn->tochild,"%c",uid->name[r]);
892 fprintf(spawn->tochild,":%u:%u:",
893 uid->created,uid->expiredate);
895 if(uid->is_revoked)
896 fprintf(spawn->tochild,"r");
897 if(uid->is_expired)
898 fprintf(spawn->tochild,"e");
900 fprintf(spawn->tochild,"\n");
905 fprintf(spawn->tochild,"INFO %s END\n",key->d);
907 fprintf(spawn->tochild,"KEY %s BEGIN\n",key->d);
908 fwrite(iobuf_get_temp_buffer(buffer),
909 iobuf_get_temp_length(buffer),1,spawn->tochild);
910 fprintf(spawn->tochild,"KEY %s END\n",key->d);
912 iobuf_close(buffer);
913 release_kbnode(block);
916 free_strlist(temp);
919 break;
922 case SEARCH:
924 STRLIST key;
926 fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
928 /* Which keys do we want? Remember that the gpgkeys_ program
929 is going to lump these together into a search string. */
931 for(key=list;key!=NULL;key=key->next)
933 fprintf(spawn->tochild,"%s\n",key->d);
934 if(key!=list)
936 searchstr=xrealloc(searchstr,
937 strlen(searchstr)+strlen(key->d)+2);
938 strcat(searchstr," ");
940 else
942 searchstr=xmalloc (strlen(key->d)+1);
943 searchstr[0]='\0';
946 strcat(searchstr,key->d);
949 fprintf(spawn->tochild,"\n");
951 break;
954 default:
955 log_fatal(_("no keyserver action!\n"));
956 break;
959 /* Done sending, so start reading. */
960 ret=exec_read(spawn);
961 if(ret)
962 goto fail;
964 /* Now handle the response */
966 for(;;)
968 int plen;
969 char *ptr;
971 maxlen=1024;
972 if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
974 ret = iobuf_error (spawn->fromchild);
975 goto fail; /* i.e. EOF */
978 ptr=line;
980 /* remove trailing whitespace */
981 plen=strlen(ptr);
982 while(plen>0 && ascii_isspace(ptr[plen-1]))
983 plen--;
984 plen[ptr]='\0';
986 if(*ptr=='\0')
987 break;
989 if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
991 gotversion=1;
993 if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
995 log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
996 KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
997 goto fail;
1000 else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1002 if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1003 log_info(_("WARNING: keyserver handler from a different "
1004 "version of GnuPG (%s)\n"),&ptr[8]);
1006 else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1007 outofband=1; /* Currently the only OPTION */
1010 if(!gotversion)
1012 log_error(_("keyserver did not send VERSION\n"));
1013 goto fail;
1016 if(!outofband)
1017 switch(action)
1019 case GET:
1021 void *stats_handle;
1023 stats_handle=import_new_stats_handle();
1025 /* Slurp up all the key data. In the future, it might be
1026 nice to look for KEY foo OUTOFBAND and FAILED indicators.
1027 It's harmless to ignore them, but ignoring them does make
1028 gpg complain about "no valid OpenPGP data found". One
1029 way to do this could be to continue parsing this
1030 line-by-line and make a temp iobuf for each key. */
1032 import_keys_stream(spawn->fromchild,stats_handle,
1033 opt.keyserver_options.import_options);
1035 import_print_stats(stats_handle);
1036 import_release_stats_handle(stats_handle);
1038 break;
1041 /* Nothing to do here */
1042 case SEND:
1043 break;
1045 case SEARCH:
1047 keyserver_search_prompt(spawn->fromchild,searchstr);
1049 break;
1052 default:
1053 log_fatal(_("no keyserver action!\n"));
1054 break;
1057 fail:
1058 xfree (line);
1060 *prog=exec_finish(spawn);
1062 return ret;
1065 static int
1066 keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,int count)
1068 int rc=0,ret=0;
1070 if(opt.keyserver_scheme==NULL)
1072 log_error(_("no keyserver known (use option --keyserver)\n"));
1073 return GPG_ERR_BAD_URI;
1076 #ifdef DISABLE_KEYSERVER_HELPERS
1078 log_error(_("external keyserver calls are not supported in this build\n"));
1079 return GPG_ERR_KEYSERVER;
1081 #else
1082 /* Spawn a handler */
1084 rc=keyserver_spawn(action,list,desc,count,&ret);
1085 if(ret)
1087 switch(ret)
1089 case KEYSERVER_SCHEME_NOT_FOUND:
1090 log_error(_("no handler for keyserver scheme \"%s\"\n"),
1091 opt.keyserver_scheme);
1092 break;
1094 case KEYSERVER_NOT_SUPPORTED:
1095 log_error(_("action \"%s\" not supported with keyserver "
1096 "scheme \"%s\"\n"),
1097 action==GET?"get":action==SEND?"send":
1098 action==SEARCH?"search":"unknown",
1099 opt.keyserver_scheme);
1100 break;
1102 case KEYSERVER_VERSION_ERROR:
1103 log_error(_("gpgkeys_%s does not support handler version %d\n"),
1104 opt.keyserver_scheme,KEYSERVER_PROTO_VERSION);
1105 break;
1107 case KEYSERVER_INTERNAL_ERROR:
1108 default:
1109 log_error(_("keyserver internal error\n"));
1110 break;
1113 return GPG_ERR_KEYSERVER;
1116 if(rc)
1118 log_error(_("keyserver communications error: %s\n"),gpg_strerror (rc));
1120 return rc;
1123 return 0;
1124 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1127 int
1128 keyserver_export(STRLIST users)
1130 /* We better ask for confirmation when the user entered --send-keys
1131 without arguments. Sending all keys might not be the thing he
1132 intended to do */
1133 if (users || opt.batch || opt.answer_yes)
1135 else if ( !cpr_get_answer_is_yes
1136 ("keyserver_export.send_all",
1137 _("Do you really want to send all your "
1138 "public keys to the keyserver? (y/N) ")))
1139 return -1;
1141 return keyserver_work(SEND,users,NULL,0);
1144 int
1145 keyserver_import(STRLIST users)
1147 KEYDB_SEARCH_DESC *desc;
1148 int num=100,count=0;
1149 int rc=0;
1151 /* Build a list of key ids */
1152 desc=xmalloc (sizeof(KEYDB_SEARCH_DESC)*num);
1154 for(;users;users=users->next)
1156 classify_user_id (users->d, &desc[count]);
1157 if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1158 desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1159 desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1160 desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1162 log_error(_("skipping invalid key ID \"%s\"\n"),users->d);
1163 continue;
1166 count++;
1167 if(count==num)
1169 num+=100;
1170 desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1174 if(count>0)
1175 rc=keyserver_work(GET,NULL,desc,count);
1177 xfree (desc);
1179 return rc;
1183 keyserver_import_fprint(const byte *fprint,size_t fprint_len)
1185 KEYDB_SEARCH_DESC desc;
1187 memset(&desc,0,sizeof(desc));
1189 if(fprint_len==16)
1190 desc.mode=KEYDB_SEARCH_MODE_FPR16;
1191 else if(fprint_len==20)
1192 desc.mode=KEYDB_SEARCH_MODE_FPR20;
1193 else
1194 return -1;
1196 memcpy(desc.u.fpr,fprint,fprint_len);
1198 return keyserver_work(GET,NULL,&desc,1);
1201 int
1202 keyserver_import_keyid(u32 *keyid)
1204 KEYDB_SEARCH_DESC desc;
1206 memset(&desc,0,sizeof(desc));
1208 desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1209 desc.u.kid[0]=keyid[0];
1210 desc.u.kid[1]=keyid[1];
1212 return keyserver_work(GET,NULL,&desc,1);
1215 /* code mostly stolen from do_export_stream */
1216 static int
1217 keyidlist(STRLIST users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1219 int rc=0,ndesc,num=100;
1220 KBNODE keyblock=NULL,node;
1221 KEYDB_HANDLE kdbhd;
1222 KEYDB_SEARCH_DESC *desc;
1223 STRLIST sl;
1225 *count=0;
1227 *klist=xmalloc (sizeof(KEYDB_SEARCH_DESC)*num);
1229 kdbhd=keydb_new(0);
1231 if(!users)
1233 ndesc = 1;
1234 desc = xcalloc (1, ndesc * sizeof *desc);
1235 desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1237 else
1239 for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1241 desc = xmalloc ( ndesc * sizeof *desc);
1243 for (ndesc=0, sl=users; sl; sl = sl->next)
1245 if(classify_user_id (sl->d, desc+ndesc))
1246 ndesc++;
1247 else
1248 log_error (_("key `%s' not found: %s\n"),
1249 sl->d, gpg_strerror (GPG_ERR_INV_USER_ID));
1253 while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1255 if (!users)
1256 desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1258 /* read the keyblock */
1259 rc = keydb_get_keyblock (kdbhd, &keyblock );
1260 if( rc )
1262 log_error (_("error reading keyblock: %s\n"), gpg_strerror (rc) );
1263 goto leave;
1266 if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1268 /* This is to work around a bug in some keyservers (pksd and
1269 OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1270 The answer is to refresh both the correct v4 keyid
1271 (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1272 This only happens for key refresh using the HKP scheme
1273 and if the refresh-add-fake-v3-keyids keyserver option is
1274 set. */
1275 if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1276 node->pkt->pkt.public_key->version>=4)
1278 (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1279 v3_keyid (node->pkt->pkt.public_key->pkey[0],
1280 (*klist)[*count].u.kid);
1281 (*count)++;
1283 if(*count==num)
1285 num+=100;
1286 *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1290 /* v4 keys get full fingerprints. v3 keys get long keyids.
1291 This is because it's easy to calculate any sort of key id
1292 from a v4 fingerprint, but not a v3 fingerprint. */
1294 if(node->pkt->pkt.public_key->version<4)
1296 (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1297 keyid_from_pk(node->pkt->pkt.public_key,
1298 (*klist)[*count].u.kid);
1300 else
1302 size_t dummy;
1304 (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1305 fingerprint_from_pk(node->pkt->pkt.public_key,
1306 (*klist)[*count].u.fpr,&dummy);
1309 (*count)++;
1311 if(*count==num)
1313 num+=100;
1314 *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1319 if(rc==-1)
1320 rc=0;
1322 leave:
1323 xfree (desc);
1324 keydb_release(kdbhd);
1325 release_kbnode(keyblock);
1327 return rc;
1330 /* Note this is different than the original HKP refresh. It allows
1331 usernames to refresh only part of the keyring. */
1333 int
1334 keyserver_refresh(STRLIST users)
1336 int rc,count,fakev3=0;
1337 KEYDB_SEARCH_DESC *desc;
1339 /* We switch merge_only on during a refresh, as 'refresh' should
1340 never import new keys, even if their keyids match. Is it worth
1341 preserving the old merge_only value here? */
1342 opt.merge_only=1;
1344 /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1345 scheme, then enable fake v3 keyid generation. */
1346 if(opt.keyserver_options.fake_v3_keyids && opt.keyserver_scheme &&
1347 (ascii_strcasecmp(opt.keyserver_scheme,"hkp")==0 ||
1348 ascii_strcasecmp(opt.keyserver_scheme,"mailto")==0))
1349 fakev3=1;
1351 rc=keyidlist(users,&desc,&count,fakev3);
1352 if(rc)
1353 return rc;
1355 if(count>0)
1357 if(opt.keyserver_uri)
1359 if(count==1)
1360 log_info(_("refreshing 1 key from %s\n"),opt.keyserver_uri);
1361 else
1362 log_info(_("refreshing %d keys from %s\n"),
1363 count,opt.keyserver_uri);
1366 rc=keyserver_work(GET,NULL,desc,count);
1369 xfree (desc);
1371 return rc;
1375 keyserver_search(STRLIST tokens)
1377 if(tokens)
1378 return keyserver_work(SEARCH,tokens,NULL,0);
1379 else
1380 return 0;