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