163d3bae090c70c5d8eca51bf34ab9ec5df89d52
[gnupg.git] / g10 / keyserver.c
1 /* keyserver.c - generic keyserver code
2  * Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
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.
10  *
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.
15  *
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
19  */
20
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 "filter.h"
28 #include "keydb.h"
29 #include "status.h"
30 #include "exec.h"
31 #include "main.h"
32 #include "i18n.h"
33 #include "iobuf.h"
34 #include "memory.h"
35 #include "ttyio.h"
36 #include "options.h"
37 #include "packet.h"
38 #include "keyserver-internal.h"
39 #include "util.h"
40
41 #define GET    0
42 #define SEND   1
43 #define SEARCH 2
44
45 struct keyrec
46 {
47   KEYDB_SEARCH_DESC desc;
48   time_t createtime,expiretime;
49   int size,flags;
50   byte type;
51   IOBUF uidbuf;
52   int lines;
53 };
54
55 struct kopts
56 {
57   char *name;
58   int tell; /* tell remote process about this one */
59   int *flag;
60 } keyserver_opts[]=
61 {
62   {"include-revoked",1,&opt.keyserver_options.include_revoked},
63   {"include-disabled",1,&opt.keyserver_options.include_disabled},
64   {"include-subkeys",1,&opt.keyserver_options.include_subkeys},
65   {"keep-temp-files",0,&opt.keyserver_options.keep_temp_files},
66   {"refresh-add-fake-v3-keyids",0,&opt.keyserver_options.fake_v3_keyids},
67   {"auto-key-retrieve",0,&opt.keyserver_options.auto_key_retrieve},
68   {"try-dns-srv",1,&opt.keyserver_options.try_dns_srv},
69   {NULL}
70 };
71
72 static int keyserver_work(int action,STRLIST list,
73                           KEYDB_SEARCH_DESC *desc,int count);
74
75 void 
76 parse_keyserver_options(char *options)
77 {
78   char *tok,*arg;
79
80   while((tok=argsep(&options,&arg)))
81     {
82       int i,hit=0;
83
84       if(tok[0]=='\0')
85         continue;
86
87       for(i=0;keyserver_opts[i].name;i++)
88         {
89           if(ascii_strcasecmp(tok,keyserver_opts[i].name)==0)
90             {
91               *(keyserver_opts[i].flag)=1;
92               hit=1;
93               break;
94             }
95           else if(ascii_strncasecmp("no-",tok,3)==0 &&
96                   ascii_strcasecmp(&tok[3],keyserver_opts[i].name)==0)
97             {
98               *(keyserver_opts[i].flag)=0;
99               hit=1;
100               break;
101             }
102         }
103
104       /* These options need more than just a flag */
105       if(!hit)
106         {
107           if(ascii_strcasecmp(tok,"verbose")==0)
108             opt.keyserver_options.verbose++;
109           else if(ascii_strcasecmp(tok,"no-verbose")==0)
110             opt.keyserver_options.verbose--;
111 #ifdef EXEC_TEMPFILE_ONLY
112           else if(ascii_strcasecmp(tok,"use-temp-files")==0 ||
113                   ascii_strcasecmp(tok,"no-use-temp-files")==0)
114             log_info(_("WARNING: keyserver option \"%s\" is not used "
115                        "on this platform\n"),tok);
116 #else
117           else if(ascii_strcasecmp(tok,"use-temp-files")==0)
118             opt.keyserver_options.use_temp_files=1;
119           else if(ascii_strcasecmp(tok,"no-use-temp-files")==0)
120             opt.keyserver_options.use_temp_files=0;
121 #endif
122           else
123             if(!parse_import_options(tok,
124                                      &opt.keyserver_options.import_options,0)
125                &&
126                !parse_export_options(tok,
127                                      &opt.keyserver_options.export_options,0))
128               {
129                 if(arg)
130                   {
131                     char *joined;
132
133                     joined=m_alloc(strlen(tok)+1+strlen(arg)+1);
134                     /* Make a canonical name=value form with no
135                        spaces */
136                     strcpy(joined,tok);
137                     strcat(joined,"=");
138                     strcat(joined,arg);
139                     add_to_strlist(&opt.keyserver_options.other,joined);
140                     m_free(joined);
141                   }
142                 else
143                   add_to_strlist(&opt.keyserver_options.other,tok);
144               }
145         }
146     }
147 }
148
149 int 
150 parse_keyserver_uri(char *uri,const char *configname,unsigned int configlineno)
151 {
152   int assume_hkp=0;
153
154   assert(uri!=NULL);
155
156   opt.keyserver_host=NULL;
157   opt.keyserver_port=NULL;
158   opt.keyserver_opaque=NULL;
159
160   /* Get the scheme */
161
162   opt.keyserver_scheme=strsep(&uri,":");
163   if(uri==NULL)
164     {
165       /* Assume HKP if there is no scheme */
166       assume_hkp=1;
167       uri=opt.keyserver_scheme;
168       opt.keyserver_scheme="hkp";
169     }
170   else
171     {
172       /* Force to lowercase */
173       char *i;
174
175       for(i=opt.keyserver_scheme;*i!='\0';i++)
176         *i=ascii_tolower(*i);
177     }
178
179   if(ascii_strcasecmp(opt.keyserver_scheme,"x-broken-hkp")==0)
180     {
181       deprecated_warning(configname,configlineno,"x-broken-hkp",
182                          "--keyserver-options ","broken-http-proxy");
183       opt.keyserver_scheme="hkp";
184       add_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
185     }
186   else if(ascii_strcasecmp(opt.keyserver_scheme,"x-hkp")==0
187           || ascii_strcasecmp(opt.keyserver_scheme,"http")==0)
188     {
189       /* Canonicalize this to "hkp" so it works with both the internal
190          and external keyserver interface. */
191       opt.keyserver_scheme="hkp";
192     }
193
194   if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
195     {
196       /* Two slashes means network path. */
197
198       /* Skip over the "//", if any */
199       if(!assume_hkp)
200         uri+=2;
201
202       /* Get the host */
203       opt.keyserver_host=strsep(&uri,":/");
204       if(opt.keyserver_host[0]=='\0')
205         return G10ERR_BAD_URI;
206
207       if(uri==NULL || uri[0]=='\0')
208         opt.keyserver_port=NULL;
209       else
210         {
211           char *ch;
212
213           /* Get the port */
214           opt.keyserver_port=strsep(&uri,"/");
215
216           /* Ports are digits only */
217           ch=opt.keyserver_port;
218           while(*ch!='\0')
219             {
220               if(!digitp(ch))
221                 return G10ERR_BAD_URI;
222
223               ch++;
224             }
225
226           /* It would seem to be reasonable to limit the range of the
227              ports to values between 1-65535, but RFC 1738 and 1808
228              imply there is no limit.  Of course, the real world has
229              limits. */
230         }
231
232       /* (any path part of the URI is discarded for now as no keyserver
233          uses it yet) */
234     }
235   else if(uri[0]!='/')
236     {
237       /* No slash means opaque.  Just record the opaque blob and get
238          out. */
239       opt.keyserver_opaque=uri;
240       return 0;
241     }
242   else
243     {
244       /* One slash means absolute path.  We don't need to support that
245          yet. */
246       return G10ERR_BAD_URI;
247     }
248
249   if(opt.keyserver_scheme[0]=='\0')
250     return G10ERR_BAD_URI;
251
252   return 0;
253 }
254
255 static void
256 print_keyrec(int number,struct keyrec *keyrec)
257 {
258   int i;
259
260   iobuf_writebyte(keyrec->uidbuf,0);
261   iobuf_flush_temp(keyrec->uidbuf);
262   printf("(%d)\t%s  ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
263
264   if(keyrec->size>0)
265     printf("%d bit ",keyrec->size);
266
267   if(keyrec->type)
268     {
269       const char *str=pubkey_algo_to_string(keyrec->type);
270
271       if(str)
272         printf("%s ",str);
273       else
274         printf("unknown ");
275     }
276
277   switch(keyrec->desc.mode)
278     {
279     case KEYDB_SEARCH_MODE_SHORT_KID:
280       printf("key %08lX",(ulong)keyrec->desc.u.kid[1]);
281       break;
282
283     case KEYDB_SEARCH_MODE_LONG_KID:
284       printf("key %08lX%08lX",(ulong)keyrec->desc.u.kid[0],
285              (ulong)keyrec->desc.u.kid[1]);
286       break;
287
288     case KEYDB_SEARCH_MODE_FPR16:
289       printf("key ");
290       for(i=0;i<16;i++)
291         printf("%02X",(unsigned char)keyrec->desc.u.fpr[i]);
292       break;
293
294     case KEYDB_SEARCH_MODE_FPR20:
295       printf("key ");
296       for(i=0;i<20;i++)
297         printf("%02X",(unsigned char)keyrec->desc.u.fpr[i]);
298       break;
299
300     default:
301       BUG();
302       break;
303     }
304
305   if(keyrec->createtime>0)
306     printf(", created %s",strtimestamp(keyrec->createtime));
307
308   if(keyrec->expiretime>0)
309     printf(", expires %s",strtimestamp(keyrec->expiretime));
310
311   if(keyrec->flags&1)
312     printf(" (%s)",("revoked"));
313   if(keyrec->flags&2)
314     printf(" (%s)",("disabled"));
315   if(keyrec->flags&4)
316     printf(" (%s)",("expired"));
317
318   printf("\n");
319 }
320
321 /* Returns a keyrec (which must be freed) once a key is complete, and
322    NULL otherwise.  Call with a NULL keystring once key parsing is
323    complete to return any unfinished keys. */
324 static struct keyrec *
325 parse_keyrec(char *keystring)
326 {
327   static struct keyrec *work=NULL;
328   struct keyrec *ret=NULL;
329   char *record;
330   int i;
331
332   if(keystring==NULL)
333     {
334       if(work==NULL)
335         return NULL;
336       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
337         {
338           m_free(work);
339           return NULL;
340         }
341       else
342         {
343           ret=work;
344           work=NULL;
345           return ret;
346         }
347     }
348
349   if(work==NULL)
350     {
351       work=m_alloc_clear(sizeof(struct keyrec));
352       work->uidbuf=iobuf_temp();
353     }
354
355   /* Remove trailing whitespace */
356   for(i=strlen(keystring);i>0;i--)
357     if(ascii_isspace(keystring[i-1]))
358       keystring[i-1]='\0';
359     else
360       break;
361
362   if((record=strsep(&keystring,":"))==NULL)
363     return ret;
364
365   if(ascii_strcasecmp("pub",record)==0)
366     {
367       char *tok;
368
369       if(work->desc.mode)
370         {
371           ret=work;
372           work=m_alloc_clear(sizeof(struct keyrec));
373           work->uidbuf=iobuf_temp();
374         }
375
376       if((tok=strsep(&keystring,":"))==NULL)
377         return ret;
378
379       classify_user_id(tok,&work->desc);
380       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
381          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
382          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
383          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
384         {
385           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
386           return ret;
387         }
388
389       /* Note all items after this are optional.  This allows us to
390          have a pub line as simple as pub:keyid and nothing else. */
391
392       work->lines++;
393
394       if((tok=strsep(&keystring,":"))==NULL)
395         return ret;
396
397       work->type=atoi(tok);
398
399       if((tok=strsep(&keystring,":"))==NULL)
400         return ret;
401
402       work->size=atoi(tok);
403
404       if((tok=strsep(&keystring,":"))==NULL)
405         return ret;
406
407       work->createtime=atoi(tok);
408
409       if((tok=strsep(&keystring,":"))==NULL)
410         return ret;
411
412       work->expiretime=atoi(tok);
413
414       if((tok=strsep(&keystring,":"))==NULL)
415         return ret;
416
417       while(*tok)
418         switch(*tok++)
419           {
420           case 'r':
421           case 'R':
422             work->flags|=1;
423             break;
424             
425           case 'd':
426           case 'D':
427             work->flags|=2;
428             break;
429
430           case 'e':
431           case 'E':
432             work->flags|=4;
433             break;
434           }
435
436       if(work->expiretime && work->expiretime<=make_timestamp())
437         work->flags|=4;
438     }
439   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
440     {
441       char *userid,*tok,*decoded;
442
443       if((tok=strsep(&keystring,":"))==NULL)
444         return ret;
445
446       if(strlen(tok)==0)
447         return ret;
448
449       userid=tok;
450
451       /* By definition, de-%-encoding is always smaller than the
452          original string so we can decode in place. */
453
454       i=0;
455
456       while(*tok)
457         if(tok[0]=='%' && tok[1] && tok[2])
458           {
459             if((userid[i]=hextobyte(&tok[1]))==-1)
460               userid[i]='?';
461
462             i++;
463             tok+=3;
464           }
465         else
466           userid[i++]=*tok++;
467
468       /* We don't care about the other info provided in the uid: line
469          since no keyserver supports marking userids with timestamps
470          or revoked/expired/disabled yet. */
471
472       /* No need to check for control characters, as utf8_to_native
473          does this for us. */
474
475       decoded=utf8_to_native(userid,i,0);
476       if(strlen(decoded)>opt.screen_columns-10)
477         decoded[opt.screen_columns-10]='\0';
478       iobuf_writestr(work->uidbuf,decoded);
479       m_free(decoded);
480       iobuf_writestr(work->uidbuf,"\n\t");
481       work->lines++;
482     }
483   
484   /* Ignore any records other than "pri" and "uid" for easy future
485      growth. */
486
487   return ret;
488 }
489
490 /* TODO: do this as a list sent to keyserver_work rather than calling
491    it once for each key to get the correct counts after the import
492    (cosmetics, really) and to better take advantage of the keyservers
493    that can do multiple fetches in one go (LDAP). */
494 static int
495 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
496 {
497   char *answer;
498
499   if(count && opt.command_fd==-1)
500     {
501       static int from=1;
502       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
503       from=numdesc+1;
504     }
505
506   answer=cpr_get_no_help("keysearch.prompt",
507                          _("Enter number(s), N)ext, or Q)uit > "));
508   /* control-d */
509   if(answer[0]=='\x04')
510     {
511       printf("Q\n");
512       answer[0]='q';
513     }
514
515   if(answer[0]=='q' || answer[0]=='Q')
516     {
517       m_free(answer);
518       return 1;
519     }
520   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
521     {
522       char *split=answer,*num;
523
524       while((num=strsep(&split," ,"))!=NULL)
525         if(atoi(num)>=1 && atoi(num)<=numdesc)
526           keyserver_work(GET,NULL,&desc[atoi(num)-1],1);
527
528       m_free(answer);
529       return 1;
530     }
531
532   return 0;
533 }
534
535 /* Count and searchstr are just for cosmetics.  If the count is too
536    small, it will grow safely.  If negative it disables the "Key x-y
537    of z" messages. */
538 static void
539 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
540 {
541   int i=0,validcount=0,started=0,header=0,count=1,numlines=0;
542   unsigned int maxlen,buflen;
543   KEYDB_SEARCH_DESC *desc;
544   byte *line=NULL;
545
546   desc=m_alloc(count*sizeof(KEYDB_SEARCH_DESC));
547
548   for(;;)
549     {
550       struct keyrec *keyrec;
551       int rl;
552
553       maxlen=1024;
554       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
555
556       if(opt.with_colons)
557         {
558           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
559              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
560             {
561               header=1;
562               continue;
563             }
564           else if(ascii_strncasecmp("SEARCH ",line,7)==0
565                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
566             continue;
567
568           printf("%s",line);
569         }
570
571       /* Look for an info: line.  The only current info: values
572          defined are the version and key count. */
573       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
574         {
575           char *tok,*str=&line[5];
576
577           if((tok=strsep(&str,":"))!=NULL)
578             {
579               int version;
580
581               if(sscanf(tok,"%d",&version)!=1)
582                 version=1;
583
584               if(version!=1)
585                 {
586                   log_error(_("invalid keyserver protocol "
587                               "(us %d!=handler %d)\n"),1,version);
588                   break;
589                 }
590             }
591
592           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
593             {
594               if(count==0)
595                 goto notfound;
596               else if(count<0)
597                 count=10;
598               else
599                 validcount=1;
600
601               desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
602             }
603
604           started=1;
605           continue;
606         }
607
608       if(rl==0)
609         {
610           keyrec=parse_keyrec(NULL);
611
612           if(keyrec==NULL)
613             {
614               if(i==0)
615                 {
616                   count=0;
617                   break;
618                 }
619
620               if(i!=count)
621                 validcount=0;
622
623               for(;;)
624                 {
625                   if(show_prompt(desc,i,validcount?count:0,searchstr))
626                     break;
627                   validcount=0;
628                 }
629
630               break;
631             }
632         }
633       else
634         keyrec=parse_keyrec(line);
635
636       if(i==count)
637         {
638           /* keyserver helper sent more keys than they claimed in the
639              info: line. */
640           count+=10;
641           desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
642           validcount=0;
643         }
644
645       if(keyrec)
646         {
647           desc[i]=keyrec->desc;
648
649           if(!opt.with_colons)
650             {
651               /* screen_lines - 1 for the prompt. */
652               if(numlines+keyrec->lines>opt.screen_lines-1)
653                 {
654                   if(show_prompt(desc,i,validcount?count:0,searchstr))
655                     break;
656                   else
657                     numlines=0;
658                 }
659
660               print_keyrec(i+1,keyrec);
661             }
662
663           numlines+=keyrec->lines;
664           iobuf_close(keyrec->uidbuf);
665           m_free(keyrec);
666
667           started=1;
668           i++;
669         }
670     }
671
672   m_free(desc);
673   m_free(line);
674
675  notfound:
676   if(count==0)
677     {
678       if(searchstr)
679         log_info(_("key \"%s\" not found on keyserver\n"),searchstr);
680       else
681         log_info(_("key not found on keyserver\n"));
682       return;
683     }
684 }
685
686 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
687 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
688
689 static int 
690 keyserver_spawn(int action,STRLIST list,
691                 KEYDB_SEARCH_DESC *desc,int count,int *prog)
692 {
693   int ret=0,i,gotversion=0,outofband=0;
694   STRLIST temp;
695   unsigned int maxlen,buflen;
696   char *command=NULL,*searchstr=NULL;
697   byte *line=NULL;
698   struct kopts *kopts;
699   struct exec_info *spawn;
700
701 #ifdef EXEC_TEMPFILE_ONLY
702   opt.keyserver_options.use_temp_files=1;
703 #endif
704
705   /* Push the libexecdir into path.  If DISABLE_KEYSERVER_PATH is set,
706      use the 0 arg to replace the path. */
707 #ifdef DISABLE_KEYSERVER_PATH
708   set_exec_path(GNUPG_LIBEXECDIR,0);
709 #else
710   set_exec_path(GNUPG_LIBEXECDIR,opt.exec_path_set);
711 #endif
712
713   /* Build the filename for the helper to execute */
714   command=m_alloc(strlen("gpgkeys_")+strlen(opt.keyserver_scheme)+1);
715   strcpy(command,"gpgkeys_");
716   strcat(command,opt.keyserver_scheme);
717
718   if(opt.keyserver_options.use_temp_files)
719     {
720       if(opt.keyserver_options.keep_temp_files)
721         {
722           command=m_realloc(command,strlen(command)+
723                             strlen(KEYSERVER_ARGS_KEEP)+1);
724           strcat(command,KEYSERVER_ARGS_KEEP);
725         }
726       else
727         {
728           command=m_realloc(command,strlen(command)+
729                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
730           strcat(command,KEYSERVER_ARGS_NOKEEP);  
731         }
732
733       ret=exec_write(&spawn,NULL,command,NULL,0,0);
734     }
735   else
736     ret=exec_write(&spawn,command,NULL,NULL,0,0);
737
738   if(ret)
739     return ret;
740
741   fprintf(spawn->tochild,"# This is a gpg keyserver communications file\n");
742   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
743   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
744   fprintf(spawn->tochild,"SCHEME %s\n",opt.keyserver_scheme);
745
746   if(opt.keyserver_opaque)
747     fprintf(spawn->tochild,"OPAQUE %s\n",opt.keyserver_opaque);
748   else
749     {
750       if(opt.keyserver_host)
751         fprintf(spawn->tochild,"HOST %s\n",opt.keyserver_host);
752
753       if(opt.keyserver_port)
754         fprintf(spawn->tochild,"PORT %s\n",opt.keyserver_port);
755     }
756
757   /* Write options */
758
759   for(i=0,kopts=keyserver_opts;kopts[i].name;i++)
760     if(*(kopts[i].flag) && kopts[i].tell)
761       fprintf(spawn->tochild,"OPTION %s\n",kopts[i].name);
762
763   for(i=0;i<opt.keyserver_options.verbose;i++)
764     fprintf(spawn->tochild,"OPTION verbose\n");
765
766   temp=opt.keyserver_options.other;
767
768   for(;temp;temp=temp->next)
769     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
770
771   switch(action)
772     {
773     case GET:
774       {
775         fprintf(spawn->tochild,"COMMAND GET\n\n");
776
777         /* Which keys do we want? */
778
779         for(i=0;i<count;i++)
780           {
781             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
782               {
783                 int f;
784
785                 fprintf(spawn->tochild,"0x");
786
787                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
788                   fprintf(spawn->tochild,"%02X",(byte)desc[i].u.fpr[f]);
789
790                 fprintf(spawn->tochild,"\n");
791               }
792             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
793               {
794                 int f;
795
796                 fprintf(spawn->tochild,"0x");
797
798                 for(f=0;f<16;f++)
799                   fprintf(spawn->tochild,"%02X",(byte)desc[i].u.fpr[f]);
800
801                 fprintf(spawn->tochild,"\n");
802               }
803             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
804               fprintf(spawn->tochild,"0x%08lX%08lX\n",
805                       (ulong)desc[i].u.kid[0],
806                       (ulong)desc[i].u.kid[1]);
807             else
808               fprintf(spawn->tochild,"0x%08lX\n",
809                       (ulong)desc[i].u.kid[1]);
810           }
811
812         fprintf(spawn->tochild,"\n");
813
814         break;
815       }
816
817     case SEND:
818       {
819         STRLIST key;
820
821         /* Note the extra \n here to send an empty keylist block */
822         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
823
824         for(key=list;key!=NULL;key=key->next)
825           {
826             armor_filter_context_t afx;
827             IOBUF buffer=iobuf_temp();
828             KBNODE block;
829
830             temp=NULL;
831             add_to_strlist(&temp,key->d);
832
833             memset(&afx,0,sizeof(afx));
834             afx.what=1;
835             iobuf_push_filter(buffer,armor_filter,&afx);
836
837             /* TODO: Don't use the keyblock hack here - instead,
838                output each key as a different ascii armored blob with
839                its own INFO section. */
840
841             if(export_pubkeys_stream(buffer,temp,&block,
842                                      opt.keyserver_options.export_options)==-1)
843               iobuf_close(buffer);
844             else
845               {
846                 KBNODE node;
847
848                 iobuf_flush_temp(buffer);
849
850                 merge_keys_and_selfsig(block);
851
852                 fprintf(spawn->tochild,"INFO %s BEGIN\n",key->d);
853
854                 for(node=block;node;node=node->next)
855                   {
856                     switch(node->pkt->pkttype)
857                       {
858                       default:
859                         continue;
860
861                       case PKT_PUBLIC_KEY:
862                       case PKT_PUBLIC_SUBKEY:
863                         {
864                           PKT_public_key *pk=node->pkt->pkt.public_key;
865
866                           keyid_from_pk(pk,NULL);
867
868                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
869                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
870                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
871                                   pk->pubkey_algo,
872                                   nbits_from_pk(pk),
873                                   pk->timestamp,
874                                   pk->expiredate);
875
876                           if(pk->is_revoked)
877                             fprintf(spawn->tochild,"r");
878                           if(pk->has_expired)
879                             fprintf(spawn->tochild,"e");
880
881                           fprintf(spawn->tochild,"\n");
882
883                           break;
884                         }
885
886                       case PKT_USER_ID:
887                         {
888                           PKT_user_id *uid=node->pkt->pkt.user_id;
889                           int r;
890
891                           if(uid->attrib_data)
892                             continue;
893
894                           fprintf(spawn->tochild,"uid:");
895
896                           /* Quote ':', '%', and any 8-bit
897                              characters */
898                           for(r=0;r<uid->len;r++)
899                             {
900                               if(uid->name[r]==':' || uid->name[r]=='%'
901                                  || uid->name[r]&0x80)
902                                 fprintf(spawn->tochild,"%%%02X",uid->name[r]);
903                               else
904                                 fprintf(spawn->tochild,"%c",uid->name[r]);
905                             }
906
907                           fprintf(spawn->tochild,":%u:%u:",
908                                   uid->created,uid->expiredate);
909
910                           if(uid->is_revoked)
911                             fprintf(spawn->tochild,"r");
912                           if(uid->is_expired)
913                             fprintf(spawn->tochild,"e");
914
915                           fprintf(spawn->tochild,"\n");
916                         }
917                       }
918                   }
919
920                 fprintf(spawn->tochild,"INFO %s END\n",key->d);
921
922                 fprintf(spawn->tochild,"KEY %s BEGIN\n",key->d);
923                 fwrite(iobuf_get_temp_buffer(buffer),
924                        iobuf_get_temp_length(buffer),1,spawn->tochild);
925                 fprintf(spawn->tochild,"KEY %s END\n",key->d);
926
927                 iobuf_close(buffer);
928                 release_kbnode(block);
929               }
930
931             free_strlist(temp);
932           }
933
934         break;
935       }
936
937     case SEARCH:
938       {
939         STRLIST key;
940
941         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
942
943         /* Which keys do we want?  Remember that the gpgkeys_ program
944            is going to lump these together into a search string. */
945
946         for(key=list;key!=NULL;key=key->next)
947           {
948             fprintf(spawn->tochild,"%s\n",key->d);
949             if(key!=list)
950               {
951                 searchstr=m_realloc(searchstr,
952                                     strlen(searchstr)+strlen(key->d)+2);
953                 strcat(searchstr," ");
954               }
955             else
956               {
957                 searchstr=m_alloc(strlen(key->d)+1);
958                 searchstr[0]='\0';
959               }
960
961             strcat(searchstr,key->d);
962           }
963
964         fprintf(spawn->tochild,"\n");
965
966         break;
967       }
968
969     default:
970       log_fatal(_("no keyserver action!\n"));
971       break;
972     }
973
974   /* Done sending, so start reading. */
975   ret=exec_read(spawn);
976   if(ret)
977     goto fail;
978
979   /* Now handle the response */
980
981   for(;;)
982     {
983       int plen;
984       char *ptr;
985
986       maxlen=1024;
987       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
988         {
989           ret=G10ERR_READ_FILE;
990           goto fail; /* i.e. EOF */
991         }
992
993       ptr=line;
994
995       /* remove trailing whitespace */
996       plen=strlen(ptr);
997       while(plen>0 && ascii_isspace(ptr[plen-1]))
998         plen--;
999       plen[ptr]='\0';
1000
1001       if(*ptr=='\0')
1002         break;
1003
1004       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1005         {
1006           gotversion=1;
1007
1008           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1009             {
1010               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1011                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1012               goto fail;
1013             }
1014         }
1015       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1016         {
1017           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1018             log_info(_("WARNING: keyserver handler from a different "
1019                        "version of GnuPG (%s)\n"),&ptr[8]);
1020         }
1021       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1022         outofband=1; /* Currently the only OPTION */
1023     }
1024
1025   if(!gotversion)
1026     {
1027       log_error(_("keyserver did not send VERSION\n"));
1028       goto fail;
1029     }
1030
1031   if(!outofband)
1032     switch(action)
1033       {
1034       case GET:
1035         {
1036           void *stats_handle;
1037
1038           stats_handle=import_new_stats_handle();
1039
1040           /* Slurp up all the key data.  In the future, it might be
1041              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1042              It's harmless to ignore them, but ignoring them does make
1043              gpg complain about "no valid OpenPGP data found".  One
1044              way to do this could be to continue parsing this
1045              line-by-line and make a temp iobuf for each key. */
1046
1047           import_keys_stream(spawn->fromchild,stats_handle,
1048                              opt.keyserver_options.import_options);
1049
1050           import_print_stats(stats_handle);
1051           import_release_stats_handle(stats_handle);
1052
1053           break;
1054         }
1055
1056         /* Nothing to do here */
1057       case SEND:
1058         break;
1059
1060       case SEARCH:
1061         {
1062           keyserver_search_prompt(spawn->fromchild,searchstr);
1063
1064           break;
1065         }
1066
1067       default:
1068         log_fatal(_("no keyserver action!\n"));
1069         break;
1070       }
1071
1072  fail:
1073   m_free(line);
1074
1075   *prog=exec_finish(spawn);
1076
1077   return ret;
1078 }
1079
1080 static int 
1081 keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,int count)
1082 {
1083   int rc=0,ret=0;
1084
1085   if(opt.keyserver_scheme==NULL)
1086     {
1087       log_error(_("no keyserver known (use option --keyserver)\n"));
1088       return G10ERR_BAD_URI;
1089     }
1090
1091 #ifdef DISABLE_KEYSERVER_HELPERS
1092
1093   log_error(_("external keyserver calls are not supported in this build\n"));
1094   return G10ERR_KEYSERVER;
1095
1096 #else
1097   /* Spawn a handler */
1098
1099   rc=keyserver_spawn(action,list,desc,count,&ret);
1100   if(ret)
1101     {
1102       switch(ret)
1103         {
1104         case KEYSERVER_SCHEME_NOT_FOUND:
1105           log_error(_("no handler for keyserver scheme \"%s\"\n"),
1106                     opt.keyserver_scheme);
1107           break;
1108
1109         case KEYSERVER_NOT_SUPPORTED:
1110           log_error(_("action \"%s\" not supported with keyserver "
1111                       "scheme \"%s\"\n"),
1112                     action==GET?"get":action==SEND?"send":
1113                     action==SEARCH?"search":"unknown",
1114                     opt.keyserver_scheme);
1115           break;
1116
1117         case KEYSERVER_VERSION_ERROR:
1118           log_error(_("gpgkeys_%s does not support handler version %d\n"),
1119                     opt.keyserver_scheme,KEYSERVER_PROTO_VERSION);
1120           break;
1121
1122         case KEYSERVER_INTERNAL_ERROR:
1123         default:
1124           log_error(_("keyserver internal error\n"));
1125           break;
1126         }
1127
1128       return G10ERR_KEYSERVER;
1129     }
1130
1131   if(rc)
1132     {
1133       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1134
1135       return rc;
1136     }
1137
1138   return 0;
1139 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1140 }
1141
1142 int 
1143 keyserver_export(STRLIST users)
1144 {
1145   /* We better ask for confirmation when the user entered --send-keys
1146      without arguments.  Sending all keys might not be the thing he
1147      intended to do */
1148   if (users || opt.batch || opt.answer_yes)
1149     ;
1150   else if ( !cpr_get_answer_is_yes
1151             ("keyserver_export.send_all",
1152              _("Do you really want to send all your "
1153                "public keys to the keyserver? (y/N) ")))
1154     return -1;
1155
1156   return keyserver_work(SEND,users,NULL,0);
1157 }
1158
1159 int 
1160 keyserver_import(STRLIST users)
1161 {
1162   KEYDB_SEARCH_DESC *desc;
1163   int num=100,count=0;
1164   int rc=0;
1165
1166   /* Build a list of key ids */
1167   desc=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1168
1169   for(;users;users=users->next)
1170     {
1171       classify_user_id (users->d, &desc[count]);
1172       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1173          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1174          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1175          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1176         {
1177           log_error(_("skipping invalid key ID \"%s\"\n"),users->d);
1178           continue;
1179         }
1180
1181       count++;
1182       if(count==num)
1183         {
1184           num+=100;
1185           desc=m_realloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1186         }
1187     }
1188
1189   if(count>0)
1190     rc=keyserver_work(GET,NULL,desc,count);
1191
1192   m_free(desc);
1193
1194   return rc;
1195 }
1196
1197 int
1198 keyserver_import_fprint(const byte *fprint,size_t fprint_len)
1199 {
1200   KEYDB_SEARCH_DESC desc;
1201
1202   memset(&desc,0,sizeof(desc));
1203
1204   if(fprint_len==16)
1205     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1206   else if(fprint_len==20)
1207     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1208   else
1209     return -1;
1210
1211   memcpy(desc.u.fpr,fprint,fprint_len);
1212
1213   return keyserver_work(GET,NULL,&desc,1);
1214 }
1215
1216 int 
1217 keyserver_import_keyid(u32 *keyid)
1218 {
1219   KEYDB_SEARCH_DESC desc;
1220
1221   memset(&desc,0,sizeof(desc));
1222
1223   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1224   desc.u.kid[0]=keyid[0];
1225   desc.u.kid[1]=keyid[1];
1226
1227   return keyserver_work(GET,NULL,&desc,1);
1228 }
1229
1230 /* code mostly stolen from do_export_stream */
1231 static int 
1232 keyidlist(STRLIST users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1233 {
1234   int rc=0,ndesc,num=100;
1235   KBNODE keyblock=NULL,node;
1236   KEYDB_HANDLE kdbhd;
1237   KEYDB_SEARCH_DESC *desc;
1238   STRLIST sl;
1239
1240   *count=0;
1241
1242   *klist=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1243
1244   kdbhd=keydb_new(0);
1245
1246   if(!users)
1247     {
1248       ndesc = 1;
1249       desc = m_alloc_clear ( ndesc * sizeof *desc);
1250       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1251     }
1252   else
1253     {
1254       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
1255         ;
1256       desc = m_alloc ( ndesc * sizeof *desc);
1257         
1258       for (ndesc=0, sl=users; sl; sl = sl->next)
1259         {
1260           if(classify_user_id (sl->d, desc+ndesc))
1261             ndesc++;
1262           else
1263             log_error (_("key `%s' not found: %s\n"),
1264                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1265         }
1266     }
1267
1268   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1269     {
1270       if (!users) 
1271         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1272
1273       /* read the keyblock */
1274       rc = keydb_get_keyblock (kdbhd, &keyblock );
1275       if( rc )
1276         {
1277           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1278           goto leave;
1279         }
1280
1281       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1282         {
1283           /* This is to work around a bug in some keyservers (pksd and
1284              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1285              The answer is to refresh both the correct v4 keyid
1286              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1287              This only happens for key refresh using the HKP scheme
1288              and if the refresh-add-fake-v3-keyids keyserver option is
1289              set. */
1290           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1291              node->pkt->pkt.public_key->version>=4)
1292             {
1293               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1294               mpi_get_keyid(node->pkt->pkt.public_key->pkey[0],
1295                             (*klist)[*count].u.kid);
1296               (*count)++;
1297
1298               if(*count==num)
1299                 {
1300                   num+=100;
1301                   *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1302                 }
1303             }
1304
1305           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1306              This is because it's easy to calculate any sort of key id
1307              from a v4 fingerprint, but not a v3 fingerprint. */
1308
1309           if(node->pkt->pkt.public_key->version<4)
1310             {
1311               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1312               keyid_from_pk(node->pkt->pkt.public_key,
1313                             (*klist)[*count].u.kid);
1314             }
1315           else
1316             {
1317               size_t dummy;
1318
1319               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1320               fingerprint_from_pk(node->pkt->pkt.public_key,
1321                                   (*klist)[*count].u.fpr,&dummy);
1322             }
1323
1324           (*count)++;
1325
1326           if(*count==num)
1327             {
1328               num+=100;
1329               *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1330             }
1331         }
1332     }
1333
1334   if(rc==-1)
1335     rc=0;
1336   
1337  leave:
1338   m_free(desc);
1339   keydb_release(kdbhd);
1340   release_kbnode(keyblock);
1341
1342   return rc;
1343 }
1344
1345 /* Note this is different than the original HKP refresh.  It allows
1346    usernames to refresh only part of the keyring. */
1347
1348 int 
1349 keyserver_refresh(STRLIST users)
1350 {
1351   int rc,count,fakev3=0;
1352   KEYDB_SEARCH_DESC *desc;
1353
1354   /* We switch merge_only on during a refresh, as 'refresh' should
1355      never import new keys, even if their keyids match.  Is it worth
1356      preserving the old merge_only value here? */
1357   opt.import_options|=IMPORT_MERGE_ONLY;
1358
1359   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1360      scheme, then enable fake v3 keyid generation. */
1361   if(opt.keyserver_options.fake_v3_keyids && opt.keyserver_scheme &&
1362      (ascii_strcasecmp(opt.keyserver_scheme,"hkp")==0 ||
1363       ascii_strcasecmp(opt.keyserver_scheme,"mailto")==0))
1364     fakev3=1;
1365
1366   rc=keyidlist(users,&desc,&count,fakev3);
1367   if(rc)
1368     return rc;
1369
1370   if(count>0)
1371     {
1372       if(opt.keyserver_uri)
1373         {
1374           if(count==1)
1375             log_info(_("refreshing 1 key from %s\n"),opt.keyserver_uri);
1376           else
1377             log_info(_("refreshing %d keys from %s\n"),
1378                      count,opt.keyserver_uri);
1379         }
1380
1381       rc=keyserver_work(GET,NULL,desc,count);
1382     }
1383
1384   m_free(desc);
1385
1386   return rc;
1387 }
1388
1389 int
1390 keyserver_search(STRLIST tokens)
1391 {
1392   if(tokens)
1393     return keyserver_work(SEARCH,tokens,NULL,0);
1394   else
1395     return 0;
1396 }