* getkey.c (get_seckey_byname2): If no explicit default key is set, don't
[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_SUBKEYS|KEYSERVER_TRY_DNS_SRV)
58
59 static struct parse_options keyserver_opts[]=
60   {
61     {"include-revoked",KEYSERVER_INCLUDE_REVOKED,NULL},      
62     {"include-subkeys",KEYSERVER_INCLUDE_SUBKEYS,NULL},
63     {"keep-temp-files",KEYSERVER_KEEP_TEMP_FILES,NULL},
64     {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL},
65     {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL},
66     {"try-dns-srv",KEYSERVER_TRY_DNS_SRV,NULL},
67     {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL},
68     {NULL,0,NULL}
69   };
70
71 static int keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
72                           int count,struct keyserver_spec *keyserver);
73
74 int
75 parse_keyserver_options(char *options)
76 {
77   int ret=1;
78   char *tok;
79
80   while((tok=optsep(&options)))
81     {
82       if(tok[0]=='\0')
83         continue;
84
85       /* For backwards compatibility.  1.2.x used honor-http-proxy and
86          there are a good number of documents published that recommend
87          it. */
88       if(ascii_strcasecmp(tok,"honor-http-proxy")==0)
89         tok="http-proxy";
90       else if(ascii_strcasecmp(tok,"no-honor-http-proxy")==0)
91         tok="no-http-proxy";
92
93       /* We accept quite a few possible options here - some options to
94          handle specially, the keyserver_options list, and import and
95          export options that pertain to keyserver operations.  Note
96          that you must use strncasecmp here as there might be an
97          =argument attached which will foil the use of strcasecmp. */
98
99 #ifdef EXEC_TEMPFILE_ONLY
100       if(ascii_strncasecmp(tok,"use-temp-files",14)==0 ||
101               ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
102         log_info(_("WARNING: keyserver option `%s' is not used"
103                    " on this platform\n"),tok);
104 #else
105       if(ascii_strncasecmp(tok,"use-temp-files",14)==0)
106         opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
107       else if(ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
108         opt.keyserver_options.options&=~KEYSERVER_USE_TEMP_FILES;
109 #endif
110       else if(!parse_options(tok,&opt.keyserver_options.options,
111                              keyserver_opts,0)
112          && !parse_import_options(tok,
113                                   &opt.keyserver_options.import_options,0)
114          && !parse_export_options(tok,
115                                   &opt.keyserver_options.export_options,0))
116         {
117           /* All of the standard options have failed, so the option is
118              destined for a keyserver plugin. */
119           char *arg=argsplit(tok);
120
121           if(arg)
122             {
123               char *joined;
124
125               joined=m_alloc(strlen(tok)+1+strlen(arg)+1);
126               /* Make a canonical name=value form with no
127                  spaces */
128               strcpy(joined,tok);
129               strcat(joined,"=");
130               strcat(joined,arg);
131               add_to_strlist(&opt.keyserver_options.other,joined);
132               m_free(joined);
133             }
134           else
135             add_to_strlist(&opt.keyserver_options.other,tok);
136         }
137     }
138
139   return ret;
140 }
141
142 void
143 free_keyserver_spec(struct keyserver_spec *keyserver)
144 {
145   m_free(keyserver->uri);
146   m_free(keyserver->scheme);
147   m_free(keyserver->auth);
148   m_free(keyserver->host);
149   m_free(keyserver->port);
150   m_free(keyserver->path);
151   m_free(keyserver->opaque);
152   m_free(keyserver);
153 }
154
155 struct keyserver_spec *
156 parse_keyserver_uri(const char *uri,int require_scheme,
157                     const char *configname,unsigned int configlineno)
158 {
159   int assume_hkp=0;
160   struct keyserver_spec *keyserver;
161   const char *idx;
162   int count;
163
164   assert(uri!=NULL);
165
166   keyserver=m_alloc_clear(sizeof(struct keyserver_spec));
167
168   keyserver->uri=m_strdup(uri);
169
170   /* Get the scheme */
171
172   for(idx=uri,count=0;*idx && *idx!=':';idx++)
173     {
174       count++;
175
176       /* Do we see the start of an RFC-2732 ipv6 address here?  If so,
177          there clearly isn't a scheme so get out early. */
178       if(*idx=='[')
179         {
180           /* Was the '[' the first thing in the string?  If not, we
181              have a mangled scheme with a [ in it so fail. */
182           if(count==1)
183             break;
184           else
185             goto fail;
186         }
187     }
188
189   if(count==0)
190     goto fail;
191
192   if(*idx=='\0' || *idx=='[')
193     {
194       if(require_scheme)
195         return NULL;
196
197       /* Assume HKP if there is no scheme */
198       assume_hkp=1;
199       keyserver->scheme=m_strdup("hkp");
200     }
201   else
202     {
203       int i;
204
205       keyserver->scheme=m_alloc(count+1);
206
207       /* Force to lowercase */
208       for(i=0;i<count;i++)
209         keyserver->scheme[i]=ascii_tolower(uri[i]);
210
211       keyserver->scheme[i]='\0';
212
213       /* Skip past the scheme and colon */
214       uri+=count+1;
215     }
216
217   if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
218     {
219       deprecated_warning(configname,configlineno,"x-broken-hkp",
220                          "--keyserver-options ","broken-http-proxy");
221       m_free(keyserver->scheme);
222       keyserver->scheme=m_strdup("hkp");
223       add_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
224     }
225   else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
226     {
227       /* Canonicalize this to "hkp" so it works with both the internal
228          and external keyserver interface. */
229       m_free(keyserver->scheme);
230       keyserver->scheme=m_strdup("hkp");
231     }
232
233   if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
234     {
235       /* Two slashes means network path. */
236
237       /* Skip over the "//", if any */
238       if(!assume_hkp)
239         uri+=2;
240
241       /* Do we have userinfo auth data present? */
242       for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++)
243         count++;
244
245       /* We found a @ before the slash, so that means everything
246          before the @ is auth data. */
247       if(*idx=='@')
248         {
249           if(count==0)
250             goto fail;
251
252           keyserver->auth=m_alloc(count+1);
253           strncpy(keyserver->auth,uri,count);
254           keyserver->auth[count]='\0';
255           uri+=count+1;
256         }
257
258       /* Is it an RFC-2732 ipv6 [literal address] ? */
259       if(*uri=='[')
260         {
261           for(idx=uri+1,count=1;*idx
262                 && (isxdigit(*idx) || *idx==':' || *idx=='.');idx++)
263             count++;
264
265           /* Is the ipv6 literal address terminated? */
266           if(*idx==']')
267             count++;
268           else
269             goto fail;
270         }
271       else
272         for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
273           count++;
274
275       if(count==0)
276         goto fail;
277
278       keyserver->host=m_alloc(count+1);
279       strncpy(keyserver->host,uri,count);
280       keyserver->host[count]='\0';
281
282       /* Skip past the host */
283       uri+=count;
284
285       if(*uri==':')
286         {
287           /* It would seem to be reasonable to limit the range of the
288              ports to values between 1-65535, but RFC 1738 and 1808
289              imply there is no limit.  Of course, the real world has
290              limits. */
291
292           for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
293             {
294               count++;
295
296               /* Ports are digits only */
297               if(!digitp(idx))
298                 goto fail;
299             }
300
301           keyserver->port=m_alloc(count+1);
302           strncpy(keyserver->port,uri+1,count);
303           keyserver->port[count]='\0';
304
305           /* Skip past the colon and port number */
306           uri+=1+count;
307         }
308
309       /* Everything else is the path */
310       if(*uri)
311         keyserver->path=m_strdup(uri);
312       else
313         keyserver->path=m_strdup("/");
314     }
315   else if(uri[0]!='/')
316     {
317       /* No slash means opaque.  Just record the opaque blob and get
318          out. */
319       keyserver->opaque=m_strdup(uri);
320     }
321   else
322     {
323       /* One slash means absolute path.  We don't need to support that
324          yet. */
325       goto fail;
326     }
327
328   return keyserver;
329
330  fail:
331   free_keyserver_spec(keyserver);
332
333   return NULL;
334 }
335
336 struct keyserver_spec *
337 parse_preferred_keyserver(PKT_signature *sig)
338 {
339   struct keyserver_spec *spec=NULL;
340   const byte *p;
341   size_t plen;
342
343   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
344   if(p && plen)
345     {
346       byte *dupe=m_alloc(plen+1);
347
348       memcpy(dupe,p,plen);
349       dupe[plen]='\0';
350       spec=parse_keyserver_uri(dupe,1,NULL,0);
351       m_free(dupe);
352     }
353
354   return spec;
355 }
356
357 static void
358 print_keyrec(int number,struct keyrec *keyrec)
359 {
360   int i;
361
362   iobuf_writebyte(keyrec->uidbuf,0);
363   iobuf_flush_temp(keyrec->uidbuf);
364   printf("(%d)\t%s  ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
365
366   if(keyrec->size>0)
367     printf("%d bit ",keyrec->size);
368
369   if(keyrec->type)
370     {
371       const char *str=pubkey_algo_to_string(keyrec->type);
372
373       if(str)
374         printf("%s ",str);
375       else
376         printf("unknown ");
377     }
378
379   switch(keyrec->desc.mode)
380     {
381       /* If the keyserver helper gave us a short keyid, we have no
382          choice but to use it.  Do check --keyid-format to add a 0x if
383          needed. */
384     case KEYDB_SEARCH_MODE_SHORT_KID:
385       printf("key %s%08lX",
386              (opt.keyid_format==KF_0xSHORT
387               || opt.keyid_format==KF_0xLONG)?"0x":"",
388              (ulong)keyrec->desc.u.kid[1]);
389       break;
390
391       /* However, if it gave us a long keyid, we can honor
392          --keyid-format */
393     case KEYDB_SEARCH_MODE_LONG_KID:
394       printf("key %s",keystr(keyrec->desc.u.kid));
395       break;
396
397     case KEYDB_SEARCH_MODE_FPR16:
398       printf("key ");
399       for(i=0;i<16;i++)
400         printf("%02X",keyrec->desc.u.fpr[i]);
401       break;
402
403     case KEYDB_SEARCH_MODE_FPR20:
404       printf("key ");
405       for(i=0;i<20;i++)
406         printf("%02X",keyrec->desc.u.fpr[i]);
407       break;
408
409     default:
410       BUG();
411       break;
412     }
413
414   if(keyrec->createtime>0)
415     {
416       printf(", ");
417       printf(_("created: %s"),strtimestamp(keyrec->createtime));
418     }
419
420   if(keyrec->expiretime>0)
421     {
422       printf(", ");
423       printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
424     }
425
426   if(keyrec->flags&1)
427     printf(" (%s)",_("revoked"));
428   if(keyrec->flags&2)
429     printf(" (%s)",_("disabled"));
430   if(keyrec->flags&4)
431     printf(" (%s)",_("expired"));
432
433   printf("\n");
434 }
435
436 /* Returns a keyrec (which must be freed) once a key is complete, and
437    NULL otherwise.  Call with a NULL keystring once key parsing is
438    complete to return any unfinished keys. */
439 static struct keyrec *
440 parse_keyrec(char *keystring)
441 {
442   static struct keyrec *work=NULL;
443   struct keyrec *ret=NULL;
444   char *record;
445   int i;
446
447   if(keystring==NULL)
448     {
449       if(work==NULL)
450         return NULL;
451       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
452         {
453           m_free(work);
454           return NULL;
455         }
456       else
457         {
458           ret=work;
459           work=NULL;
460           return ret;
461         }
462     }
463
464   if(work==NULL)
465     {
466       work=m_alloc_clear(sizeof(struct keyrec));
467       work->uidbuf=iobuf_temp();
468     }
469
470   /* Remove trailing whitespace */
471   for(i=strlen(keystring);i>0;i--)
472     if(ascii_isspace(keystring[i-1]))
473       keystring[i-1]='\0';
474     else
475       break;
476
477   if((record=strsep(&keystring,":"))==NULL)
478     return ret;
479
480   if(ascii_strcasecmp("pub",record)==0)
481     {
482       char *tok;
483
484       if(work->desc.mode)
485         {
486           ret=work;
487           work=m_alloc_clear(sizeof(struct keyrec));
488           work->uidbuf=iobuf_temp();
489         }
490
491       if((tok=strsep(&keystring,":"))==NULL)
492         return ret;
493
494       classify_user_id(tok,&work->desc);
495       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
496          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
497          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
498          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
499         {
500           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
501           return ret;
502         }
503
504       /* Note all items after this are optional.  This allows us to
505          have a pub line as simple as pub:keyid and nothing else. */
506
507       work->lines++;
508
509       if((tok=strsep(&keystring,":"))==NULL)
510         return ret;
511
512       work->type=atoi(tok);
513
514       if((tok=strsep(&keystring,":"))==NULL)
515         return ret;
516
517       work->size=atoi(tok);
518
519       if((tok=strsep(&keystring,":"))==NULL)
520         return ret;
521
522       if(atoi(tok)<=0)
523         work->createtime=0;
524       else
525         work->createtime=atoi(tok);
526
527       if((tok=strsep(&keystring,":"))==NULL)
528         return ret;
529
530       if(atoi(tok)<=0)
531         work->expiretime=0;
532       else
533         {
534           work->expiretime=atoi(tok);
535           /* Force the 'e' flag on if this key is expired. */
536           if(work->expiretime<=make_timestamp())
537             work->flags|=4;
538         }
539
540       if((tok=strsep(&keystring,":"))==NULL)
541         return ret;
542
543       while(*tok)
544         switch(*tok++)
545           {
546           case 'r':
547           case 'R':
548             work->flags|=1;
549             break;
550             
551           case 'd':
552           case 'D':
553             work->flags|=2;
554             break;
555
556           case 'e':
557           case 'E':
558             work->flags|=4;
559             break;
560           }
561     }
562   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
563     {
564       char *userid,*tok,*decoded;
565
566       if((tok=strsep(&keystring,":"))==NULL)
567         return ret;
568
569       if(strlen(tok)==0)
570         return ret;
571
572       userid=tok;
573
574       /* By definition, de-%-encoding is always smaller than the
575          original string so we can decode in place. */
576
577       i=0;
578
579       while(*tok)
580         if(tok[0]=='%' && tok[1] && tok[2])
581           {
582             if((userid[i]=hextobyte(&tok[1]))==-1)
583               userid[i]='?';
584
585             i++;
586             tok+=3;
587           }
588         else
589           userid[i++]=*tok++;
590
591       /* We don't care about the other info provided in the uid: line
592          since no keyserver supports marking userids with timestamps
593          or revoked/expired/disabled yet. */
594
595       /* No need to check for control characters, as utf8_to_native
596          does this for us. */
597
598       decoded=utf8_to_native(userid,i,0);
599       if(strlen(decoded)>opt.screen_columns-10)
600         decoded[opt.screen_columns-10]='\0';
601       iobuf_writestr(work->uidbuf,decoded);
602       m_free(decoded);
603       iobuf_writestr(work->uidbuf,"\n\t");
604       work->lines++;
605     }
606
607   /* Ignore any records other than "pri" and "uid" for easy future
608      growth. */
609
610   return ret;
611 }
612
613 /* TODO: do this as a list sent to keyserver_work rather than calling
614    it once for each key to get the correct counts after the import
615    (cosmetics, really) and to better take advantage of the keyservers
616    that can do multiple fetches in one go (LDAP). */
617 static int
618 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
619 {
620   char *answer;
621
622   if(count && opt.command_fd==-1)
623     {
624       static int from=1;
625       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
626       from=numdesc+1;
627     }
628
629   answer=cpr_get_no_help("keysearch.prompt",
630                          _("Enter number(s), N)ext, or Q)uit > "));
631   /* control-d */
632   if(answer[0]=='\x04')
633     {
634       printf("Q\n");
635       answer[0]='q';
636     }
637
638   if(answer[0]=='q' || answer[0]=='Q')
639     {
640       m_free(answer);
641       return 1;
642     }
643   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
644     {
645       char *split=answer,*num;
646
647       while((num=strsep(&split," ,"))!=NULL)
648         if(atoi(num)>=1 && atoi(num)<=numdesc)
649           keyserver_work(GET,NULL,&desc[atoi(num)-1],1,opt.keyserver);
650
651       m_free(answer);
652       return 1;
653     }
654
655   return 0;
656 }
657
658 /* Count and searchstr are just for cosmetics.  If the count is too
659    small, it will grow safely.  If negative it disables the "Key x-y
660    of z" messages.  searchstr should be UTF-8 (rather than native). */
661 static void
662 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
663 {
664   int i=0,validcount=0,started=0,header=0,count=1;
665   unsigned int maxlen,buflen,numlines=0;
666   KEYDB_SEARCH_DESC *desc;
667   byte *line=NULL;
668   char *localstr=NULL;
669
670   if(searchstr)
671     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
672
673   desc=m_alloc(count*sizeof(KEYDB_SEARCH_DESC));
674
675   for(;;)
676     {
677       struct keyrec *keyrec;
678       int rl;
679
680       maxlen=1024;
681       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
682
683       if(opt.with_colons)
684         {
685           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
686              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
687             {
688               header=1;
689               continue;
690             }
691           else if(ascii_strncasecmp("SEARCH ",line,7)==0
692                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
693             continue;
694
695           printf("%s",line);
696         }
697
698       /* Look for an info: line.  The only current info: values
699          defined are the version and key count. */
700       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
701         {
702           char *tok,*str=&line[5];
703
704           if((tok=strsep(&str,":"))!=NULL)
705             {
706               int version;
707
708               if(sscanf(tok,"%d",&version)!=1)
709                 version=1;
710
711               if(version!=1)
712                 {
713                   log_error(_("invalid keyserver protocol "
714                               "(us %d!=handler %d)\n"),1,version);
715                   break;
716                 }
717             }
718
719           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
720             {
721               if(count==0)
722                 goto notfound;
723               else if(count<0)
724                 count=10;
725               else
726                 validcount=1;
727
728               desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
729             }
730
731           started=1;
732           continue;
733         }
734
735       if(rl==0)
736         {
737           keyrec=parse_keyrec(NULL);
738
739           if(keyrec==NULL)
740             {
741               if(i==0)
742                 {
743                   count=0;
744                   break;
745                 }
746
747               if(i!=count)
748                 validcount=0;
749
750               for(;;)
751                 {
752                   if(show_prompt(desc,i,validcount?count:0,localstr))
753                     break;
754                   validcount=0;
755                 }
756
757               break;
758             }
759         }
760       else
761         keyrec=parse_keyrec(line);
762
763       if(i==count)
764         {
765           /* keyserver helper sent more keys than they claimed in the
766              info: line. */
767           count+=10;
768           desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
769           validcount=0;
770         }
771
772       if(keyrec)
773         {
774           desc[i]=keyrec->desc;
775
776           if(!opt.with_colons)
777             {
778               /* screen_lines - 1 for the prompt. */
779               if(numlines+keyrec->lines>opt.screen_lines-1)
780                 {
781                   if(show_prompt(desc,i,validcount?count:0,localstr))
782                     break;
783                   else
784                     numlines=0;
785                 }
786
787               print_keyrec(i+1,keyrec);
788             }
789
790           numlines+=keyrec->lines;
791           iobuf_close(keyrec->uidbuf);
792           m_free(keyrec);
793
794           started=1;
795           i++;
796         }
797     }
798
799  notfound:
800   if(count==0)
801     {
802       if(localstr)
803         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
804       else
805         log_info(_("key not found on keyserver\n"));
806     }
807
808   m_free(localstr);
809   m_free(desc);
810   m_free(line);
811 }
812
813 /* We sometimes want to use a different gpgkeys_xxx for a given
814    protocol (for example, ldaps is handled by gpgkeys_ldap).  Map
815    these here. */
816 static const char *
817 keyserver_typemap(const char *type)
818 {
819   if(strcmp(type,"ldaps")==0)
820     return "ldap";
821 #ifdef FTP_VIA_LIBCURL
822   else if(strcmp(type,"ftp")==0)
823     return "curl";
824 #endif
825 #ifdef FTPS_VIA_LIBCURL
826   else if(strcmp(type,"ftps")==0)
827     return "curl";
828 #endif
829 #ifdef HTTP_VIA_LIBCURL
830   else if(strcmp(type,"http")==0)
831     return "curl";
832 #endif
833 #ifdef HTTPS_VIA_LIBCURL
834   else if(strcmp(type,"https")==0)
835     return "curl";
836 #endif
837   else
838     return type;
839 }
840
841 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
842 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
843
844 static int 
845 keyserver_spawn(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
846                 int count,int *prog,struct keyserver_spec *keyserver)
847 {
848   int ret=0,i,gotversion=0,outofband=0;
849   STRLIST temp;
850   unsigned int maxlen,buflen;
851   char *command=NULL,*searchstr=NULL;
852   byte *line=NULL;
853   struct parse_options *kopts;
854   struct exec_info *spawn;
855   const char *scheme;
856
857   assert(keyserver);
858
859 #ifdef EXEC_TEMPFILE_ONLY
860   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
861 #endif
862
863   /* Push the libexecdir into path.  If DISABLE_KEYSERVER_PATH is set,
864      use the 0 arg to replace the path. */
865 #ifdef DISABLE_KEYSERVER_PATH
866   set_exec_path(GNUPG_LIBEXECDIR,0);
867 #else
868   set_exec_path(GNUPG_LIBEXECDIR,opt.exec_path_set);
869 #endif
870
871   /* Build the filename for the helper to execute */
872   scheme=keyserver_typemap(keyserver->scheme);
873   command=m_alloc(strlen("gpgkeys_")+strlen(scheme)+1);
874   strcpy(command,"gpgkeys_"); 
875   strcat(command,scheme);
876   
877   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
878     {
879       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
880         {
881           command=m_realloc(command,strlen(command)+
882                             strlen(KEYSERVER_ARGS_KEEP)+1);
883           strcat(command,KEYSERVER_ARGS_KEEP);
884         }
885       else
886         {
887           command=m_realloc(command,strlen(command)+
888                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
889           strcat(command,KEYSERVER_ARGS_NOKEEP);  
890         }
891
892       ret=exec_write(&spawn,NULL,command,NULL,0,0);
893     }
894   else
895     ret=exec_write(&spawn,command,NULL,NULL,0,0);
896
897   if(ret)
898     return ret;
899
900   fprintf(spawn->tochild,
901           "# This is a GnuPG %s keyserver communications file\n",VERSION);
902   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
903   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
904   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
905
906   if(keyserver->opaque)
907     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
908   else
909     {
910       if(keyserver->auth)
911         fprintf(spawn->tochild,"AUTH %s\n",keyserver->auth);
912
913       if(keyserver->host)
914         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
915
916       if(keyserver->port)
917         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
918
919       if(keyserver->path)
920         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
921     }
922
923   /* Write options */
924
925   for(i=0,kopts=keyserver_opts;kopts[i].name;i++)
926     if(opt.keyserver_options.options & kopts[i].bit & REMOTE_TELL)
927       fprintf(spawn->tochild,"OPTION %s\n",kopts[i].name);
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 }