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