59d67e32d479c4465cba88deb3a23984c5a6d512
[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,*tok;
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       if(work->desc.mode)
346         {
347           ret=work;
348           work=m_alloc_clear(sizeof(struct keyrec));
349           work->uidbuf=iobuf_temp();
350         }
351
352       if((tok=strsep(&keystring,":"))==NULL)
353         return ret;
354
355       classify_user_id(tok,&work->desc);
356       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
357          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
358          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
359          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
360         {
361           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
362           return ret;
363         }
364
365       /* Note all items after this are optional.  This allows us to
366          have a pub line as simple as pub:keyid and nothing else. */
367
368       work->lines++;
369
370       if((tok=strsep(&keystring,":"))==NULL)
371         return ret;
372
373       work->type=atoi(tok);
374
375       if((tok=strsep(&keystring,":"))==NULL)
376         return ret;
377
378       work->size=atoi(tok);
379
380       if((tok=strsep(&keystring,":"))==NULL)
381         return ret;
382
383       work->createtime=atoi(tok);
384
385       if((tok=strsep(&keystring,":"))==NULL)
386         return ret;
387
388       work->expiretime=atoi(tok);
389
390       if((tok=strsep(&keystring,":"))==NULL)
391         return ret;
392
393       while(*tok)
394         switch(*tok++)
395           {
396           case 'r':
397           case 'R':
398             work->flags|=1;
399             break;
400             
401           case 'd':
402           case 'D':
403             work->flags|=2;
404             break;
405
406           case 'e':
407           case 'E':
408             work->flags|=4;
409             break;
410           }
411
412       if(work->expiretime && work->expiretime<=make_timestamp())
413         work->flags|=4;
414     }
415   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
416     {
417       char *userid,*tok,*decoded;
418       int i=0;
419
420       if((tok=strsep(&keystring,":"))==NULL)
421         return ret;
422
423       if(strlen(tok)==0)
424         return ret;
425
426       userid=tok;
427
428       /* By definition, de-%-encoding is always smaller than the
429          original string so we can decode in place. */
430
431       while(*tok)
432         if(tok[0]=='%' && tok[1] && tok[2])
433           {
434             if((userid[i]=hextobyte(&tok[1]))==-1)
435               userid[i]='?';
436
437             i++;
438             tok+=3;
439           }
440         else
441           userid[i++]=*tok++;
442
443       /* We don't care about the other info provided in the uid: line
444          since no keyserver supports marking userids with timestamps
445          or revoked/expired/disabled yet. */
446
447       /* No need to check for control characters, as utf8_to_native
448          does this for us. */
449
450       decoded=utf8_to_native(userid,i,0);
451       iobuf_writestr(work->uidbuf,decoded);
452       m_free(decoded);
453       iobuf_writestr(work->uidbuf,"\n\t");
454       work->lines++;
455     }
456   
457   /* Ignore any records other than "pri" and "uid" for easy future
458      growth. */
459
460   return ret;
461 }
462
463 /* TODO: do this as a list sent to keyserver_work rather than calling
464    it once for each key to get the correct counts after the import
465    (cosmetics, really) and to better take advantage of the keyservers
466    that can do multiple fetches in one go (LDAP). */
467 static int
468 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
469 {
470   char *answer;
471
472   if(count)
473     {
474       static int from=1;
475       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
476       from=numdesc+1;
477     }
478
479   answer=cpr_get_no_help("keysearch.prompt",
480                          _("Enter number(s), N)ext, or Q)uit > "));
481   /* control-d */
482   if(answer[0]=='\x04')
483     {
484       printf("Q\n");
485       answer[0]='q';
486     }
487
488   if(answer[0]=='q' || answer[0]=='Q')
489     {
490       m_free(answer);
491       return 1;
492     }
493   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
494     {
495       char *split=answer,*num;
496
497       while((num=strsep(&split," ,"))!=NULL)
498         if(atoi(num)>=1 && atoi(num)<=numdesc)
499           keyserver_work(GET,NULL,&desc[atoi(num)-1],1);
500
501       m_free(answer);
502       return 1;
503     }
504
505   return 0;
506 }
507
508 /* Count and searchstr are just for cosmetics.  If the count is too
509    small, it will grow safely.  If negative it disables the "Key x-y
510    of z" messages. */
511 static void
512 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
513 {
514   int i=0,validcount=0,started=0,count=1;
515   unsigned int maxlen,buflen;
516   KEYDB_SEARCH_DESC *desc;
517   byte *line=NULL;
518   /* TODO: Something other than 23?  That's 24-1 (the prompt). */
519   int maxlines=23,numlines=0;
520
521   desc=m_alloc(count*sizeof(KEYDB_SEARCH_DESC));
522
523   for(;;)
524     {
525       struct keyrec *keyrec;
526       int rl;
527
528       maxlen=1024;
529       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
530
531       /* Look for an info: line.  The only current info: values
532          defined are the version and key count. */
533       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
534         {
535           char *tok,*str=&line[5];
536
537           if((tok=strsep(&str,":"))!=NULL)
538             {
539               int version;
540
541               if(sscanf(tok,"%d",&version)!=1)
542                 version=1;
543
544               if(version!=1)
545                 {
546                   log_error(_("invalid keyserver protocol "
547                               "(us %d!=handler %d)\n"),1,version);
548                   break;
549                 }
550             }
551
552           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
553             {
554               if(count==0)
555                 goto notfound;
556               else if(count<0)
557                 count=10;
558               else
559                 validcount=1;
560
561               desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
562             }
563
564           started=1;
565           continue;
566         }
567
568       if(rl==0)
569         {
570           keyrec=parse_keyrec(NULL);
571
572           if(keyrec==NULL)
573             {
574               if(i==0)
575                 {
576                   count=0;
577                   break;
578                 }
579
580               if(i!=count)
581                 validcount=0;
582
583               for(;;)
584                 {
585                   if(show_prompt(desc,i,validcount?count:0,searchstr))
586                     break;
587                   validcount=0;
588                 }
589
590               break;
591             }
592         }
593       else
594         keyrec=parse_keyrec(line);
595
596       if(i==count)
597         {
598           /* keyserver helper sent more keys than they claimed in the
599              info: line. */
600           count+=10;
601           desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
602           validcount=0;
603         }
604
605       if(keyrec)
606         {
607           desc[i]=keyrec->desc;
608
609           if(numlines+keyrec->lines>maxlines)
610             {
611               if(show_prompt(desc,i,validcount?count:0,searchstr))
612                 break;
613               else
614                 numlines=0;
615             }
616
617           print_keyrec(i+1,keyrec);
618           numlines+=keyrec->lines;
619           iobuf_close(keyrec->uidbuf);
620           m_free(keyrec);
621
622           started=1;
623           i++;
624         }
625     }
626
627   m_free(desc);
628   m_free(line);
629
630  notfound:
631   if(count==0)
632     {
633       if(searchstr)
634         log_info(_("key \"%s\" not found on keyserver\n"),searchstr);
635       else
636         log_info(_("key not found on keyserver\n"));
637       return;
638     }
639 }
640
641 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
642 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
643
644 static int 
645 keyserver_spawn(int action,STRLIST list,
646                 KEYDB_SEARCH_DESC *desc,int count,int *prog)
647 {
648   int ret=0,i,gotversion=0,outofband=0;
649   STRLIST temp;
650   unsigned int maxlen,buflen;
651   char *command=NULL,*searchstr=NULL;
652   byte *line=NULL;
653   struct kopts *kopts;
654   struct exec_info *spawn;
655
656 #ifdef EXEC_TEMPFILE_ONLY
657   opt.keyserver_options.use_temp_files=1;
658 #endif
659
660   /* Push the libexecdir into path.  If DISABLE_KEYSERVER_PATH is set,
661      use the 0 arg to replace the path. */
662 #ifdef DISABLE_KEYSERVER_PATH
663   set_exec_path(GNUPG_LIBEXECDIR,0);
664 #else
665   set_exec_path(GNUPG_LIBEXECDIR,opt.exec_path_set);
666 #endif
667
668   /* Build the filename for the helper to execute */
669   command=m_alloc(strlen("gpgkeys_")+strlen(opt.keyserver_scheme)+1);
670   strcpy(command,"gpgkeys_");
671   strcat(command,opt.keyserver_scheme);
672
673   if(opt.keyserver_options.use_temp_files)
674     {
675       if(opt.keyserver_options.keep_temp_files)
676         {
677           command=m_realloc(command,strlen(command)+
678                             strlen(KEYSERVER_ARGS_KEEP)+1);
679           strcat(command,KEYSERVER_ARGS_KEEP);
680         }
681       else
682         {
683           command=m_realloc(command,strlen(command)+
684                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
685           strcat(command,KEYSERVER_ARGS_NOKEEP);  
686         }
687
688       ret=exec_write(&spawn,NULL,command,NULL,0,0);
689     }
690   else
691     ret=exec_write(&spawn,command,NULL,NULL,0,0);
692
693   if(ret)
694     return ret;
695
696   fprintf(spawn->tochild,"# This is a gpg keyserver communications file\n");
697   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
698   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
699
700   if(opt.keyserver_opaque)
701     fprintf(spawn->tochild,"OPAQUE %s\n",opt.keyserver_opaque);
702   else
703     {
704       if(opt.keyserver_host)
705         fprintf(spawn->tochild,"HOST %s\n",opt.keyserver_host);
706
707       if(opt.keyserver_port)
708         fprintf(spawn->tochild,"PORT %s\n",opt.keyserver_port);
709     }
710
711   /* Write options */
712
713   for(i=0,kopts=keyserver_opts;kopts[i].name;i++)
714     if(*(kopts[i].flag) && kopts[i].tell)
715       fprintf(spawn->tochild,"OPTION %s\n",kopts[i].name);
716
717   for(i=0;i<opt.keyserver_options.verbose;i++)
718     fprintf(spawn->tochild,"OPTION verbose\n");
719
720   temp=opt.keyserver_options.other;
721
722   for(;temp;temp=temp->next)
723     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
724
725   switch(action)
726     {
727     case GET:
728       {
729         fprintf(spawn->tochild,"COMMAND GET\n\n");
730
731         /* Which keys do we want? */
732
733         for(i=0;i<count;i++)
734           {
735             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
736               {
737                 int f;
738
739                 fprintf(spawn->tochild,"0x");
740
741                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
742                   fprintf(spawn->tochild,"%02X",(byte)desc[i].u.fpr[f]);
743
744                 fprintf(spawn->tochild,"\n");
745               }
746             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
747               {
748                 int f;
749
750                 fprintf(spawn->tochild,"0x");
751
752                 for(f=0;f<16;f++)
753                   fprintf(spawn->tochild,"%02X",(byte)desc[i].u.fpr[f]);
754
755                 fprintf(spawn->tochild,"\n");
756               }
757             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
758               fprintf(spawn->tochild,"0x%08lX%08lX\n",
759                       (ulong)desc[i].u.kid[0],
760                       (ulong)desc[i].u.kid[1]);
761             else
762               fprintf(spawn->tochild,"0x%08lX\n",
763                       (ulong)desc[i].u.kid[1]);
764           }
765
766         fprintf(spawn->tochild,"\n");
767
768         break;
769       }
770
771     case SEND:
772       {
773         STRLIST key;
774
775         /* Note the extra \n here to send an empty keylist block */
776         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
777
778         for(key=list;key!=NULL;key=key->next)
779           {
780             armor_filter_context_t afx;
781             IOBUF buffer=iobuf_temp();
782
783             temp=NULL;
784             add_to_strlist(&temp,key->d);
785
786             memset(&afx,0,sizeof(afx));
787             afx.what=1;
788             iobuf_push_filter(buffer,armor_filter,&afx);
789
790             if(export_pubkeys_stream(buffer,temp,
791                                      opt.keyserver_options.export_options)==-1)
792               iobuf_close(buffer);
793             else
794               {
795                 iobuf_flush_temp(buffer);
796
797                 fprintf(spawn->tochild,"KEY %s BEGIN\n",key->d);
798                 fwrite(iobuf_get_temp_buffer(buffer),
799                        iobuf_get_temp_length(buffer),1,spawn->tochild);
800                 fprintf(spawn->tochild,"KEY %s END\n",key->d);
801
802                 iobuf_close(buffer);
803               }
804
805             free_strlist(temp);
806           }
807
808         break;
809       }
810
811     case SEARCH:
812       {
813         STRLIST key;
814
815         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
816
817         /* Which keys do we want?  Remember that the gpgkeys_ program
818            is going to lump these together into a search string. */
819
820         for(key=list;key!=NULL;key=key->next)
821           {
822             fprintf(spawn->tochild,"%s\n",key->d);
823             if(key!=list)
824               {
825                 searchstr=m_realloc(searchstr,
826                                     strlen(searchstr)+strlen(key->d)+2);
827                 strcat(searchstr," ");
828               }
829             else
830               {
831                 searchstr=m_alloc(strlen(key->d)+1);
832                 searchstr[0]='\0';
833               }
834
835             strcat(searchstr,key->d);
836           }
837
838         fprintf(spawn->tochild,"\n");
839
840         break;
841       }
842
843     default:
844       log_fatal(_("no keyserver action!\n"));
845       break;
846     }
847
848   /* Done sending, so start reading. */
849   ret=exec_read(spawn);
850   if(ret)
851     goto fail;
852
853   /* Now handle the response */
854
855   for(;;)
856     {
857       int plen;
858       char *ptr;
859
860       maxlen=1024;
861       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
862         {
863           ret=G10ERR_READ_FILE;
864           goto fail; /* i.e. EOF */
865         }
866
867       ptr=line;
868
869       /* remove trailing whitespace */
870       plen=strlen(ptr);
871       while(plen>0 && isspace(ptr[plen-1]))
872         plen--;
873       plen[ptr]='\0';
874
875       if(*ptr=='\0')
876         break;
877
878       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
879         {
880           gotversion=1;
881
882           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
883             {
884               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
885                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
886               goto fail;
887             }
888         }
889       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
890         {
891           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
892             log_info(_("WARNING: keyserver handler from a different "
893                        "version of GnuPG (%s)\n"),&ptr[8]);
894         }
895       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
896         outofband=1; /* Currently the only OPTION */
897     }
898
899   if(!gotversion)
900     {
901       log_error(_("keyserver did not send VERSION\n"));
902       goto fail;
903     }
904
905   if(!outofband)
906     switch(action)
907       {
908       case GET:
909         {
910           void *stats_handle;
911
912           stats_handle=import_new_stats_handle();
913
914           /* Slurp up all the key data.  In the future, it might be
915              nice to look for KEY foo OUTOFBAND and FAILED indicators.
916              It's harmless to ignore them, but ignoring them does make
917              gpg complain about "no valid OpenPGP data found".  One
918              way to do this could be to continue parsing this
919              line-by-line and make a temp iobuf for each key. */
920
921           import_keys_stream(spawn->fromchild,stats_handle,
922                              opt.keyserver_options.import_options);
923
924           import_print_stats(stats_handle);
925           import_release_stats_handle(stats_handle);
926
927           break;
928         }
929
930         /* Nothing to do here */
931       case SEND:
932         break;
933
934       case SEARCH:
935         {
936           keyserver_search_prompt(spawn->fromchild,searchstr);
937
938           break;
939         }
940
941       default:
942         log_fatal(_("no keyserver action!\n"));
943         break;
944       }
945
946  fail:
947   m_free(line);
948
949   *prog=exec_finish(spawn);
950
951   return ret;
952 }
953
954 static int 
955 keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,int count)
956 {
957   int rc=0,ret=0;
958
959   if(opt.keyserver_scheme==NULL)
960     {
961       log_error(_("no keyserver known (use option --keyserver)\n"));
962       return G10ERR_BAD_URI;
963     }
964
965 #ifdef DISABLE_KEYSERVER_HELPERS
966
967   log_error(_("external keyserver calls are not supported in this build\n"));
968   return G10ERR_KEYSERVER;
969
970 #else
971   /* Spawn a handler */
972
973   rc=keyserver_spawn(action,list,desc,count,&ret);
974   if(ret)
975     {
976       switch(ret)
977         {
978         case KEYSERVER_SCHEME_NOT_FOUND:
979           log_error(_("no handler for keyserver scheme \"%s\"\n"),
980                     opt.keyserver_scheme);
981           break;
982
983         case KEYSERVER_NOT_SUPPORTED:
984           log_error(_("action \"%s\" not supported with keyserver "
985                       "scheme \"%s\"\n"),
986                     action==GET?"get":action==SEND?"send":
987                     action==SEARCH?"search":"unknown",
988                     opt.keyserver_scheme);
989           break;
990
991         case KEYSERVER_VERSION_ERROR:
992           log_error(_("gpgkeys_%s does not support handler version %d\n"),
993                     opt.keyserver_scheme,KEYSERVER_PROTO_VERSION);
994           break;
995
996         case KEYSERVER_INTERNAL_ERROR:
997         default:
998           log_error(_("keyserver internal error\n"));
999           break;
1000         }
1001
1002       return G10ERR_KEYSERVER;
1003     }
1004
1005   if(rc)
1006     {
1007       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1008
1009       return rc;
1010     }
1011
1012   return 0;
1013 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1014 }
1015
1016 int 
1017 keyserver_export(STRLIST users)
1018 {
1019   /* We better ask for confirmation when the user entered --send-keys
1020      without arguments.  Sending all keys might not be the thing he
1021      intended to do */
1022   if (users || opt.batch || opt.answer_yes)
1023     ;
1024   else if ( !cpr_get_answer_is_yes
1025             ("keyserver_export.send_all",
1026              _("Do you really want to send all your "
1027                "public keys to the keyserver? (y/N) ")))
1028     return -1;
1029
1030   return keyserver_work(SEND,users,NULL,0);
1031 }
1032
1033 int 
1034 keyserver_import(STRLIST users)
1035 {
1036   KEYDB_SEARCH_DESC *desc;
1037   int num=100,count=0;
1038   int rc=0;
1039
1040   /* Build a list of key ids */
1041   desc=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1042
1043   for(;users;users=users->next)
1044     {
1045       classify_user_id (users->d, &desc[count]);
1046       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1047          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1048          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1049          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1050         {
1051           log_error(_("skipping invalid key ID \"%s\"\n"),users->d);
1052           continue;
1053         }
1054
1055       count++;
1056       if(count==num)
1057         {
1058           num+=100;
1059           desc=m_realloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1060         }
1061     }
1062
1063   if(count>0)
1064     rc=keyserver_work(GET,NULL,desc,count);
1065
1066   m_free(desc);
1067
1068   return rc;
1069 }
1070
1071 int
1072 keyserver_import_fprint(const byte *fprint,size_t fprint_len)
1073 {
1074   KEYDB_SEARCH_DESC desc;
1075
1076   memset(&desc,0,sizeof(desc));
1077
1078   if(fprint_len==16)
1079     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1080   else if(fprint_len==20)
1081     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1082   else
1083     return -1;
1084
1085   memcpy(desc.u.fpr,fprint,fprint_len);
1086
1087   return keyserver_work(GET,NULL,&desc,1);
1088 }
1089
1090 int 
1091 keyserver_import_keyid(u32 *keyid)
1092 {
1093   KEYDB_SEARCH_DESC desc;
1094
1095   memset(&desc,0,sizeof(desc));
1096
1097   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1098   desc.u.kid[0]=keyid[0];
1099   desc.u.kid[1]=keyid[1];
1100
1101   return keyserver_work(GET,NULL,&desc,1);
1102 }
1103
1104 /* code mostly stolen from do_export_stream */
1105 static int 
1106 keyidlist(STRLIST users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1107 {
1108   int rc=0,ndesc,num=100;
1109   KBNODE keyblock=NULL,node;
1110   KEYDB_HANDLE kdbhd;
1111   KEYDB_SEARCH_DESC *desc;
1112   STRLIST sl;
1113
1114   *count=0;
1115
1116   *klist=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1117
1118   kdbhd=keydb_new(0);
1119
1120   if(!users)
1121     {
1122       ndesc = 1;
1123       desc = m_alloc_clear ( ndesc * sizeof *desc);
1124       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1125     }
1126   else
1127     {
1128       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
1129         ;
1130       desc = m_alloc ( ndesc * sizeof *desc);
1131         
1132       for (ndesc=0, sl=users; sl; sl = sl->next)
1133         {
1134           if(classify_user_id (sl->d, desc+ndesc))
1135             ndesc++;
1136           else
1137             log_error (_("key `%s' not found: %s\n"),
1138                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1139         }
1140     }
1141
1142   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1143     {
1144       if (!users) 
1145         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1146
1147       /* read the keyblock */
1148       rc = keydb_get_keyblock (kdbhd, &keyblock );
1149       if( rc )
1150         {
1151           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1152           goto leave;
1153         }
1154
1155       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1156         {
1157           /* This is to work around a bug in some keyservers (pksd and
1158              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1159              The answer is to refresh both the correct v4 keyid
1160              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1161              This only happens for key refresh using the HKP scheme
1162              and if the refresh-add-fake-v3-keyids keyserver option is
1163              set. */
1164           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1165              node->pkt->pkt.public_key->version>=4)
1166             {
1167               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1168               mpi_get_keyid(node->pkt->pkt.public_key->pkey[0],
1169                             (*klist)[*count].u.kid);
1170               (*count)++;
1171
1172               if(*count==num)
1173                 {
1174                   num+=100;
1175                   *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1176                 }
1177             }
1178
1179           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1180              This is because it's easy to calculate any sort of key id
1181              from a v4 fingerprint, but not a v3 fingerprint. */
1182
1183           if(node->pkt->pkt.public_key->version<4)
1184             {
1185               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1186               keyid_from_pk(node->pkt->pkt.public_key,
1187                             (*klist)[*count].u.kid);
1188             }
1189           else
1190             {
1191               size_t dummy;
1192
1193               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1194               fingerprint_from_pk(node->pkt->pkt.public_key,
1195                                   (*klist)[*count].u.fpr,&dummy);
1196             }
1197
1198           (*count)++;
1199
1200           if(*count==num)
1201             {
1202               num+=100;
1203               *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1204             }
1205         }
1206     }
1207
1208   if(rc==-1)
1209     rc=0;
1210   
1211  leave:
1212   m_free(desc);
1213   keydb_release(kdbhd);
1214   release_kbnode(keyblock);
1215
1216   return rc;
1217 }
1218
1219 /* Note this is different than the original HKP refresh.  It allows
1220    usernames to refresh only part of the keyring. */
1221
1222 int 
1223 keyserver_refresh(STRLIST users)
1224 {
1225   int rc,count,fakev3=0;
1226   KEYDB_SEARCH_DESC *desc;
1227
1228   /* We switch merge_only on during a refresh, as 'refresh' should
1229      never import new keys, even if their keyids match.  Is it worth
1230      preserving the old merge_only value here? */
1231   opt.merge_only=1;
1232
1233   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1234      scheme, then enable fake v3 keyid generation. */
1235   if(opt.keyserver_options.fake_v3_keyids && opt.keyserver_scheme &&
1236      (ascii_strcasecmp(opt.keyserver_scheme,"hkp")==0 ||
1237       ascii_strcasecmp(opt.keyserver_scheme,"mailto")==0))
1238     fakev3=1;
1239
1240   rc=keyidlist(users,&desc,&count,fakev3);
1241   if(rc)
1242     return rc;
1243
1244   if(count==1)
1245     log_info(_("refreshing 1 key from %s\n"),opt.keyserver_uri);
1246   else
1247     log_info(_("refreshing %d keys from %s\n"),count,opt.keyserver_uri);
1248
1249   if(count>0)
1250     rc=keyserver_work(GET,NULL,desc,count);
1251
1252   m_free(desc);
1253
1254   return 0;
1255 }
1256
1257 int
1258 keyserver_search(STRLIST tokens)
1259 {
1260   if(tokens)
1261     return keyserver_work(SEARCH,tokens,NULL,0);
1262   else
1263     return 0;
1264 }