* keyserver.c (keyserver_spawn): Don't mess about with the $PATH.
[gnupg.git] / g10 / keyserver.c
1 /* keyserver.c - generic keyserver code
2  * Copyright (C) 2001, 2002, 2003, 2004, 2005 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 "trustdb.h"
39 #include "keyserver-internal.h"
40 #include "util.h"
41
42 #define GET    0
43 #define SEND   1
44 #define SEARCH 2
45
46 #define GPGKEYS_PREFIX "gpgkeys_"
47
48 struct keyrec
49 {
50   KEYDB_SEARCH_DESC desc;
51   u32 createtime,expiretime;
52   int size,flags;
53   byte type;
54   IOBUF uidbuf;
55   unsigned int lines;
56 };
57
58 /* Tell remote processes about these options */
59 #define REMOTE_TELL (KEYSERVER_INCLUDE_REVOKED|KEYSERVER_INCLUDE_SUBKEYS|KEYSERVER_TRY_DNS_SRV)
60
61 static struct parse_options keyserver_opts[]=
62   {
63     {"include-revoked",KEYSERVER_INCLUDE_REVOKED,NULL},      
64     {"include-subkeys",KEYSERVER_INCLUDE_SUBKEYS,NULL},
65     {"keep-temp-files",KEYSERVER_KEEP_TEMP_FILES,NULL},
66     {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL},
67     {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL},
68     {"try-dns-srv",KEYSERVER_TRY_DNS_SRV,NULL},
69     {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL},
70     {NULL,0,NULL}
71   };
72
73 static int keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
74                           int count,struct keyserver_spec *keyserver);
75
76 int
77 parse_keyserver_options(char *options)
78 {
79   int ret=1;
80   char *tok;
81
82   while((tok=optsep(&options)))
83     {
84       if(tok[0]=='\0')
85         continue;
86
87       /* For backwards compatibility.  1.2.x used honor-http-proxy and
88          there are a good number of documents published that recommend
89          it. */
90       if(ascii_strcasecmp(tok,"honor-http-proxy")==0)
91         tok="http-proxy";
92       else if(ascii_strcasecmp(tok,"no-honor-http-proxy")==0)
93         tok="no-http-proxy";
94
95       /* We accept quite a few possible options here - some options to
96          handle specially, the keyserver_options list, and import and
97          export options that pertain to keyserver operations.  Note
98          that you must use strncasecmp here as there might be an
99          =argument attached which will foil the use of strcasecmp. */
100
101 #ifdef EXEC_TEMPFILE_ONLY
102       if(ascii_strncasecmp(tok,"use-temp-files",14)==0 ||
103               ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
104         log_info(_("WARNING: keyserver option `%s' is not used"
105                    " on this platform\n"),tok);
106 #else
107       if(ascii_strncasecmp(tok,"use-temp-files",14)==0)
108         opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
109       else if(ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
110         opt.keyserver_options.options&=~KEYSERVER_USE_TEMP_FILES;
111 #endif
112       else if(!parse_options(tok,&opt.keyserver_options.options,
113                              keyserver_opts,0)
114          && !parse_import_options(tok,
115                                   &opt.keyserver_options.import_options,0)
116          && !parse_export_options(tok,
117                                   &opt.keyserver_options.export_options,0))
118         {
119           /* All of the standard options have failed, so the option is
120              destined for a keyserver plugin. */
121           char *arg=argsplit(tok);
122
123           if(arg)
124             {
125               char *joined;
126
127               joined=m_alloc(strlen(tok)+1+strlen(arg)+1);
128               /* Make a canonical name=value form with no
129                  spaces */
130               strcpy(joined,tok);
131               strcat(joined,"=");
132               strcat(joined,arg);
133               add_to_strlist(&opt.keyserver_options.other,joined);
134               m_free(joined);
135             }
136           else
137             add_to_strlist(&opt.keyserver_options.other,tok);
138         }
139     }
140
141   return ret;
142 }
143
144 void
145 free_keyserver_spec(struct keyserver_spec *keyserver)
146 {
147   m_free(keyserver->uri);
148   m_free(keyserver->scheme);
149   m_free(keyserver->auth);
150   m_free(keyserver->host);
151   m_free(keyserver->port);
152   m_free(keyserver->path);
153   m_free(keyserver->opaque);
154   m_free(keyserver);
155 }
156
157 struct keyserver_spec *
158 parse_keyserver_uri(const char *uri,int require_scheme,
159                     const char *configname,unsigned int configlineno)
160 {
161   int assume_hkp=0;
162   struct keyserver_spec *keyserver;
163   const char *idx;
164   int count;
165
166   assert(uri!=NULL);
167
168   keyserver=m_alloc_clear(sizeof(struct keyserver_spec));
169
170   keyserver->uri=m_strdup(uri);
171
172   /* Get the scheme */
173
174   for(idx=uri,count=0;*idx && *idx!=':';idx++)
175     {
176       count++;
177
178       /* Do we see the start of an RFC-2732 ipv6 address here?  If so,
179          there clearly isn't a scheme so get out early. */
180       if(*idx=='[')
181         {
182           /* Was the '[' the first thing in the string?  If not, we
183              have a mangled scheme with a [ in it so fail. */
184           if(count==1)
185             break;
186           else
187             goto fail;
188         }
189     }
190
191   if(count==0)
192     goto fail;
193
194   if(*idx=='\0' || *idx=='[')
195     {
196       if(require_scheme)
197         return NULL;
198
199       /* Assume HKP if there is no scheme */
200       assume_hkp=1;
201       keyserver->scheme=m_strdup("hkp");
202     }
203   else
204     {
205       int i;
206
207       keyserver->scheme=m_alloc(count+1);
208
209       /* Force to lowercase */
210       for(i=0;i<count;i++)
211         keyserver->scheme[i]=ascii_tolower(uri[i]);
212
213       keyserver->scheme[i]='\0';
214
215       /* Skip past the scheme and colon */
216       uri+=count+1;
217     }
218
219   if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
220     {
221       deprecated_warning(configname,configlineno,"x-broken-hkp",
222                          "--keyserver-options ","broken-http-proxy");
223       m_free(keyserver->scheme);
224       keyserver->scheme=m_strdup("hkp");
225       add_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
226     }
227   else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
228     {
229       /* Canonicalize this to "hkp" so it works with both the internal
230          and external keyserver interface. */
231       m_free(keyserver->scheme);
232       keyserver->scheme=m_strdup("hkp");
233     }
234
235   if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
236     {
237       /* Two slashes means network path. */
238
239       /* Skip over the "//", if any */
240       if(!assume_hkp)
241         uri+=2;
242
243       /* Do we have userinfo auth data present? */
244       for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++)
245         count++;
246
247       /* We found a @ before the slash, so that means everything
248          before the @ is auth data. */
249       if(*idx=='@')
250         {
251           if(count==0)
252             goto fail;
253
254           keyserver->auth=m_alloc(count+1);
255           strncpy(keyserver->auth,uri,count);
256           keyserver->auth[count]='\0';
257           uri+=count+1;
258         }
259
260       /* Is it an RFC-2732 ipv6 [literal address] ? */
261       if(*uri=='[')
262         {
263           for(idx=uri+1,count=1;*idx
264                 && (isxdigit(*idx) || *idx==':' || *idx=='.');idx++)
265             count++;
266
267           /* Is the ipv6 literal address terminated? */
268           if(*idx==']')
269             count++;
270           else
271             goto fail;
272         }
273       else
274         for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
275           count++;
276
277       if(count==0)
278         goto fail;
279
280       keyserver->host=m_alloc(count+1);
281       strncpy(keyserver->host,uri,count);
282       keyserver->host[count]='\0';
283
284       /* Skip past the host */
285       uri+=count;
286
287       if(*uri==':')
288         {
289           /* It would seem to be reasonable to limit the range of the
290              ports to values between 1-65535, but RFC 1738 and 1808
291              imply there is no limit.  Of course, the real world has
292              limits. */
293
294           for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
295             {
296               count++;
297
298               /* Ports are digits only */
299               if(!digitp(idx))
300                 goto fail;
301             }
302
303           keyserver->port=m_alloc(count+1);
304           strncpy(keyserver->port,uri+1,count);
305           keyserver->port[count]='\0';
306
307           /* Skip past the colon and port number */
308           uri+=1+count;
309         }
310
311       /* Everything else is the path */
312       if(*uri)
313         keyserver->path=m_strdup(uri);
314       else
315         keyserver->path=m_strdup("/");
316     }
317   else if(uri[0]!='/')
318     {
319       /* No slash means opaque.  Just record the opaque blob and get
320          out. */
321       keyserver->opaque=m_strdup(uri);
322     }
323   else
324     {
325       /* One slash means absolute path.  We don't need to support that
326          yet. */
327       goto fail;
328     }
329
330   return keyserver;
331
332  fail:
333   free_keyserver_spec(keyserver);
334
335   return NULL;
336 }
337
338 struct keyserver_spec *
339 parse_preferred_keyserver(PKT_signature *sig)
340 {
341   struct keyserver_spec *spec=NULL;
342   const byte *p;
343   size_t plen;
344
345   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
346   if(p && plen)
347     {
348       byte *dupe=m_alloc(plen+1);
349
350       memcpy(dupe,p,plen);
351       dupe[plen]='\0';
352       spec=parse_keyserver_uri(dupe,1,NULL,0);
353       m_free(dupe);
354     }
355
356   return spec;
357 }
358
359 static void
360 print_keyrec(int number,struct keyrec *keyrec)
361 {
362   int i;
363
364   iobuf_writebyte(keyrec->uidbuf,0);
365   iobuf_flush_temp(keyrec->uidbuf);
366   printf("(%d)\t%s  ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
367
368   if(keyrec->size>0)
369     printf("%d bit ",keyrec->size);
370
371   if(keyrec->type)
372     {
373       const char *str=pubkey_algo_to_string(keyrec->type);
374
375       if(str)
376         printf("%s ",str);
377       else
378         printf("unknown ");
379     }
380
381   switch(keyrec->desc.mode)
382     {
383       /* If the keyserver helper gave us a short keyid, we have no
384          choice but to use it.  Do check --keyid-format to add a 0x if
385          needed. */
386     case KEYDB_SEARCH_MODE_SHORT_KID:
387       printf("key %s%08lX",
388              (opt.keyid_format==KF_0xSHORT
389               || opt.keyid_format==KF_0xLONG)?"0x":"",
390              (ulong)keyrec->desc.u.kid[1]);
391       break;
392
393       /* However, if it gave us a long keyid, we can honor
394          --keyid-format */
395     case KEYDB_SEARCH_MODE_LONG_KID:
396       printf("key %s",keystr(keyrec->desc.u.kid));
397       break;
398
399     case KEYDB_SEARCH_MODE_FPR16:
400       printf("key ");
401       for(i=0;i<16;i++)
402         printf("%02X",keyrec->desc.u.fpr[i]);
403       break;
404
405     case KEYDB_SEARCH_MODE_FPR20:
406       printf("key ");
407       for(i=0;i<20;i++)
408         printf("%02X",keyrec->desc.u.fpr[i]);
409       break;
410
411     default:
412       BUG();
413       break;
414     }
415
416   if(keyrec->createtime>0)
417     {
418       printf(", ");
419       printf(_("created: %s"),strtimestamp(keyrec->createtime));
420     }
421
422   if(keyrec->expiretime>0)
423     {
424       printf(", ");
425       printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
426     }
427
428   if(keyrec->flags&1)
429     printf(" (%s)",_("revoked"));
430   if(keyrec->flags&2)
431     printf(" (%s)",_("disabled"));
432   if(keyrec->flags&4)
433     printf(" (%s)",_("expired"));
434
435   printf("\n");
436 }
437
438 /* Returns a keyrec (which must be freed) once a key is complete, and
439    NULL otherwise.  Call with a NULL keystring once key parsing is
440    complete to return any unfinished keys. */
441 static struct keyrec *
442 parse_keyrec(char *keystring)
443 {
444   static struct keyrec *work=NULL;
445   struct keyrec *ret=NULL;
446   char *record;
447   int i;
448
449   if(keystring==NULL)
450     {
451       if(work==NULL)
452         return NULL;
453       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
454         {
455           m_free(work);
456           return NULL;
457         }
458       else
459         {
460           ret=work;
461           work=NULL;
462           return ret;
463         }
464     }
465
466   if(work==NULL)
467     {
468       work=m_alloc_clear(sizeof(struct keyrec));
469       work->uidbuf=iobuf_temp();
470     }
471
472   /* Remove trailing whitespace */
473   for(i=strlen(keystring);i>0;i--)
474     if(ascii_isspace(keystring[i-1]))
475       keystring[i-1]='\0';
476     else
477       break;
478
479   if((record=strsep(&keystring,":"))==NULL)
480     return ret;
481
482   if(ascii_strcasecmp("pub",record)==0)
483     {
484       char *tok;
485
486       if(work->desc.mode)
487         {
488           ret=work;
489           work=m_alloc_clear(sizeof(struct keyrec));
490           work->uidbuf=iobuf_temp();
491         }
492
493       if((tok=strsep(&keystring,":"))==NULL)
494         return ret;
495
496       classify_user_id(tok,&work->desc);
497       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
498          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
499          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
500          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
501         {
502           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
503           return ret;
504         }
505
506       /* Note all items after this are optional.  This allows us to
507          have a pub line as simple as pub:keyid and nothing else. */
508
509       work->lines++;
510
511       if((tok=strsep(&keystring,":"))==NULL)
512         return ret;
513
514       work->type=atoi(tok);
515
516       if((tok=strsep(&keystring,":"))==NULL)
517         return ret;
518
519       work->size=atoi(tok);
520
521       if((tok=strsep(&keystring,":"))==NULL)
522         return ret;
523
524       if(atoi(tok)<=0)
525         work->createtime=0;
526       else
527         work->createtime=atoi(tok);
528
529       if((tok=strsep(&keystring,":"))==NULL)
530         return ret;
531
532       if(atoi(tok)<=0)
533         work->expiretime=0;
534       else
535         {
536           work->expiretime=atoi(tok);
537           /* Force the 'e' flag on if this key is expired. */
538           if(work->expiretime<=make_timestamp())
539             work->flags|=4;
540         }
541
542       if((tok=strsep(&keystring,":"))==NULL)
543         return ret;
544
545       while(*tok)
546         switch(*tok++)
547           {
548           case 'r':
549           case 'R':
550             work->flags|=1;
551             break;
552             
553           case 'd':
554           case 'D':
555             work->flags|=2;
556             break;
557
558           case 'e':
559           case 'E':
560             work->flags|=4;
561             break;
562           }
563     }
564   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
565     {
566       char *userid,*tok,*decoded;
567
568       if((tok=strsep(&keystring,":"))==NULL)
569         return ret;
570
571       if(strlen(tok)==0)
572         return ret;
573
574       userid=tok;
575
576       /* By definition, de-%-encoding is always smaller than the
577          original string so we can decode in place. */
578
579       i=0;
580
581       while(*tok)
582         if(tok[0]=='%' && tok[1] && tok[2])
583           {
584             if((userid[i]=hextobyte(&tok[1]))==-1)
585               userid[i]='?';
586
587             i++;
588             tok+=3;
589           }
590         else
591           userid[i++]=*tok++;
592
593       /* We don't care about the other info provided in the uid: line
594          since no keyserver supports marking userids with timestamps
595          or revoked/expired/disabled yet. */
596
597       /* No need to check for control characters, as utf8_to_native
598          does this for us. */
599
600       decoded=utf8_to_native(userid,i,0);
601       if(strlen(decoded)>opt.screen_columns-10)
602         decoded[opt.screen_columns-10]='\0';
603       iobuf_writestr(work->uidbuf,decoded);
604       m_free(decoded);
605       iobuf_writestr(work->uidbuf,"\n\t");
606       work->lines++;
607     }
608
609   /* Ignore any records other than "pri" and "uid" for easy future
610      growth. */
611
612   return ret;
613 }
614
615 /* TODO: do this as a list sent to keyserver_work rather than calling
616    it once for each key to get the correct counts after the import
617    (cosmetics, really) and to better take advantage of the keyservers
618    that can do multiple fetches in one go (LDAP). */
619 static int
620 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
621 {
622   char *answer;
623
624   if(count && opt.command_fd==-1)
625     {
626       static int from=1;
627       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
628       from=numdesc+1;
629     }
630
631   answer=cpr_get_no_help("keysearch.prompt",
632                          _("Enter number(s), N)ext, or Q)uit > "));
633   /* control-d */
634   if(answer[0]=='\x04')
635     {
636       printf("Q\n");
637       answer[0]='q';
638     }
639
640   if(answer[0]=='q' || answer[0]=='Q')
641     {
642       m_free(answer);
643       return 1;
644     }
645   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
646     {
647       char *split=answer,*num;
648
649       while((num=strsep(&split," ,"))!=NULL)
650         if(atoi(num)>=1 && atoi(num)<=numdesc)
651           keyserver_work(GET,NULL,&desc[atoi(num)-1],1,opt.keyserver);
652
653       m_free(answer);
654       return 1;
655     }
656
657   return 0;
658 }
659
660 /* Count and searchstr are just for cosmetics.  If the count is too
661    small, it will grow safely.  If negative it disables the "Key x-y
662    of z" messages.  searchstr should be UTF-8 (rather than native). */
663 static void
664 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
665 {
666   int i=0,validcount=0,started=0,header=0,count=1;
667   unsigned int maxlen,buflen,numlines=0;
668   KEYDB_SEARCH_DESC *desc;
669   byte *line=NULL;
670   char *localstr=NULL;
671
672   if(searchstr)
673     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
674
675   desc=m_alloc(count*sizeof(KEYDB_SEARCH_DESC));
676
677   for(;;)
678     {
679       struct keyrec *keyrec;
680       int rl;
681
682       maxlen=1024;
683       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
684
685       if(opt.with_colons)
686         {
687           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
688              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
689             {
690               header=1;
691               continue;
692             }
693           else if(ascii_strncasecmp("SEARCH ",line,7)==0
694                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
695             continue;
696
697           printf("%s",line);
698         }
699
700       /* Look for an info: line.  The only current info: values
701          defined are the version and key count. */
702       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
703         {
704           char *tok,*str=&line[5];
705
706           if((tok=strsep(&str,":"))!=NULL)
707             {
708               int version;
709
710               if(sscanf(tok,"%d",&version)!=1)
711                 version=1;
712
713               if(version!=1)
714                 {
715                   log_error(_("invalid keyserver protocol "
716                               "(us %d!=handler %d)\n"),1,version);
717                   break;
718                 }
719             }
720
721           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
722             {
723               if(count==0)
724                 goto notfound;
725               else if(count<0)
726                 count=10;
727               else
728                 validcount=1;
729
730               desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
731             }
732
733           started=1;
734           continue;
735         }
736
737       if(rl==0)
738         {
739           keyrec=parse_keyrec(NULL);
740
741           if(keyrec==NULL)
742             {
743               if(i==0)
744                 {
745                   count=0;
746                   break;
747                 }
748
749               if(i!=count)
750                 validcount=0;
751
752               for(;;)
753                 {
754                   if(show_prompt(desc,i,validcount?count:0,localstr))
755                     break;
756                   validcount=0;
757                 }
758
759               break;
760             }
761         }
762       else
763         keyrec=parse_keyrec(line);
764
765       if(i==count)
766         {
767           /* keyserver helper sent more keys than they claimed in the
768              info: line. */
769           count+=10;
770           desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
771           validcount=0;
772         }
773
774       if(keyrec)
775         {
776           desc[i]=keyrec->desc;
777
778           if(!opt.with_colons)
779             {
780               /* screen_lines - 1 for the prompt. */
781               if(numlines+keyrec->lines>opt.screen_lines-1)
782                 {
783                   if(show_prompt(desc,i,validcount?count:0,localstr))
784                     break;
785                   else
786                     numlines=0;
787                 }
788
789               print_keyrec(i+1,keyrec);
790             }
791
792           numlines+=keyrec->lines;
793           iobuf_close(keyrec->uidbuf);
794           m_free(keyrec);
795
796           started=1;
797           i++;
798         }
799     }
800
801  notfound:
802   if(count==0)
803     {
804       if(localstr)
805         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
806       else
807         log_info(_("key not found on keyserver\n"));
808     }
809
810   m_free(localstr);
811   m_free(desc);
812   m_free(line);
813 }
814
815 /* We sometimes want to use a different gpgkeys_xxx for a given
816    protocol (for example, ldaps is handled by gpgkeys_ldap).  Map
817    these here. */
818 static const char *
819 keyserver_typemap(const char *type)
820 {
821   if(strcmp(type,"ldaps")==0)
822     return "ldap";
823 #ifdef FTP_VIA_LIBCURL
824   else if(strcmp(type,"ftp")==0)
825     return "curl";
826 #endif
827 #ifdef FTPS_VIA_LIBCURL
828   else if(strcmp(type,"ftps")==0)
829     return "curl";
830 #endif
831 #ifdef HTTP_VIA_LIBCURL
832   else if(strcmp(type,"http")==0)
833     return "curl";
834 #endif
835 #ifdef HTTPS_VIA_LIBCURL
836   else if(strcmp(type,"https")==0)
837     return "curl";
838 #endif
839   else
840     return type;
841 }
842
843 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
844 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
845
846 static int 
847 keyserver_spawn(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
848                 int count,int *prog,struct keyserver_spec *keyserver)
849 {
850   int ret=0,i,gotversion=0,outofband=0;
851   STRLIST temp;
852   unsigned int maxlen,buflen;
853   char *command=NULL,*searchstr=NULL;
854   byte *line=NULL;
855   struct parse_options *kopts;
856   struct exec_info *spawn;
857   const char *scheme;
858
859   assert(keyserver);
860
861 #ifdef EXEC_TEMPFILE_ONLY
862   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
863 #endif
864
865   /* Build the filename for the helper to execute */
866   scheme=keyserver_typemap(keyserver->scheme);
867
868 #ifdef DISABLE_KEYSERVER_PATH
869   /* Destroy any path we might have.  This is a little tricky,
870      portability-wise.  It's not correct to delete the PATH
871      environment variable, as that may fall back to a system built-in
872      PATH.  Similarly, it is not correct to set PATH to the null
873      string (PATH="") since this actually deletes the PATH environment
874      variable under MinGW.  The safest thing to do here is to force
875      PATH to be GNUPG_LIBEXECDIR.  All this is not that meaningful on
876      Unix-like systems (since we're going to give a full path to
877      gpgkeys_foo), but on W32 it prevents loading any DLLs from
878      directories in %PATH%. */
879   set_exec_path(GNUPG_LIBEXECDIR,0);
880 #else
881   if(opt.exec_path_set)
882     {
883       /* If exec-path was set, and DISABLE_KEYSERVER_PATH is
884          undefined, then don't specify a full path to gpgkeys_foo, so
885          that the PATH can work. */
886       command=m_alloc(strlen(GPGKEYS_PREFIX)+strlen(scheme)+1);
887       command[0]='\0';
888     }
889   else
890 #endif
891     {
892       /* Specify a full path to gpgkeys_foo. */
893       command=m_alloc(strlen(GNUPG_LIBEXECDIR)+strlen(DIRSEP_S)+
894                       strlen(GPGKEYS_PREFIX)+strlen(scheme)+1);
895       strcpy(command,GNUPG_LIBEXECDIR);
896       strcat(command,DIRSEP_S);
897     }
898
899   strcat(command,GPGKEYS_PREFIX); 
900   strcat(command,scheme);
901
902   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
903     {
904       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
905         {
906           command=m_realloc(command,strlen(command)+
907                             strlen(KEYSERVER_ARGS_KEEP)+1);
908           strcat(command,KEYSERVER_ARGS_KEEP);
909         }
910       else
911         {
912           command=m_realloc(command,strlen(command)+
913                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
914           strcat(command,KEYSERVER_ARGS_NOKEEP);  
915         }
916
917       ret=exec_write(&spawn,NULL,command,NULL,0,0);
918     }
919   else
920     ret=exec_write(&spawn,command,NULL,NULL,0,0);
921
922   if(ret)
923     return ret;
924
925   fprintf(spawn->tochild,
926           "# This is a GnuPG %s keyserver communications file\n",VERSION);
927   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
928   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
929   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
930
931   if(keyserver->opaque)
932     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
933   else
934     {
935       if(keyserver->auth)
936         fprintf(spawn->tochild,"AUTH %s\n",keyserver->auth);
937
938       if(keyserver->host)
939         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
940
941       if(keyserver->port)
942         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
943
944       if(keyserver->path)
945         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
946     }
947
948   /* Write options */
949
950   for(i=0,kopts=keyserver_opts;kopts[i].name;i++)
951     if(opt.keyserver_options.options & kopts[i].bit & REMOTE_TELL)
952       fprintf(spawn->tochild,"OPTION %s\n",kopts[i].name);
953
954   for(temp=opt.keyserver_options.other;temp;temp=temp->next)
955     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
956
957   switch(action)
958     {
959     case GET:
960       {
961         fprintf(spawn->tochild,"COMMAND GET\n\n");
962
963         /* Which keys do we want? */
964
965         for(i=0;i<count;i++)
966           {
967             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
968               {
969                 int f;
970
971                 fprintf(spawn->tochild,"0x");
972
973                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
974                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
975
976                 fprintf(spawn->tochild,"\n");
977               }
978             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
979               {
980                 int f;
981
982                 fprintf(spawn->tochild,"0x");
983
984                 for(f=0;f<16;f++)
985                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
986
987                 fprintf(spawn->tochild,"\n");
988               }
989             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
990               fprintf(spawn->tochild,"0x%08lX%08lX\n",
991                       (ulong)desc[i].u.kid[0],
992                       (ulong)desc[i].u.kid[1]);
993             else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
994               fprintf(spawn->tochild,"0x%08lX\n",
995                       (ulong)desc[i].u.kid[1]);
996             else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
997               continue;
998             else
999               BUG();
1000
1001             if(keyserver->host)
1002               log_info(_("requesting key %s from %s server %s\n"),
1003                        keystr_from_desc(&desc[i]),
1004                        keyserver->scheme,keyserver->host);
1005             else
1006               log_info(_("requesting key %s from %s\n"),
1007                        keystr_from_desc(&desc[i]),keyserver->uri);
1008           }
1009
1010         fprintf(spawn->tochild,"\n");
1011
1012         break;
1013       }
1014
1015     case SEND:
1016       {
1017         STRLIST key;
1018
1019         /* Note the extra \n here to send an empty keylist block */
1020         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
1021
1022         for(key=list;key!=NULL;key=key->next)
1023           {
1024             armor_filter_context_t afx;
1025             IOBUF buffer=iobuf_temp();
1026             KBNODE block;
1027
1028             temp=NULL;
1029             add_to_strlist(&temp,key->d);
1030
1031             memset(&afx,0,sizeof(afx));
1032             afx.what=1;
1033             /* Tell the armor filter to use Unix-style \n line
1034                endings, since we're going to fprintf this to a file
1035                that (on Win32) is open in text mode.  The win32 stdio
1036                will transform the \n to \r\n and we'll end up with the
1037                proper line endings on win32.  This is a no-op on
1038                Unix. */
1039             afx.eol[0]='\n';
1040             iobuf_push_filter(buffer,armor_filter,&afx);
1041
1042             /* TODO: Remove Comment: lines from keys exported this
1043                way? */
1044
1045             if(export_pubkeys_stream(buffer,temp,&block,
1046                                      opt.keyserver_options.export_options)==-1)
1047               iobuf_close(buffer);
1048             else
1049               {
1050                 KBNODE node;
1051
1052                 iobuf_flush_temp(buffer);
1053
1054                 merge_keys_and_selfsig(block);
1055
1056                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
1057                         (ulong)block->pkt->pkt.public_key->keyid[0],
1058                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1059
1060                 for(node=block;node;node=node->next)
1061                   {
1062                     switch(node->pkt->pkttype)
1063                       {
1064                       default:
1065                         continue;
1066
1067                       case PKT_PUBLIC_KEY:
1068                       case PKT_PUBLIC_SUBKEY:
1069                         {
1070                           PKT_public_key *pk=node->pkt->pkt.public_key;
1071
1072                           keyid_from_pk(pk,NULL);
1073
1074                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
1075                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
1076                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
1077                                   pk->pubkey_algo,
1078                                   nbits_from_pk(pk),
1079                                   pk->timestamp,
1080                                   pk->expiredate);
1081
1082                           if(pk->is_revoked)
1083                             fprintf(spawn->tochild,"r");
1084                           if(pk->has_expired)
1085                             fprintf(spawn->tochild,"e");
1086
1087                           fprintf(spawn->tochild,"\n");
1088                         }
1089                         break;
1090
1091                       case PKT_USER_ID:
1092                         {
1093                           PKT_user_id *uid=node->pkt->pkt.user_id;
1094                           int r;
1095
1096                           if(uid->attrib_data)
1097                             continue;
1098
1099                           fprintf(spawn->tochild,"uid:");
1100
1101                           /* Quote ':', '%', and any 8-bit
1102                              characters */
1103                           for(r=0;r<uid->len;r++)
1104                             {
1105                               if(uid->name[r]==':' || uid->name[r]=='%'
1106                                  || uid->name[r]&0x80)
1107                                 fprintf(spawn->tochild,"%%%02X",
1108                                         (byte)uid->name[r]);
1109                               else
1110                                 fprintf(spawn->tochild,"%c",uid->name[r]);
1111                             }
1112
1113                           fprintf(spawn->tochild,":%u:%u:",
1114                                   uid->created,uid->expiredate);
1115
1116                           if(uid->is_revoked)
1117                             fprintf(spawn->tochild,"r");
1118                           if(uid->is_expired)
1119                             fprintf(spawn->tochild,"e");
1120
1121                           fprintf(spawn->tochild,"\n");
1122                         }
1123                         break;
1124
1125                         /* This bit is really for the benefit of
1126                            people who store their keys in LDAP
1127                            servers.  It makes it easy to do queries
1128                            for things like "all keys signed by
1129                            Isabella". */
1130                       case PKT_SIGNATURE:
1131                         {
1132                           PKT_signature *sig=node->pkt->pkt.signature;
1133
1134                           if(!IS_UID_SIG(sig))
1135                             continue;
1136
1137                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1138                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1139                                   sig->sig_class,sig->timestamp,
1140                                   sig->expiredate);
1141                         }
1142                         break;
1143                       }
1144                   }
1145
1146                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1147                         (ulong)block->pkt->pkt.public_key->keyid[0],
1148                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1149
1150                 fprintf(spawn->tochild,"KEY %s BEGIN\n",key->d);
1151                 fwrite(iobuf_get_temp_buffer(buffer),
1152                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1153                 fprintf(spawn->tochild,"KEY %s END\n",key->d);
1154
1155                 iobuf_close(buffer);
1156
1157                 if(keyserver->host)
1158                   log_info(_("sending key %s to %s server %s\n"),
1159                            keystr(block->pkt->pkt.public_key->keyid),
1160                            keyserver->scheme,keyserver->host);
1161                 else
1162                   log_info(_("sending key %s to %s\n"),
1163                            keystr(block->pkt->pkt.public_key->keyid),
1164                            keyserver->uri);
1165
1166                 release_kbnode(block);
1167               }
1168
1169             free_strlist(temp);
1170           }
1171
1172         break;
1173       }
1174
1175     case SEARCH:
1176       {
1177         STRLIST key;
1178
1179         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1180
1181         /* Which keys do we want?  Remember that the gpgkeys_ program
1182            is going to lump these together into a search string. */
1183
1184         for(key=list;key!=NULL;key=key->next)
1185           {
1186             fprintf(spawn->tochild,"%s\n",key->d);
1187             if(key!=list)
1188               {
1189                 searchstr=m_realloc(searchstr,
1190                                     strlen(searchstr)+strlen(key->d)+2);
1191                 strcat(searchstr," ");
1192               }
1193             else
1194               {
1195                 searchstr=m_alloc(strlen(key->d)+1);
1196                 searchstr[0]='\0';
1197               }
1198
1199             strcat(searchstr,key->d);
1200           }
1201
1202         fprintf(spawn->tochild,"\n");
1203
1204         if(keyserver->host)
1205           log_info(_("searching for \"%s\" from %s server %s\n"),
1206                    searchstr,keyserver->scheme,keyserver->host);
1207         else
1208           log_info(_("searching for \"%s\" from %s\n"),
1209                    searchstr,keyserver->uri);
1210
1211         break;
1212       }
1213
1214     default:
1215       log_fatal(_("no keyserver action!\n"));
1216       break;
1217     }
1218
1219   /* Done sending, so start reading. */
1220   ret=exec_read(spawn);
1221   if(ret)
1222     goto fail;
1223
1224   /* Now handle the response */
1225
1226   for(;;)
1227     {
1228       int plen;
1229       char *ptr;
1230
1231       maxlen=1024;
1232       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1233         {
1234           ret=G10ERR_READ_FILE;
1235           goto fail; /* i.e. EOF */
1236         }
1237
1238       ptr=line;
1239
1240       /* remove trailing whitespace */
1241       plen=strlen(ptr);
1242       while(plen>0 && ascii_isspace(ptr[plen-1]))
1243         plen--;
1244       plen[ptr]='\0';
1245
1246       if(*ptr=='\0')
1247         break;
1248
1249       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1250         {
1251           gotversion=1;
1252
1253           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1254             {
1255               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1256                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1257               goto fail;
1258             }
1259         }
1260       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1261         {
1262           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1263             log_info(_("WARNING: keyserver handler from a different"
1264                        " version of GnuPG (%s)\n"),&ptr[8]);
1265         }
1266       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1267         outofband=1; /* Currently the only OPTION */
1268     }
1269
1270   if(!gotversion)
1271     {
1272       log_error(_("keyserver did not send VERSION\n"));
1273       goto fail;
1274     }
1275
1276   if(!outofband)
1277     switch(action)
1278       {
1279       case GET:
1280         {
1281           void *stats_handle;
1282
1283           stats_handle=import_new_stats_handle();
1284
1285           /* Slurp up all the key data.  In the future, it might be
1286              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1287              It's harmless to ignore them, but ignoring them does make
1288              gpg complain about "no valid OpenPGP data found".  One
1289              way to do this could be to continue parsing this
1290              line-by-line and make a temp iobuf for each key. */
1291
1292           import_keys_stream(spawn->fromchild,stats_handle,
1293                              opt.keyserver_options.import_options);
1294
1295           import_print_stats(stats_handle);
1296           import_release_stats_handle(stats_handle);
1297
1298           break;
1299         }
1300
1301         /* Nothing to do here */
1302       case SEND:
1303         break;
1304
1305       case SEARCH:
1306         keyserver_search_prompt(spawn->fromchild,searchstr);
1307         break;
1308
1309       default:
1310         log_fatal(_("no keyserver action!\n"));
1311         break;
1312       }
1313
1314  fail:
1315   m_free(line);
1316   m_free(searchstr);
1317
1318   *prog=exec_finish(spawn);
1319
1320   return ret;
1321 }
1322
1323 static int 
1324 keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
1325                int count,struct keyserver_spec *keyserver)
1326 {
1327   int rc=0,ret=0;
1328
1329   if(!keyserver)
1330     {
1331       log_error(_("no keyserver known (use option --keyserver)\n"));
1332       return G10ERR_BAD_URI;
1333     }
1334
1335 #ifdef DISABLE_KEYSERVER_HELPERS
1336
1337   log_error(_("external keyserver calls are not supported in this build\n"));
1338   return G10ERR_KEYSERVER;
1339
1340 #else
1341   /* Spawn a handler */
1342
1343   rc=keyserver_spawn(action,list,desc,count,&ret,keyserver);
1344   if(ret)
1345     {
1346       switch(ret)
1347         {
1348         case KEYSERVER_SCHEME_NOT_FOUND:
1349           log_error(_("no handler for keyserver scheme `%s'\n"),
1350                     keyserver->scheme);
1351           break;
1352
1353         case KEYSERVER_NOT_SUPPORTED:
1354           log_error(_("action `%s' not supported with keyserver "
1355                       "scheme `%s'\n"),
1356                     action==GET?"get":action==SEND?"send":
1357                     action==SEARCH?"search":"unknown",
1358                     keyserver->scheme);
1359           break;
1360
1361         case KEYSERVER_VERSION_ERROR:
1362           log_error(_(GPGKEYS_PREFIX "%s does not support"
1363                       " handler version %d\n"),
1364                     keyserver_typemap(keyserver->scheme),
1365                     KEYSERVER_PROTO_VERSION);
1366           break;
1367
1368         case KEYSERVER_TIMEOUT:
1369           log_error(_("keyserver timed out\n"));
1370           break;
1371
1372         case KEYSERVER_INTERNAL_ERROR:
1373         default:
1374           log_error(_("keyserver internal error\n"));
1375           break;
1376         }
1377
1378       return G10ERR_KEYSERVER;
1379     }
1380
1381   if(rc)
1382     {
1383       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1384
1385       return rc;
1386     }
1387
1388   return 0;
1389 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1390 }
1391
1392 int 
1393 keyserver_export(STRLIST users)
1394 {
1395   STRLIST sl=NULL;
1396   KEYDB_SEARCH_DESC desc;
1397   int rc=0;
1398
1399   /* Weed out descriptors that we don't support sending */
1400   for(;users;users=users->next)
1401     {
1402       classify_user_id (users->d, &desc);
1403       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1404          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1405          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1406          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1407         {
1408           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1409           continue;
1410         }
1411       else
1412         append_to_strlist(&sl,users->d);
1413     }
1414
1415   if(sl)
1416     {
1417       rc=keyserver_work(SEND,sl,NULL,0,opt.keyserver);
1418       free_strlist(sl);
1419     }
1420
1421   return rc;
1422 }
1423
1424 int 
1425 keyserver_import(STRLIST users)
1426 {
1427   KEYDB_SEARCH_DESC *desc;
1428   int num=100,count=0;
1429   int rc=0;
1430
1431   /* Build a list of key ids */
1432   desc=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1433
1434   for(;users;users=users->next)
1435     {
1436       classify_user_id (users->d, &desc[count]);
1437       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1438          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1439          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1440          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1441         {
1442           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1443           continue;
1444         }
1445
1446       count++;
1447       if(count==num)
1448         {
1449           num+=100;
1450           desc=m_realloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1451         }
1452     }
1453
1454   if(count>0)
1455     rc=keyserver_work(GET,NULL,desc,count,opt.keyserver);
1456
1457   m_free(desc);
1458
1459   return rc;
1460 }
1461
1462 int
1463 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1464                         struct keyserver_spec *keyserver)
1465 {
1466   KEYDB_SEARCH_DESC desc;
1467
1468   memset(&desc,0,sizeof(desc));
1469
1470   if(fprint_len==16)
1471     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1472   else if(fprint_len==20)
1473     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1474   else
1475     return -1;
1476
1477   memcpy(desc.u.fpr,fprint,fprint_len);
1478
1479   return keyserver_work(GET,NULL,&desc,1,keyserver);
1480 }
1481
1482 int 
1483 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1484 {
1485   KEYDB_SEARCH_DESC desc;
1486
1487   memset(&desc,0,sizeof(desc));
1488
1489   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1490   desc.u.kid[0]=keyid[0];
1491   desc.u.kid[1]=keyid[1];
1492
1493   return keyserver_work(GET,NULL,&desc,1,keyserver);
1494 }
1495
1496 /* code mostly stolen from do_export_stream */
1497 static int 
1498 keyidlist(STRLIST users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1499 {
1500   int rc=0,ndesc,num=100;
1501   KBNODE keyblock=NULL,node;
1502   KEYDB_HANDLE kdbhd;
1503   KEYDB_SEARCH_DESC *desc;
1504   STRLIST sl;
1505
1506   *count=0;
1507
1508   *klist=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1509
1510   kdbhd=keydb_new(0);
1511
1512   if(!users)
1513     {
1514       ndesc = 1;
1515       desc = m_alloc_clear ( ndesc * sizeof *desc);
1516       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1517     }
1518   else
1519     {
1520       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
1521         ;
1522       desc = m_alloc ( ndesc * sizeof *desc);
1523         
1524       for (ndesc=0, sl=users; sl; sl = sl->next)
1525         {
1526           if(classify_user_id (sl->d, desc+ndesc))
1527             ndesc++;
1528           else
1529             log_error (_("key \"%s\" not found: %s\n"),
1530                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1531         }
1532     }
1533
1534   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1535     {
1536       if (!users) 
1537         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1538
1539       /* read the keyblock */
1540       rc = keydb_get_keyblock (kdbhd, &keyblock );
1541       if( rc )
1542         {
1543           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1544           goto leave;
1545         }
1546
1547       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1548         {
1549           /* This is to work around a bug in some keyservers (pksd and
1550              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1551              The answer is to refresh both the correct v4 keyid
1552              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1553              This only happens for key refresh using the HKP scheme
1554              and if the refresh-add-fake-v3-keyids keyserver option is
1555              set. */
1556           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1557              node->pkt->pkt.public_key->version>=4)
1558             {
1559               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1560               mpi_get_keyid(node->pkt->pkt.public_key->pkey[0],
1561                             (*klist)[*count].u.kid);
1562               (*count)++;
1563
1564               if(*count==num)
1565                 {
1566                   num+=100;
1567                   *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1568                 }
1569             }
1570
1571           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1572              This is because it's easy to calculate any sort of keyid
1573              from a v4 fingerprint, but not a v3 fingerprint. */
1574
1575           if(node->pkt->pkt.public_key->version<4)
1576             {
1577               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1578               keyid_from_pk(node->pkt->pkt.public_key,
1579                             (*klist)[*count].u.kid);
1580             }
1581           else
1582             {
1583               size_t dummy;
1584
1585               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1586               fingerprint_from_pk(node->pkt->pkt.public_key,
1587                                   (*klist)[*count].u.fpr,&dummy);
1588             }
1589
1590           /* This is a little hackish, using the skipfncvalue as a
1591              void* pointer to the keyserver spec, but we don't need
1592              the skipfnc here, and it saves having an additional field
1593              for this (which would be wasted space most of the
1594              time). */
1595
1596           (*klist)[*count].skipfncvalue=NULL;
1597
1598           /* Are we honoring preferred keyservers? */
1599           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1600             {
1601               PKT_user_id *uid=NULL;
1602               PKT_signature *sig=NULL;
1603
1604               merge_keys_and_selfsig(keyblock);
1605
1606               for(node=node->next;node;node=node->next)
1607                 {
1608                   if(node->pkt->pkttype==PKT_USER_ID
1609                      && node->pkt->pkt.user_id->is_primary)
1610                     uid=node->pkt->pkt.user_id;
1611                   else if(node->pkt->pkttype==PKT_SIGNATURE
1612                           && node->pkt->pkt.signature->
1613                           flags.chosen_selfsig && uid)
1614                     {
1615                       sig=node->pkt->pkt.signature;
1616                       break;
1617                     }
1618                 }
1619
1620               /* Try and parse the keyserver URL.  If it doesn't work,
1621                  then we end up writing NULL which indicates we are
1622                  the same as any other key. */
1623               if(uid && sig)
1624                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1625             }
1626
1627           (*count)++;
1628
1629           if(*count==num)
1630             {
1631               num+=100;
1632               *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1633             }
1634         }
1635     }
1636
1637   if(rc==-1)
1638     rc=0;
1639   
1640  leave:
1641   if(rc)
1642     m_free(*klist);
1643   m_free(desc);
1644   keydb_release(kdbhd);
1645   release_kbnode(keyblock);
1646
1647   return rc;
1648 }
1649
1650 /* Note this is different than the original HKP refresh.  It allows
1651    usernames to refresh only part of the keyring. */
1652
1653 int 
1654 keyserver_refresh(STRLIST users)
1655 {
1656   int rc,count,numdesc,fakev3=0;
1657   KEYDB_SEARCH_DESC *desc;
1658   unsigned int options=opt.keyserver_options.import_options;
1659
1660   /* We switch merge-only on during a refresh, as 'refresh' should
1661      never import new keys, even if their keyids match. */
1662   opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY;
1663
1664   /* Similarly, we switch on fast-import, since refresh may make
1665      multiple import sets (due to preferred keyserver URLs).  We don't
1666      want each set to rebuild the trustdb.  Instead we do it once at
1667      the end here. */
1668   opt.keyserver_options.import_options|=IMPORT_FAST;
1669
1670   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1671      scheme, then enable fake v3 keyid generation. */
1672   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1673      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1674          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1675     fakev3=1;
1676
1677   rc=keyidlist(users,&desc,&numdesc,fakev3);
1678   if(rc)
1679     return rc;
1680
1681   count=numdesc;
1682   if(count>0)
1683     {
1684       int i;
1685
1686       /* Try to handle preferred keyserver keys first */
1687       for(i=0;i<count;i++)
1688         {
1689           if(desc[i].skipfncvalue)
1690             {
1691               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1692
1693               /* We use the keyserver structure we parsed out before.
1694                  Note that a preferred keyserver without a scheme://
1695                  will be interpreted as hkp:// */
1696
1697               rc=keyserver_work(GET,NULL,&desc[i],1,keyserver);
1698               if(rc)
1699                 log_info(_("WARNING: unable to refresh key %s"
1700                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
1701                          keyserver->uri,g10_errstr(rc));
1702               else
1703                 {
1704                   /* We got it, so mark it as NONE so we don't try and
1705                      get it again from the regular keyserver. */
1706
1707                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
1708                   count--;
1709                 }
1710
1711               free_keyserver_spec(keyserver);
1712             }
1713         }
1714     }
1715
1716   if(count>0)
1717     {
1718       if(opt.keyserver)
1719         {
1720           if(count==1)
1721             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
1722           else
1723             log_info(_("refreshing %d keys from %s\n"),
1724                      count,opt.keyserver->uri);
1725         }
1726
1727       rc=keyserver_work(GET,NULL,desc,numdesc,opt.keyserver);
1728     }
1729
1730   m_free(desc);
1731
1732   opt.keyserver_options.import_options=options;
1733
1734   /* If the original options didn't have fast import, and the trustdb
1735      is dirty, rebuild. */
1736   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
1737     trustdb_check_or_update();
1738
1739   return rc;
1740 }
1741
1742 int
1743 keyserver_search(STRLIST tokens)
1744 {
1745   if(tokens)
1746     return keyserver_work(SEARCH,tokens,NULL,0,opt.keyserver);
1747   else
1748     return 0;
1749 }