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