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