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