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