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