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