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