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