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