* Makefile.am: No need to link with curl any longer.
[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 #if defined(HAVE_LIBCURL) || defined(FAKE_CURL)
53 #define GPGKEYS_CURL "gpgkeys_curl"
54 #endif
55
56 #ifdef GPGKEYS_CURL
57 #define GPGKEYS_PREFIX_LEN (strlen(GPGKEYS_PREFIX)+strlen(GPGKEYS_CURL))
58 #else
59 #define GPGKEYS_PREFIX_LEN (strlen(GPGKEYS_PREFIX))
60 #endif
61
62 struct keyrec
63 {
64   KEYDB_SEARCH_DESC desc;
65   u32 createtime,expiretime;
66   int size,flags;
67   byte type;
68   IOBUF uidbuf;
69   unsigned int lines;
70 };
71
72 /* Tell remote processes about these options */
73 #define REMOTE_TELL (KEYSERVER_INCLUDE_REVOKED|KEYSERVER_INCLUDE_SUBKEYS|KEYSERVER_TRY_DNS_SRV)
74
75 static struct parse_options keyserver_opts[]=
76   {
77     {"include-revoked",KEYSERVER_INCLUDE_REVOKED,NULL},      
78     {"include-subkeys",KEYSERVER_INCLUDE_SUBKEYS,NULL},
79     {"keep-temp-files",KEYSERVER_KEEP_TEMP_FILES,NULL},
80     {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL},
81     {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL},
82     {"auto-pka-retrieve",KEYSERVER_AUTO_PKA_RETRIEVE,NULL},
83     {"try-dns-srv",KEYSERVER_TRY_DNS_SRV,NULL},
84     {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL},
85     {NULL,0,NULL}
86   };
87
88 static int keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
89                           int count,struct keyserver_spec *keyserver);
90
91 int
92 parse_keyserver_options(char *options)
93 {
94   int ret=1;
95   char *tok;
96
97   while((tok=optsep(&options)))
98     {
99       if(tok[0]=='\0')
100         continue;
101
102       /* For backwards compatibility.  1.2.x used honor-http-proxy and
103          there are a good number of documents published that recommend
104          it. */
105       if(ascii_strcasecmp(tok,"honor-http-proxy")==0)
106         tok="http-proxy";
107       else if(ascii_strcasecmp(tok,"no-honor-http-proxy")==0)
108         tok="no-http-proxy";
109
110       /* We accept quite a few possible options here - some options to
111          handle specially, the keyserver_options list, and import and
112          export options that pertain to keyserver operations.  Note
113          that you must use strncasecmp here as there might be an
114          =argument attached which will foil the use of strcasecmp. */
115
116 #ifdef EXEC_TEMPFILE_ONLY
117       if(ascii_strncasecmp(tok,"use-temp-files",14)==0 ||
118               ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
119         log_info(_("WARNING: keyserver option `%s' is not used"
120                    " on this platform\n"),tok);
121 #else
122       if(ascii_strncasecmp(tok,"use-temp-files",14)==0)
123         opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
124       else if(ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
125         opt.keyserver_options.options&=~KEYSERVER_USE_TEMP_FILES;
126 #endif
127       else if(!parse_options(tok,&opt.keyserver_options.options,
128                              keyserver_opts,0)
129          && !parse_import_options(tok,
130                                   &opt.keyserver_options.import_options,0)
131          && !parse_export_options(tok,
132                                   &opt.keyserver_options.export_options,0))
133         {
134           /* All of the standard options have failed, so the option is
135              destined for a keyserver plugin. */
136           char *arg=argsplit(tok);
137
138           if(arg)
139             {
140               char *joined;
141
142               joined=xmalloc(strlen(tok)+1+strlen(arg)+1);
143               /* Make a canonical name=value form with no
144                  spaces */
145               strcpy(joined,tok);
146               strcat(joined,"=");
147               strcat(joined,arg);
148               add_to_strlist(&opt.keyserver_options.other,joined);
149               xfree(joined);
150             }
151           else
152             add_to_strlist(&opt.keyserver_options.other,tok);
153         }
154     }
155
156   return ret;
157 }
158
159 void
160 free_keyserver_spec(struct keyserver_spec *keyserver)
161 {
162   xfree(keyserver->uri);
163   xfree(keyserver->scheme);
164   xfree(keyserver->auth);
165   xfree(keyserver->host);
166   xfree(keyserver->port);
167   xfree(keyserver->path);
168   xfree(keyserver->opaque);
169   xfree(keyserver);
170 }
171
172 /* TODO: once we cut over to an all-curl world, we don't need this
173    parser any longer so it can be removed, or at least moved to
174    keyserver/ksutil.c for limited use in gpgkeys_ldap or the like. */
175
176 struct keyserver_spec *
177 parse_keyserver_uri(const char *uri,int require_scheme,
178                     const char *configname,unsigned int configlineno)
179 {
180   int assume_hkp=0;
181   struct keyserver_spec *keyserver;
182   const char *idx;
183   int count;
184
185   assert(uri!=NULL);
186
187   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
188
189   keyserver->uri=xstrdup(uri);
190
191   /* Get the scheme */
192
193   for(idx=uri,count=0;*idx && *idx!=':';idx++)
194     {
195       count++;
196
197       /* Do we see the start of an RFC-2732 ipv6 address here?  If so,
198          there clearly isn't a scheme so get out early. */
199       if(*idx=='[')
200         {
201           /* Was the '[' the first thing in the string?  If not, we
202              have a mangled scheme with a [ in it so fail. */
203           if(count==1)
204             break;
205           else
206             goto fail;
207         }
208     }
209
210   if(count==0)
211     goto fail;
212
213   if(*idx=='\0' || *idx=='[')
214     {
215       if(require_scheme)
216         return NULL;
217
218       /* Assume HKP if there is no scheme */
219       assume_hkp=1;
220       keyserver->scheme=xstrdup("hkp");
221     }
222   else
223     {
224       int i;
225
226       keyserver->scheme=xmalloc(count+1);
227
228       /* Force to lowercase */
229       for(i=0;i<count;i++)
230         keyserver->scheme[i]=ascii_tolower(uri[i]);
231
232       keyserver->scheme[i]='\0';
233
234       /* Skip past the scheme and colon */
235       uri+=count+1;
236     }
237
238   if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
239     {
240       deprecated_warning(configname,configlineno,"x-broken-hkp",
241                          "--keyserver-options ","broken-http-proxy");
242       xfree(keyserver->scheme);
243       keyserver->scheme=xstrdup("hkp");
244       add_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
245     }
246   else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
247     {
248       /* Canonicalize this to "hkp" so it works with both the internal
249          and external keyserver interface. */
250       xfree(keyserver->scheme);
251       keyserver->scheme=xstrdup("hkp");
252     }
253
254   if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
255     {
256       /* Two slashes means network path. */
257
258       /* Skip over the "//", if any */
259       if(!assume_hkp)
260         uri+=2;
261
262       /* Do we have userinfo auth data present? */
263       for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++)
264         count++;
265
266       /* We found a @ before the slash, so that means everything
267          before the @ is auth data. */
268       if(*idx=='@')
269         {
270           if(count==0)
271             goto fail;
272
273           keyserver->auth=xmalloc(count+1);
274           strncpy(keyserver->auth,uri,count);
275           keyserver->auth[count]='\0';
276           uri+=count+1;
277         }
278
279       /* Is it an RFC-2732 ipv6 [literal address] ? */
280       if(*uri=='[')
281         {
282           for(idx=uri+1,count=1;*idx
283                 && ((isascii (*idx) && isxdigit(*idx))
284                     || *idx==':' || *idx=='.');idx++)
285             count++;
286
287           /* Is the ipv6 literal address terminated? */
288           if(*idx==']')
289             count++;
290           else
291             goto fail;
292         }
293       else
294         for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
295           count++;
296
297       if(count==0)
298         goto fail;
299
300       keyserver->host=xmalloc(count+1);
301       strncpy(keyserver->host,uri,count);
302       keyserver->host[count]='\0';
303
304       /* Skip past the host */
305       uri+=count;
306
307       if(*uri==':')
308         {
309           /* It would seem to be reasonable to limit the range of the
310              ports to values between 1-65535, but RFC 1738 and 1808
311              imply there is no limit.  Of course, the real world has
312              limits. */
313
314           for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
315             {
316               count++;
317
318               /* Ports are digits only */
319               if(!digitp(idx))
320                 goto fail;
321             }
322
323           keyserver->port=xmalloc(count+1);
324           strncpy(keyserver->port,uri+1,count);
325           keyserver->port[count]='\0';
326
327           /* Skip past the colon and port number */
328           uri+=1+count;
329         }
330
331       /* Everything else is the path */
332       if(*uri)
333         keyserver->path=xstrdup(uri);
334       else
335         keyserver->path=xstrdup("/");
336     }
337   else if(uri[0]!='/')
338     {
339       /* No slash means opaque.  Just record the opaque blob and get
340          out. */
341       keyserver->opaque=xstrdup(uri);
342     }
343   else
344     {
345       /* One slash means absolute path.  We don't need to support that
346          yet. */
347       goto fail;
348     }
349
350   return keyserver;
351
352  fail:
353   free_keyserver_spec(keyserver);
354
355   return NULL;
356 }
357
358 struct keyserver_spec *
359 parse_preferred_keyserver(PKT_signature *sig)
360 {
361   struct keyserver_spec *spec=NULL;
362   const byte *p;
363   size_t plen;
364
365   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
366   if(p && plen)
367     {
368       byte *dupe=xmalloc(plen+1);
369
370       memcpy(dupe,p,plen);
371       dupe[plen]='\0';
372       spec=parse_keyserver_uri(dupe,1,NULL,0);
373       xfree(dupe);
374     }
375
376   return spec;
377 }
378
379 static void
380 print_keyrec(int number,struct keyrec *keyrec)
381 {
382   int i;
383
384   iobuf_writebyte(keyrec->uidbuf,0);
385   iobuf_flush_temp(keyrec->uidbuf);
386   printf("(%d)\t%s  ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
387
388   if(keyrec->size>0)
389     printf("%d bit ",keyrec->size);
390
391   if(keyrec->type)
392     {
393       const char *str=pubkey_algo_to_string(keyrec->type);
394
395       if(str)
396         printf("%s ",str);
397       else
398         printf("unknown ");
399     }
400
401   switch(keyrec->desc.mode)
402     {
403       /* If the keyserver helper gave us a short keyid, we have no
404          choice but to use it.  Do check --keyid-format to add a 0x if
405          needed. */
406     case KEYDB_SEARCH_MODE_SHORT_KID:
407       printf("key %s%08lX",
408              (opt.keyid_format==KF_0xSHORT
409               || opt.keyid_format==KF_0xLONG)?"0x":"",
410              (ulong)keyrec->desc.u.kid[1]);
411       break;
412
413       /* However, if it gave us a long keyid, we can honor
414          --keyid-format */
415     case KEYDB_SEARCH_MODE_LONG_KID:
416       printf("key %s",keystr(keyrec->desc.u.kid));
417       break;
418
419     case KEYDB_SEARCH_MODE_FPR16:
420       printf("key ");
421       for(i=0;i<16;i++)
422         printf("%02X",keyrec->desc.u.fpr[i]);
423       break;
424
425     case KEYDB_SEARCH_MODE_FPR20:
426       printf("key ");
427       for(i=0;i<20;i++)
428         printf("%02X",keyrec->desc.u.fpr[i]);
429       break;
430
431     default:
432       BUG();
433       break;
434     }
435
436   if(keyrec->createtime>0)
437     {
438       printf(", ");
439       printf(_("created: %s"),strtimestamp(keyrec->createtime));
440     }
441
442   if(keyrec->expiretime>0)
443     {
444       printf(", ");
445       printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
446     }
447
448   if(keyrec->flags&1)
449     printf(" (%s)",_("revoked"));
450   if(keyrec->flags&2)
451     printf(" (%s)",_("disabled"));
452   if(keyrec->flags&4)
453     printf(" (%s)",_("expired"));
454
455   printf("\n");
456 }
457
458 /* Returns a keyrec (which must be freed) once a key is complete, and
459    NULL otherwise.  Call with a NULL keystring once key parsing is
460    complete to return any unfinished keys. */
461 static struct keyrec *
462 parse_keyrec(char *keystring)
463 {
464   static struct keyrec *work=NULL;
465   struct keyrec *ret=NULL;
466   char *record;
467   int i;
468
469   if(keystring==NULL)
470     {
471       if(work==NULL)
472         return NULL;
473       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
474         {
475           xfree(work);
476           return NULL;
477         }
478       else
479         {
480           ret=work;
481           work=NULL;
482           return ret;
483         }
484     }
485
486   if(work==NULL)
487     {
488       work=xmalloc_clear(sizeof(struct keyrec));
489       work->uidbuf=iobuf_temp();
490     }
491
492   /* Remove trailing whitespace */
493   for(i=strlen(keystring);i>0;i--)
494     if(ascii_isspace(keystring[i-1]))
495       keystring[i-1]='\0';
496     else
497       break;
498
499   if((record=strsep(&keystring,":"))==NULL)
500     return ret;
501
502   if(ascii_strcasecmp("pub",record)==0)
503     {
504       char *tok;
505
506       if(work->desc.mode)
507         {
508           ret=work;
509           work=xmalloc_clear(sizeof(struct keyrec));
510           work->uidbuf=iobuf_temp();
511         }
512
513       if((tok=strsep(&keystring,":"))==NULL)
514         return ret;
515
516       classify_user_id(tok,&work->desc);
517       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
518          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
519          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
520          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
521         {
522           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
523           return ret;
524         }
525
526       /* Note all items after this are optional.  This allows us to
527          have a pub line as simple as pub:keyid and nothing else. */
528
529       work->lines++;
530
531       if((tok=strsep(&keystring,":"))==NULL)
532         return ret;
533
534       work->type=atoi(tok);
535
536       if((tok=strsep(&keystring,":"))==NULL)
537         return ret;
538
539       work->size=atoi(tok);
540
541       if((tok=strsep(&keystring,":"))==NULL)
542         return ret;
543
544       if(atoi(tok)<=0)
545         work->createtime=0;
546       else
547         work->createtime=atoi(tok);
548
549       if((tok=strsep(&keystring,":"))==NULL)
550         return ret;
551
552       if(atoi(tok)<=0)
553         work->expiretime=0;
554       else
555         {
556           work->expiretime=atoi(tok);
557           /* Force the 'e' flag on if this key is expired. */
558           if(work->expiretime<=make_timestamp())
559             work->flags|=4;
560         }
561
562       if((tok=strsep(&keystring,":"))==NULL)
563         return ret;
564
565       while(*tok)
566         switch(*tok++)
567           {
568           case 'r':
569           case 'R':
570             work->flags|=1;
571             break;
572             
573           case 'd':
574           case 'D':
575             work->flags|=2;
576             break;
577
578           case 'e':
579           case 'E':
580             work->flags|=4;
581             break;
582           }
583     }
584   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
585     {
586       char *userid,*tok,*decoded;
587
588       if((tok=strsep(&keystring,":"))==NULL)
589         return ret;
590
591       if(strlen(tok)==0)
592         return ret;
593
594       userid=tok;
595
596       /* By definition, de-%-encoding is always smaller than the
597          original string so we can decode in place. */
598
599       i=0;
600
601       while(*tok)
602         if(tok[0]=='%' && tok[1] && tok[2])
603           {
604             if((userid[i]=hextobyte(&tok[1]))==-1)
605               userid[i]='?';
606
607             i++;
608             tok+=3;
609           }
610         else
611           userid[i++]=*tok++;
612
613       /* We don't care about the other info provided in the uid: line
614          since no keyserver supports marking userids with timestamps
615          or revoked/expired/disabled yet. */
616
617       /* No need to check for control characters, as utf8_to_native
618          does this for us. */
619
620       decoded=utf8_to_native(userid,i,0);
621       if(strlen(decoded)>opt.screen_columns-10)
622         decoded[opt.screen_columns-10]='\0';
623       iobuf_writestr(work->uidbuf,decoded);
624       xfree(decoded);
625       iobuf_writestr(work->uidbuf,"\n\t");
626       work->lines++;
627     }
628
629   /* Ignore any records other than "pri" and "uid" for easy future
630      growth. */
631
632   return ret;
633 }
634
635 /* TODO: do this as a list sent to keyserver_work rather than calling
636    it once for each key to get the correct counts after the import
637    (cosmetics, really) and to better take advantage of the keyservers
638    that can do multiple fetches in one go (LDAP). */
639 static int
640 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
641 {
642   char *answer;
643
644   if(count && opt.command_fd==-1)
645     {
646       static int from=1;
647       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
648       from=numdesc+1;
649     }
650
651   answer=cpr_get_no_help("keysearch.prompt",
652                          _("Enter number(s), N)ext, or Q)uit > "));
653   /* control-d */
654   if(answer[0]=='\x04')
655     {
656       printf("Q\n");
657       answer[0]='q';
658     }
659
660   if(answer[0]=='q' || answer[0]=='Q')
661     {
662       xfree(answer);
663       return 1;
664     }
665   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
666     {
667       char *split=answer,*num;
668
669       while((num=strsep(&split," ,"))!=NULL)
670         if(atoi(num)>=1 && atoi(num)<=numdesc)
671           keyserver_work(GET,NULL,&desc[atoi(num)-1],1,opt.keyserver);
672
673       xfree(answer);
674       return 1;
675     }
676
677   return 0;
678 }
679
680 /* Count and searchstr are just for cosmetics.  If the count is too
681    small, it will grow safely.  If negative it disables the "Key x-y
682    of z" messages.  searchstr should be UTF-8 (rather than native). */
683 static void
684 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
685 {
686   int i=0,validcount=0,started=0,header=0,count=1;
687   unsigned int maxlen,buflen,numlines=0;
688   KEYDB_SEARCH_DESC *desc;
689   byte *line=NULL;
690   char *localstr=NULL;
691
692   if(searchstr)
693     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
694
695   desc=xmalloc(count*sizeof(KEYDB_SEARCH_DESC));
696
697   for(;;)
698     {
699       struct keyrec *keyrec;
700       int rl;
701
702       maxlen=1024;
703       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
704
705       if(opt.with_colons)
706         {
707           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
708              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
709             {
710               header=1;
711               continue;
712             }
713           else if(ascii_strncasecmp("SEARCH ",line,7)==0
714                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
715             continue;
716
717           printf("%s",line);
718         }
719
720       /* Look for an info: line.  The only current info: values
721          defined are the version and key count. */
722       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
723         {
724           char *tok,*str=&line[5];
725
726           if((tok=strsep(&str,":"))!=NULL)
727             {
728               int version;
729
730               if(sscanf(tok,"%d",&version)!=1)
731                 version=1;
732
733               if(version!=1)
734                 {
735                   log_error(_("invalid keyserver protocol "
736                               "(us %d!=handler %d)\n"),1,version);
737                   break;
738                 }
739             }
740
741           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
742             {
743               if(count==0)
744                 goto notfound;
745               else if(count<0)
746                 count=10;
747               else
748                 validcount=1;
749
750               desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
751             }
752
753           started=1;
754           continue;
755         }
756
757       if(rl==0)
758         {
759           keyrec=parse_keyrec(NULL);
760
761           if(keyrec==NULL)
762             {
763               if(i==0)
764                 {
765                   count=0;
766                   break;
767                 }
768
769               if(i!=count)
770                 validcount=0;
771
772               for(;;)
773                 {
774                   if(show_prompt(desc,i,validcount?count:0,localstr))
775                     break;
776                   validcount=0;
777                 }
778
779               break;
780             }
781         }
782       else
783         keyrec=parse_keyrec(line);
784
785       if(i==count)
786         {
787           /* keyserver helper sent more keys than they claimed in the
788              info: line. */
789           count+=10;
790           desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
791           validcount=0;
792         }
793
794       if(keyrec)
795         {
796           desc[i]=keyrec->desc;
797
798           if(!opt.with_colons)
799             {
800               /* screen_lines - 1 for the prompt. */
801               if(numlines+keyrec->lines>opt.screen_lines-1)
802                 {
803                   if(show_prompt(desc,i,validcount?count:0,localstr))
804                     break;
805                   else
806                     numlines=0;
807                 }
808
809               print_keyrec(i+1,keyrec);
810             }
811
812           numlines+=keyrec->lines;
813           iobuf_close(keyrec->uidbuf);
814           xfree(keyrec);
815
816           started=1;
817           i++;
818         }
819     }
820
821  notfound:
822   /* Leave this commented out or now, and perhaps for a very long
823      time.  All HKPish servers return HTML error messages for
824      no-key-found. */
825   /* 
826      if(!started)
827      log_info(_("keyserver does not support searching\n"));
828      else
829   */
830   if(count==0)
831     {
832       if(localstr)
833         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
834       else
835         log_info(_("key not found on keyserver\n"));
836     }
837
838   xfree(localstr);
839   xfree(desc);
840   xfree(line);
841 }
842
843 /* We sometimes want to use a different gpgkeys_xxx for a given
844    protocol (for example, ldaps is handled by gpgkeys_ldap).  Map
845    these here. */
846 static const char *
847 keyserver_typemap(const char *type)
848 {
849   if(strcmp(type,"ldaps")==0)
850     return "ldap";
851   else
852     return type;
853 }
854
855 #ifdef GPGKEYS_CURL
856 static int
857 curl_cant_handle(const char *scheme)
858 {
859   if(strcmp(scheme,"ldap")==0 || strcmp(scheme,"ldaps")==0)
860     return 1;
861
862   return 0;
863 }
864 #endif
865
866 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
867 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
868
869 static int 
870 keyserver_spawn(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
871                 int count,int *prog,struct keyserver_spec *keyserver)
872 {
873   int ret=0,i,gotversion=0,outofband=0;
874   STRLIST temp;
875   unsigned int maxlen,buflen;
876   char *command,*end,*searchstr=NULL;
877   byte *line=NULL;
878   struct parse_options *kopts;
879   struct exec_info *spawn;
880   const char *scheme;
881   const char *libexecdir = get_libexecdir ();
882
883   assert(keyserver);
884
885 #ifdef EXEC_TEMPFILE_ONLY
886   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
887 #endif
888
889   /* Build the filename for the helper to execute */
890   scheme=keyserver_typemap(keyserver->scheme);
891
892 #ifdef DISABLE_KEYSERVER_PATH
893   /* Destroy any path we might have.  This is a little tricky,
894      portability-wise.  It's not correct to delete the PATH
895      environment variable, as that may fall back to a system built-in
896      PATH.  Similarly, it is not correct to set PATH to the null
897      string (PATH="") since this actually deletes the PATH environment
898      variable under MinGW.  The safest thing to do here is to force
899      PATH to be GNUPG_LIBEXECDIR.  All this is not that meaningful on
900      Unix-like systems (since we're going to give a full path to
901      gpgkeys_foo), but on W32 it prevents loading any DLLs from
902      directories in %PATH%.
903
904      After some more thinking about this we came to the conclusion
905      that it is better to load the helpers from the directory where
906      the program of this process lives.  Fortunately Windows provides
907      a way to retrieve this and our get_libexecdir function has been
908      modified to return just this.  Setting the exec-path is not
909      anymore required.  
910        set_exec_path(libexecdir);
911  */
912 #else
913   if(opt.exec_path_set)
914     {
915       /* If exec-path was set, and DISABLE_KEYSERVER_PATH is
916          undefined, then don't specify a full path to gpgkeys_foo, so
917          that the PATH can work. */
918       command=xmalloc(GPGKEYS_PREFIX_LEN+strlen(scheme)+1);
919       command[0]='\0';
920     }
921   else
922 #endif
923     {
924       /* Specify a full path to gpgkeys_foo. */
925       command=xmalloc(strlen(libexecdir)+strlen(DIRSEP_S)+
926                       GPGKEYS_PREFIX_LEN+strlen(scheme)+1);
927       strcpy(command,libexecdir);
928       strcat(command,DIRSEP_S);
929     }
930
931   end=command+strlen(command);
932
933   strcat(command,GPGKEYS_PREFIX); 
934   strcat(command,scheme);
935
936 #ifdef GPGKEYS_CURL
937   if(!curl_cant_handle(scheme) && path_access(command,X_OK)!=0)
938     strcpy(end,GPGKEYS_CURL);
939 #endif
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=xrealloc(command,strlen(command)+
946                             strlen(KEYSERVER_ARGS_KEEP)+1);
947           strcat(command,KEYSERVER_ARGS_KEEP);
948         }
949       else
950         {
951           command=xrealloc(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   xfree(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=xrealloc(searchstr,
1231                                     strlen(searchstr)+strlen(key->d)+2);
1232                 strcat(searchstr," ");
1233               }
1234             else
1235               {
1236                 searchstr=xmalloc(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=xmalloc(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=xrealloc(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   xfree(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=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1551
1552   kdbhd=keydb_new(0);
1553
1554   if(!users)
1555     {
1556       ndesc = 1;
1557       desc = xmalloc_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 = xmalloc ( 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=xrealloc(*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=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1675             }
1676         }
1677     }
1678
1679   if(rc==-1)
1680     rc=0;
1681   
1682  leave:
1683   if(rc)
1684     xfree(*klist);
1685   xfree(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   xfree(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 }