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