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