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