gpg: Limit keysize for unattended key generation to useful values.
[gnupg.git] / g10 / keyserver.c
1 /* keyserver.c - generic keyserver code
2  * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
3  *               2009, 2012 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
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 <errno.h>
28
29 #include "gpg.h"
30 #include "iobuf.h"
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 "ttyio.h"
38 #include "options.h"
39 #include "packet.h"
40 #include "trustdb.h"
41 #include "keyserver-internal.h"
42 #include "util.h"
43 #include "dns-cert.h"
44 #include "pka.h"
45 #ifdef USE_DNS_SRV
46 #include "srv.h"
47 #endif
48
49 #ifdef HAVE_W32_SYSTEM
50 /* It seems Vista doesn't grok X_OK and so fails access() tests.
51    Previous versions interpreted X_OK as F_OK anyway, so we'll just
52    use F_OK directly. */
53 #undef X_OK
54 #define X_OK F_OK
55 #endif /* HAVE_W32_SYSTEM */
56
57 struct keyrec
58 {
59   KEYDB_SEARCH_DESC desc;
60   u32 createtime,expiretime;
61   int size,flags;
62   byte type;
63   IOBUF uidbuf;
64   unsigned int lines;
65 };
66
67 enum ks_action {KS_UNKNOWN=0,KS_GET,KS_GETNAME,KS_SEND,KS_SEARCH};
68
69 static struct parse_options keyserver_opts[]=
70   {
71     /* some of these options are not real - just for the help
72        message */
73     {"max-cert-size",0,NULL,NULL},
74     {"include-revoked",0,NULL,N_("include revoked keys in search results")},
75     {"include-subkeys",0,NULL,N_("include subkeys when searching by key ID")},
76     {"use-temp-files",0,NULL,
77      N_("use temporary files to pass data to keyserver helpers")},
78     {"keep-temp-files",KEYSERVER_KEEP_TEMP_FILES,NULL,
79      N_("do not delete temporary files after using them")},
80     {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL,
81      NULL},
82     {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL,
83      N_("automatically retrieve keys when verifying signatures")},
84     {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL,
85      N_("honor the preferred keyserver URL set on the key")},
86     {"honor-pka-record",KEYSERVER_HONOR_PKA_RECORD,NULL,
87      N_("honor the PKA record set on a key when retrieving keys")},
88     {NULL,0,NULL,NULL}
89   };
90
91 static int keyserver_work(enum ks_action action,strlist_t list,
92                           KEYDB_SEARCH_DESC *desc,int count,
93                           unsigned char **fpr,size_t *fpr_len,
94                           struct keyserver_spec *keyserver);
95
96 /* Reasonable guess */
97 #define DEFAULT_MAX_CERT_SIZE 16384
98
99 static size_t max_cert_size=DEFAULT_MAX_CERT_SIZE;
100
101 static void
102 add_canonical_option(char *option,strlist_t *list)
103 {
104   char *arg=argsplit(option);
105
106   if(arg)
107     {
108       char *joined;
109
110       joined=xmalloc(strlen(option)+1+strlen(arg)+1);
111       /* Make a canonical name=value form with no spaces */
112       strcpy(joined,option);
113       strcat(joined,"=");
114       strcat(joined,arg);
115       append_to_strlist(list,joined);
116       xfree(joined);
117     }
118   else
119     append_to_strlist(list,option);
120 }
121
122 int
123 parse_keyserver_options(char *options)
124 {
125   int ret=1;
126   char *tok;
127   char *max_cert=NULL;
128
129   keyserver_opts[0].value=&max_cert;
130
131   while((tok=optsep(&options)))
132     {
133       if(tok[0]=='\0')
134         continue;
135
136       /* For backwards compatibility.  1.2.x used honor-http-proxy and
137          there are a good number of documents published that recommend
138          it. */
139       if(ascii_strcasecmp(tok,"honor-http-proxy")==0)
140         tok="http-proxy";
141       else if(ascii_strcasecmp(tok,"no-honor-http-proxy")==0)
142         tok="no-http-proxy";
143
144       /* We accept quite a few possible options here - some options to
145          handle specially, the keyserver_options list, and import and
146          export options that pertain to keyserver operations.  Note
147          that you must use strncasecmp here as there might be an
148          =argument attached which will foil the use of strcasecmp. */
149
150 #ifdef EXEC_TEMPFILE_ONLY
151       if(ascii_strncasecmp(tok,"use-temp-files",14)==0 ||
152               ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
153         log_info(_("WARNING: keyserver option `%s' is not used"
154                    " on this platform\n"),tok);
155 #else
156       if(ascii_strncasecmp(tok,"use-temp-files",14)==0)
157         opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
158       else if(ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
159         opt.keyserver_options.options&=~KEYSERVER_USE_TEMP_FILES;
160 #endif
161       else if(!parse_options(tok,&opt.keyserver_options.options,
162                              keyserver_opts,0)
163          && !parse_import_options(tok,
164                                   &opt.keyserver_options.import_options,0)
165          && !parse_export_options(tok,
166                                   &opt.keyserver_options.export_options,0))
167         {
168           /* All of the standard options have failed, so the option is
169              destined for a keyserver plugin. */
170           add_canonical_option(tok,&opt.keyserver_options.other);
171         }
172     }
173
174   if(max_cert)
175     {
176       max_cert_size=strtoul(max_cert,(char **)NULL,10);
177
178       if(max_cert_size==0)
179         max_cert_size=DEFAULT_MAX_CERT_SIZE;
180     }
181
182   return ret;
183 }
184
185 void
186 free_keyserver_spec(struct keyserver_spec *keyserver)
187 {
188   xfree(keyserver->uri);
189   xfree(keyserver->scheme);
190   xfree(keyserver->auth);
191   xfree(keyserver->host);
192   xfree(keyserver->port);
193   xfree(keyserver->path);
194   xfree(keyserver->opaque);
195   free_strlist(keyserver->options);
196   xfree(keyserver);
197 }
198
199 /* Return 0 for match */
200 static int
201 cmp_keyserver_spec(struct keyserver_spec *one,struct keyserver_spec *two)
202 {
203   if(ascii_strcasecmp(one->scheme,two->scheme)==0)
204     {
205       if(one->host && two->host && ascii_strcasecmp(one->host,two->host)==0)
206         {
207           if((one->port && two->port
208               && ascii_strcasecmp(one->port,two->port)==0)
209              || (!one->port && !two->port))
210             return 0;
211         }
212       else if(one->opaque && two->opaque
213               && ascii_strcasecmp(one->opaque,two->opaque)==0)
214         return 0;
215     }
216
217   return 1;
218 }
219
220 /* Try and match one of our keyservers.  If we can, return that.  If
221    we can't, return our input. */
222 struct keyserver_spec *
223 keyserver_match(struct keyserver_spec *spec)
224 {
225   struct keyserver_spec *ks;
226
227   for(ks=opt.keyserver;ks;ks=ks->next)
228     if(cmp_keyserver_spec(spec,ks)==0)
229       return ks;
230
231   return spec;
232 }
233
234 /* TODO: once we cut over to an all-curl world, we don't need this
235    parser any longer so it can be removed, or at least moved to
236    keyserver/ksutil.c for limited use in gpgkeys_ldap or the like. */
237
238 struct keyserver_spec *
239 parse_keyserver_uri(const char *string,int require_scheme,
240                     const char *configname,unsigned int configlineno)
241 {
242   int assume_hkp=0;
243   struct keyserver_spec *keyserver;
244   const char *idx;
245   int count;
246   char *uri,*options;
247
248   assert(string!=NULL);
249
250   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
251
252   uri=xstrdup(string);
253
254   options=strchr(uri,' ');
255   if(options)
256     {
257       char *tok;
258
259       *options='\0';
260       options++;
261
262       while((tok=optsep(&options)))
263         add_canonical_option(tok,&keyserver->options);
264     }
265
266   /* Get the scheme */
267
268   for(idx=uri,count=0;*idx && *idx!=':';idx++)
269     {
270       count++;
271
272       /* Do we see the start of an RFC-2732 ipv6 address here?  If so,
273          there clearly isn't a scheme so get out early. */
274       if(*idx=='[')
275         {
276           /* Was the '[' the first thing in the string?  If not, we
277              have a mangled scheme with a [ in it so fail. */
278           if(count==1)
279             break;
280           else
281             goto fail;
282         }
283     }
284
285   if(count==0)
286     goto fail;
287
288   if(*idx=='\0' || *idx=='[')
289     {
290       if(require_scheme)
291         return NULL;
292
293       /* Assume HKP if there is no scheme */
294       assume_hkp=1;
295       keyserver->scheme=xstrdup("hkp");
296
297       keyserver->uri=xmalloc(strlen(keyserver->scheme)+3+strlen(uri)+1);
298       strcpy(keyserver->uri,keyserver->scheme);
299       strcat(keyserver->uri,"://");
300       strcat(keyserver->uri,uri);
301     }
302   else
303     {
304       int i;
305
306       keyserver->uri=xstrdup(uri);
307
308       keyserver->scheme=xmalloc(count+1);
309
310       /* Force to lowercase */
311       for(i=0;i<count;i++)
312         keyserver->scheme[i]=ascii_tolower(uri[i]);
313
314       keyserver->scheme[i]='\0';
315
316       /* Skip past the scheme and colon */
317       uri+=count+1;
318     }
319
320   if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
321     {
322       deprecated_warning(configname,configlineno,"x-broken-hkp",
323                          "--keyserver-options ","broken-http-proxy");
324       xfree(keyserver->scheme);
325       keyserver->scheme=xstrdup("hkp");
326       append_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
327     }
328   else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
329     {
330       /* Canonicalize this to "hkp" so it works with both the internal
331          and external keyserver interface. */
332       xfree(keyserver->scheme);
333       keyserver->scheme=xstrdup("hkp");
334     }
335
336   if (uri[0]=='/' && uri[1]=='/' && uri[2] == '/')
337     {
338       /* Three slashes means network path with a default host name.
339          This is a hack because it does not crok all possible
340          combiantions.  We should better repalce all code bythe parser
341          from http.c.  */
342       keyserver->path = xstrdup (uri+2);
343     }
344   else if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
345     {
346       /* Two slashes means network path. */
347
348       /* Skip over the "//", if any */
349       if(!assume_hkp)
350         uri+=2;
351
352       /* Do we have userinfo auth data present? */
353       for(idx=uri,count=0;*idx && *idx!='@' && *idx!='/';idx++)
354         count++;
355
356       /* We found a @ before the slash, so that means everything
357          before the @ is auth data. */
358       if(*idx=='@')
359         {
360           if(count==0)
361             goto fail;
362
363           keyserver->auth=xmalloc(count+1);
364           strncpy(keyserver->auth,uri,count);
365           keyserver->auth[count]='\0';
366           uri+=count+1;
367         }
368
369       /* Is it an RFC-2732 ipv6 [literal address] ? */
370       if(*uri=='[')
371         {
372           for(idx=uri+1,count=1;*idx
373                 && ((isascii (*idx) && isxdigit(*idx))
374                     || *idx==':' || *idx=='.');idx++)
375             count++;
376
377           /* Is the ipv6 literal address terminated? */
378           if(*idx==']')
379             count++;
380           else
381             goto fail;
382         }
383       else
384         for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
385           count++;
386
387       if(count==0)
388         goto fail;
389
390       keyserver->host=xmalloc(count+1);
391       strncpy(keyserver->host,uri,count);
392       keyserver->host[count]='\0';
393
394       /* Skip past the host */
395       uri+=count;
396
397       if(*uri==':')
398         {
399           /* It would seem to be reasonable to limit the range of the
400              ports to values between 1-65535, but RFC 1738 and 1808
401              imply there is no limit.  Of course, the real world has
402              limits. */
403
404           for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
405             {
406               count++;
407
408               /* Ports are digits only */
409               if(!digitp(idx))
410                 goto fail;
411             }
412
413           keyserver->port=xmalloc(count+1);
414           strncpy(keyserver->port,uri+1,count);
415           keyserver->port[count]='\0';
416
417           /* Skip past the colon and port number */
418           uri+=1+count;
419         }
420
421       /* Everything else is the path */
422       if(*uri)
423         keyserver->path=xstrdup(uri);
424       else
425         keyserver->path=xstrdup("/");
426
427       if(keyserver->path[1])
428         keyserver->flags.direct_uri=1;
429     }
430   else if(uri[0]!='/')
431     {
432       /* No slash means opaque.  Just record the opaque blob and get
433          out. */
434       keyserver->opaque=xstrdup(uri);
435     }
436   else
437     {
438       /* One slash means absolute path.  We don't need to support that
439          yet. */
440       goto fail;
441     }
442
443   return keyserver;
444
445  fail:
446   free_keyserver_spec(keyserver);
447
448   return NULL;
449 }
450
451 struct keyserver_spec *
452 parse_preferred_keyserver(PKT_signature *sig)
453 {
454   struct keyserver_spec *spec=NULL;
455   const byte *p;
456   size_t plen;
457
458   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
459   if(p && plen)
460     {
461       byte *dupe=xmalloc(plen+1);
462
463       memcpy(dupe,p,plen);
464       dupe[plen]='\0';
465       spec=parse_keyserver_uri(dupe,1,NULL,0);
466       xfree(dupe);
467     }
468
469   return spec;
470 }
471
472 static void
473 print_keyrec(int number,struct keyrec *keyrec)
474 {
475   int i;
476
477   iobuf_writebyte(keyrec->uidbuf,0);
478   iobuf_flush_temp(keyrec->uidbuf);
479   printf("(%d)\t%s  ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
480
481   if(keyrec->size>0)
482     printf("%d bit ",keyrec->size);
483
484   if(keyrec->type)
485     {
486       const char *str;
487
488       str = openpgp_pk_algo_name (keyrec->type);
489       if(str && strcmp (str, "?"))
490         printf("%s ",str);
491       else
492         printf("unknown ");
493     }
494
495   switch(keyrec->desc.mode)
496     {
497       /* If the keyserver helper gave us a short keyid, we have no
498          choice but to use it.  Do check --keyid-format to add a 0x if
499          needed. */
500     case KEYDB_SEARCH_MODE_SHORT_KID:
501       printf("key %s%08lX",
502              (opt.keyid_format==KF_0xSHORT
503               || opt.keyid_format==KF_0xLONG)?"0x":"",
504              (ulong)keyrec->desc.u.kid[1]);
505       break;
506
507       /* However, if it gave us a long keyid, we can honor
508          --keyid-format via keystr(). */
509     case KEYDB_SEARCH_MODE_LONG_KID:
510       printf("key %s",keystr(keyrec->desc.u.kid));
511       break;
512
513       /* If it gave us a PGP 2.x fingerprint, not much we can do
514          beyond displaying it. */
515     case KEYDB_SEARCH_MODE_FPR16:
516       printf("key ");
517       for(i=0;i<16;i++)
518         printf("%02X",keyrec->desc.u.fpr[i]);
519       break;
520
521       /* If we get a modern fingerprint, we have the most
522          flexibility. */
523     case KEYDB_SEARCH_MODE_FPR20:
524       {
525         u32 kid[2];
526         keyid_from_fingerprint(keyrec->desc.u.fpr,20,kid);
527         printf("key %s",keystr(kid));
528       }
529       break;
530
531     default:
532       BUG();
533       break;
534     }
535
536   if(keyrec->createtime>0)
537     {
538       printf(", ");
539       printf(_("created: %s"),strtimestamp(keyrec->createtime));
540     }
541
542   if(keyrec->expiretime>0)
543     {
544       printf(", ");
545       printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
546     }
547
548   if(keyrec->flags&1)
549     printf(" (%s)",_("revoked"));
550   if(keyrec->flags&2)
551     printf(" (%s)",_("disabled"));
552   if(keyrec->flags&4)
553     printf(" (%s)",_("expired"));
554
555   printf("\n");
556 }
557
558 /* Returns a keyrec (which must be freed) once a key is complete, and
559    NULL otherwise.  Call with a NULL keystring once key parsing is
560    complete to return any unfinished keys. */
561 static struct keyrec *
562 parse_keyrec(char *keystring)
563 {
564   static struct keyrec *work=NULL;
565   struct keyrec *ret=NULL;
566   char *record;
567   int i;
568
569   if(keystring==NULL)
570     {
571       if(work==NULL)
572         return NULL;
573       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
574         {
575           xfree(work);
576           return NULL;
577         }
578       else
579         {
580           ret=work;
581           work=NULL;
582           return ret;
583         }
584     }
585
586   if(work==NULL)
587     {
588       work=xmalloc_clear(sizeof(struct keyrec));
589       work->uidbuf=iobuf_temp();
590     }
591
592   /* Remove trailing whitespace */
593   for(i=strlen(keystring);i>0;i--)
594     if(ascii_isspace(keystring[i-1]))
595       keystring[i-1]='\0';
596     else
597       break;
598
599   if((record=strsep(&keystring,":"))==NULL)
600     return ret;
601
602   if(ascii_strcasecmp("pub",record)==0)
603     {
604       char *tok;
605
606       if(work->desc.mode)
607         {
608           ret=work;
609           work=xmalloc_clear(sizeof(struct keyrec));
610           work->uidbuf=iobuf_temp();
611         }
612
613       if((tok=strsep(&keystring,":"))==NULL)
614         return ret;
615
616       classify_user_id(tok,&work->desc);
617       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
618          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
619          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
620          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
621         {
622           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
623           return ret;
624         }
625
626       /* Note all items after this are optional.  This allows us to
627          have a pub line as simple as pub:keyid and nothing else. */
628
629       work->lines++;
630
631       if((tok=strsep(&keystring,":"))==NULL)
632         return ret;
633
634       work->type=atoi(tok);
635
636       if((tok=strsep(&keystring,":"))==NULL)
637         return ret;
638
639       work->size=atoi(tok);
640
641       if((tok=strsep(&keystring,":"))==NULL)
642         return ret;
643
644       if(atoi(tok)<=0)
645         work->createtime=0;
646       else
647         work->createtime=atoi(tok);
648
649       if((tok=strsep(&keystring,":"))==NULL)
650         return ret;
651
652       if(atoi(tok)<=0)
653         work->expiretime=0;
654       else
655         {
656           work->expiretime=atoi(tok);
657           /* Force the 'e' flag on if this key is expired. */
658           if(work->expiretime<=make_timestamp())
659             work->flags|=4;
660         }
661
662       if((tok=strsep(&keystring,":"))==NULL)
663         return ret;
664
665       while(*tok)
666         switch(*tok++)
667           {
668           case 'r':
669           case 'R':
670             work->flags|=1;
671             break;
672
673           case 'd':
674           case 'D':
675             work->flags|=2;
676             break;
677
678           case 'e':
679           case 'E':
680             work->flags|=4;
681             break;
682           }
683     }
684   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
685     {
686       char *userid,*tok,*decoded;
687
688       if((tok=strsep(&keystring,":"))==NULL)
689         return ret;
690
691       if(strlen(tok)==0)
692         return ret;
693
694       userid=tok;
695
696       /* By definition, de-%-encoding is always smaller than the
697          original string so we can decode in place. */
698
699       i=0;
700
701       while(*tok)
702         if(tok[0]=='%' && tok[1] && tok[2])
703           {
704             int c;
705
706             userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c;
707             i++;
708             tok+=3;
709           }
710         else
711           userid[i++]=*tok++;
712
713       /* We don't care about the other info provided in the uid: line
714          since no keyserver supports marking userids with timestamps
715          or revoked/expired/disabled yet. */
716
717       /* No need to check for control characters, as utf8_to_native
718          does this for us. */
719
720       decoded=utf8_to_native(userid,i,0);
721       if(strlen(decoded)>opt.screen_columns-10)
722         decoded[opt.screen_columns-10]='\0';
723       iobuf_writestr(work->uidbuf,decoded);
724       xfree(decoded);
725       iobuf_writestr(work->uidbuf,"\n\t");
726       work->lines++;
727     }
728
729   /* Ignore any records other than "pri" and "uid" for easy future
730      growth. */
731
732   return ret;
733 }
734
735 /* TODO: do this as a list sent to keyserver_work rather than calling
736    it once for each key to get the correct counts after the import
737    (cosmetics, really) and to better take advantage of the keyservers
738    that can do multiple fetches in one go (LDAP). */
739 static int
740 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
741 {
742   char *answer;
743
744   fflush (stdout);
745
746   if(count && opt.command_fd==-1)
747     {
748       static int from=1;
749       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
750       from=numdesc+1;
751     }
752
753   answer=cpr_get_no_help("keysearch.prompt",
754                          _("Enter number(s), N)ext, or Q)uit > "));
755   /* control-d */
756   if(answer[0]=='\x04')
757     {
758       printf("Q\n");
759       answer[0]='q';
760     }
761
762   if(answer[0]=='q' || answer[0]=='Q')
763     {
764       xfree(answer);
765       return 1;
766     }
767   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
768     {
769       char *split=answer,*num;
770
771       while((num=strsep(&split," ,"))!=NULL)
772         if(atoi(num)>=1 && atoi(num)<=numdesc)
773           keyserver_work(KS_GET,NULL,&desc[atoi(num)-1],1,
774                          NULL,NULL,opt.keyserver);
775
776       xfree(answer);
777       return 1;
778     }
779
780   return 0;
781 }
782
783 /* Count and searchstr are just for cosmetics.  If the count is too
784    small, it will grow safely.  If negative it disables the "Key x-y
785    of z" messages.  searchstr should be UTF-8 (rather than native). */
786 static void
787 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
788 {
789   int i=0,validcount=0,started=0,header=0,count=1;
790   unsigned int maxlen,buflen,numlines=0;
791   KEYDB_SEARCH_DESC *desc;
792   byte *line=NULL;
793   char *localstr=NULL;
794
795   if(searchstr)
796     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
797
798   desc=xmalloc(count*sizeof(KEYDB_SEARCH_DESC));
799
800   for(;;)
801     {
802       struct keyrec *keyrec;
803       int rl;
804
805       maxlen=1024;
806       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
807
808       if(opt.with_colons)
809         {
810           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
811              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
812             {
813               header=1;
814               continue;
815             }
816           else if(ascii_strncasecmp("SEARCH ",line,7)==0
817                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
818             continue;
819
820           printf("%s",line);
821         }
822
823       /* Look for an info: line.  The only current info: values
824          defined are the version and key count. */
825       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
826         {
827           char *tok,*str=&line[5];
828
829           if((tok=strsep(&str,":"))!=NULL)
830             {
831               int version;
832
833               if(sscanf(tok,"%d",&version)!=1)
834                 version=1;
835
836               if(version!=1)
837                 {
838                   log_error(_("invalid keyserver protocol "
839                               "(us %d!=handler %d)\n"),1,version);
840                   break;
841                 }
842             }
843
844           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
845             {
846               if(count==0)
847                 goto notfound;
848               else if(count<0)
849                 count=10;
850               else
851                 validcount=1;
852
853               desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
854             }
855
856           started=1;
857           continue;
858         }
859
860       if(rl==0)
861         {
862           keyrec=parse_keyrec(NULL);
863
864           if(keyrec==NULL)
865             {
866               if(i==0)
867                 {
868                   count=0;
869                   break;
870                 }
871
872               if(i!=count)
873                 validcount=0;
874
875               if (opt.with_colons && opt.batch)
876                 break;
877
878               for(;;)
879                 {
880                   if(show_prompt(desc,i,validcount?count:0,localstr))
881                     break;
882                   validcount=0;
883                 }
884
885               break;
886             }
887         }
888       else
889         keyrec=parse_keyrec(line);
890
891       if(i==count)
892         {
893           /* keyserver helper sent more keys than they claimed in the
894              info: line. */
895           count+=10;
896           desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
897           validcount=0;
898         }
899
900       if(keyrec)
901         {
902           desc[i]=keyrec->desc;
903
904           if(!opt.with_colons)
905             {
906               /* screen_lines - 1 for the prompt. */
907               if(numlines+keyrec->lines>opt.screen_lines-1)
908                 {
909                   if(show_prompt(desc,i,validcount?count:0,localstr))
910                     break;
911                   else
912                     numlines=0;
913                 }
914
915               print_keyrec(i+1,keyrec);
916             }
917
918           numlines+=keyrec->lines;
919           iobuf_close(keyrec->uidbuf);
920           xfree(keyrec);
921
922           started=1;
923           i++;
924         }
925     }
926
927  notfound:
928   /* Leave this commented out or now, and perhaps for a very long
929      time.  All HKPish servers return HTML error messages for
930      no-key-found. */
931   /*
932      if(!started)
933      log_info(_("keyserver does not support searching\n"));
934      else
935   */
936   if(count==0)
937     {
938       if(localstr)
939         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
940       else
941         log_info(_("key not found on keyserver\n"));
942     }
943
944   xfree(localstr);
945   xfree(desc);
946   xfree(line);
947 }
948
949 /* We sometimes want to use a different gpgkeys_xxx for a given
950    protocol (for example, ldaps is handled by gpgkeys_ldap).  Map
951    these here. */
952 static const char *
953 keyserver_typemap(const char *type)
954 {
955   if(strcmp(type,"ldaps")==0)
956     return "ldap";
957   else if(strcmp(type,"hkps")==0)
958     return "hkp";
959   else
960     return type;
961 }
962
963 /* The PGP LDAP and the curl fetch-a-LDAP-object methodologies are
964    sufficiently different that we can't use curl to do LDAP. */
965 static int
966 direct_uri_map(const char *scheme,unsigned int is_direct)
967 {
968   if(is_direct && strcmp(scheme,"ldap")==0)
969     return 1;
970
971   return 0;
972 }
973
974 #if GNUPG_MAJOR_VERSION == 2
975 #define GPGKEYS_PREFIX "gpg2keys_"
976 #else
977 #define GPGKEYS_PREFIX "gpgkeys_"
978 #endif
979 #define GPGKEYS_CURL GPGKEYS_PREFIX "curl" EXEEXT
980 #define GPGKEYS_PREFIX_LEN (strlen(GPGKEYS_CURL))
981 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
982 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
983
984
985 /* Structure to convey the arg to keyserver_retrieval_filter.  */
986 struct ks_retrieval_filter_arg_s
987 {
988   KEYDB_SEARCH_DESC *desc;
989   int ndesc;
990 };
991
992
993 /* Check whether a key matches the search description.  The filter
994    returns 0 if the key shall be imported.  Note that this kind of
995    filter is not related to the iobuf filters. */
996 static int
997 keyserver_retrieval_filter (PKT_public_key *pk, PKT_secret_key *sk,
998                             void *opaque)
999 {
1000   struct ks_retrieval_filter_arg_s *arg = opaque;
1001   KEYDB_SEARCH_DESC *desc = arg->desc;
1002   int ndesc = arg->ndesc;
1003   int n;
1004   u32 keyid[2];
1005   byte fpr[MAX_FINGERPRINT_LEN];
1006   size_t fpr_len = 0;
1007
1008   /* Secret keys are not expected from a keyserver.  Do not import.  */
1009   if (sk)
1010     return G10ERR_GENERAL;
1011
1012   if (!ndesc)
1013     return 0; /* Okay if no description given.  */
1014
1015   fingerprint_from_pk (pk, fpr, &fpr_len);
1016   keyid_from_pk (pk, keyid);
1017
1018   /* Compare requested and returned fingerprints if available. */
1019   for (n = 0; n < ndesc; n++)
1020     {
1021       if (desc[n].mode == KEYDB_SEARCH_MODE_FPR20)
1022         {
1023           if (fpr_len == 20 && !memcmp (fpr, desc[n].u.fpr, 20))
1024             return 0;
1025         }
1026       else if (desc[n].mode == KEYDB_SEARCH_MODE_FPR16)
1027         {
1028           if (fpr_len == 16 && !memcmp (fpr, desc[n].u.fpr, 16))
1029             return 0;
1030         }
1031       else if (desc[n].mode == KEYDB_SEARCH_MODE_LONG_KID)
1032         {
1033           if (keyid[0] == desc[n].u.kid[0] && keyid[1] == desc[n].u.kid[1])
1034             return 0;
1035         }
1036       else if (desc[n].mode == KEYDB_SEARCH_MODE_SHORT_KID)
1037         {
1038           if (keyid[1] == desc[n].u.kid[1])
1039             return 0;
1040         }
1041       else
1042         return 0;
1043     }
1044
1045   return G10ERR_GENERAL;
1046 }
1047
1048
1049 static int
1050 keyserver_spawn (enum ks_action action, strlist_t list, KEYDB_SEARCH_DESC *desc,
1051                  int count, int *prog, unsigned char **fpr, size_t *fpr_len,
1052                  struct keyserver_spec *keyserver)
1053 {
1054   int ret=0,i,gotversion=0,outofband=0;
1055   strlist_t temp;
1056   unsigned int maxlen,buflen;
1057   char *command,*end,*searchstr=NULL;
1058   byte *line=NULL;
1059   struct exec_info *spawn;
1060   const char *scheme;
1061   const char *libexecdir = gnupg_libexecdir ();
1062
1063   assert(keyserver);
1064
1065 #ifdef EXEC_TEMPFILE_ONLY
1066   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
1067 #endif
1068
1069   /* Build the filename for the helper to execute */
1070   scheme=keyserver_typemap(keyserver->scheme);
1071
1072 #ifdef DISABLE_KEYSERVER_PATH
1073   /* Destroy any path we might have.  This is a little tricky,
1074      portability-wise.  It's not correct to delete the PATH
1075      environment variable, as that may fall back to a system built-in
1076      PATH.  Similarly, it is not correct to set PATH to the null
1077      string (PATH="") since this actually deletes the PATH environment
1078      variable under MinGW.  The safest thing to do here is to force
1079      PATH to be GNUPG_LIBEXECDIR.  All this is not that meaningful on
1080      Unix-like systems (since we're going to give a full path to
1081      gpgkeys_foo), but on W32 it prevents loading any DLLs from
1082      directories in %PATH%.
1083
1084      After some more thinking about this we came to the conclusion
1085      that it is better to load the helpers from the directory where
1086      the program of this process lives.  Fortunately Windows provides
1087      a way to retrieve this and our gnupg_libexecdir function has been
1088      modified to return just this.  Setting the exec-path is not
1089      anymore required.
1090        set_exec_path(libexecdir);
1091  */
1092 #else
1093   if(opt.exec_path_set)
1094     {
1095       /* If exec-path was set, and DISABLE_KEYSERVER_PATH is
1096          undefined, then don't specify a full path to gpgkeys_foo, so
1097          that the PATH can work. */
1098       command=xmalloc(GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1099       command[0]='\0';
1100     }
1101   else
1102 #endif
1103     {
1104       /* Specify a full path to gpgkeys_foo. */
1105       command=xmalloc(strlen(libexecdir)+strlen(DIRSEP_S)+
1106                       GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1107       strcpy(command,libexecdir);
1108       strcat(command,DIRSEP_S);
1109     }
1110
1111   end=command+strlen(command);
1112
1113   /* Build a path for the keyserver helper.  If it is direct_uri
1114      (i.e. an object fetch and not a keyserver), then add "_uri" to
1115      the end to distinguish the keyserver helper from an object
1116      fetcher that can speak that protocol (this is a problem for
1117      LDAP). */
1118
1119   strcat(command,GPGKEYS_PREFIX);
1120   strcat(command,scheme);
1121
1122   /* This "_uri" thing is in case we need to call a direct handler
1123      instead of the keyserver handler.  This lets us use gpgkeys_curl
1124      or gpgkeys_ldap_uri (we don't provide it, but a user might)
1125      instead of gpgkeys_ldap to fetch things like
1126      ldap://keyserver.pgp.com/o=PGP%20keys?pgpkey?sub?pgpkeyid=99242560 */
1127
1128   if(direct_uri_map(scheme,keyserver->flags.direct_uri))
1129     strcat(command,"_uri");
1130
1131   strcat(command,EXEEXT);
1132
1133   /* Can we execute it?  If not, try curl as our catchall. */
1134   if(path_access(command,X_OK)!=0)
1135     strcpy(end,GPGKEYS_CURL);
1136
1137   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
1138     {
1139       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
1140         {
1141           command=xrealloc(command,strlen(command)+
1142                             strlen(KEYSERVER_ARGS_KEEP)+1);
1143           strcat(command,KEYSERVER_ARGS_KEEP);
1144         }
1145       else
1146         {
1147           command=xrealloc(command,strlen(command)+
1148                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
1149           strcat(command,KEYSERVER_ARGS_NOKEEP);
1150         }
1151
1152       ret=exec_write(&spawn,NULL,command,NULL,0,0);
1153     }
1154   else
1155     ret=exec_write(&spawn,command,NULL,NULL,0,0);
1156
1157   xfree(command);
1158
1159   if(ret)
1160     return ret;
1161
1162   fprintf(spawn->tochild,
1163           "# This is a GnuPG %s keyserver communications file\n",VERSION);
1164   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1165   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
1166   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
1167
1168   if(keyserver->opaque)
1169     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
1170   else
1171     {
1172       if(keyserver->auth)
1173         fprintf(spawn->tochild,"AUTH %s\n",keyserver->auth);
1174
1175       if(keyserver->host)
1176         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
1177
1178       if(keyserver->port)
1179         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
1180
1181       if(keyserver->path)
1182         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
1183     }
1184
1185   /* Write global options */
1186
1187   for(temp=opt.keyserver_options.other;temp;temp=temp->next)
1188     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1189
1190   /* Write per-keyserver options */
1191
1192   for(temp=keyserver->options;temp;temp=temp->next)
1193     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1194
1195   switch(action)
1196     {
1197     case KS_GET:
1198       {
1199         fprintf(spawn->tochild,"COMMAND GET\n\n");
1200
1201         /* Which keys do we want? */
1202
1203         for(i=0;i<count;i++)
1204           {
1205             int quiet=0;
1206
1207             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
1208               {
1209                 int f;
1210
1211                 fprintf(spawn->tochild,"0x");
1212
1213                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
1214                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1215
1216                 fprintf(spawn->tochild,"\n");
1217               }
1218             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
1219               {
1220                 int f;
1221
1222                 fprintf(spawn->tochild,"0x");
1223
1224                 for(f=0;f<16;f++)
1225                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1226
1227                 fprintf(spawn->tochild,"\n");
1228               }
1229             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
1230               fprintf(spawn->tochild,"0x%08lX%08lX\n",
1231                       (ulong)desc[i].u.kid[0],
1232                       (ulong)desc[i].u.kid[1]);
1233             else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
1234               fprintf(spawn->tochild,"0x%08lX\n",
1235                       (ulong)desc[i].u.kid[1]);
1236             else if(desc[i].mode==KEYDB_SEARCH_MODE_EXACT)
1237               {
1238                 fprintf(spawn->tochild,"0x0000000000000000\n");
1239                 quiet=1;
1240               }
1241             else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
1242               continue;
1243             else
1244               BUG();
1245
1246             if(!quiet)
1247               {
1248                 if(keyserver->host)
1249                   log_info(_("requesting key %s from %s server %s\n"),
1250                            keystr_from_desc(&desc[i]),
1251                            keyserver->scheme,keyserver->host);
1252                 else
1253                   log_info(_("requesting key %s from %s\n"),
1254                            keystr_from_desc(&desc[i]),keyserver->uri);
1255               }
1256           }
1257
1258         fprintf(spawn->tochild,"\n");
1259
1260         break;
1261       }
1262
1263     case KS_GETNAME:
1264       {
1265         strlist_t key;
1266
1267         fprintf(spawn->tochild,"COMMAND GETNAME\n\n");
1268
1269         /* Which names do we want? */
1270
1271         for(key=list;key!=NULL;key=key->next)
1272           fprintf(spawn->tochild,"%s\n",key->d);
1273
1274         fprintf(spawn->tochild,"\n");
1275
1276         if(keyserver->host)
1277           log_info(_("searching for names from %s server %s\n"),
1278                    keyserver->scheme,keyserver->host);
1279         else
1280           log_info(_("searching for names from %s\n"),keyserver->uri);
1281
1282         break;
1283       }
1284
1285     case KS_SEND:
1286       {
1287         strlist_t key;
1288
1289         /* Note the extra \n here to send an empty keylist block */
1290         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
1291
1292         for(key=list;key!=NULL;key=key->next)
1293           {
1294             armor_filter_context_t *afx;
1295             IOBUF buffer = iobuf_temp ();
1296             KBNODE block;
1297
1298             temp=NULL;
1299             add_to_strlist(&temp,key->d);
1300
1301             afx = new_armor_context ();
1302             afx->what = 1;
1303             /* Tell the armor filter to use Unix-style \n line
1304                endings, since we're going to fprintf this to a file
1305                that (on Win32) is open in text mode.  The win32 stdio
1306                will transform the \n to \r\n and we'll end up with the
1307                proper line endings on win32.  This is a no-op on
1308                Unix. */
1309             afx->eol[0] = '\n';
1310             push_armor_filter (afx, buffer);
1311             release_armor_context (afx);
1312
1313             /* TODO: Remove Comment: lines from keys exported this
1314                way? */
1315
1316             if(export_pubkeys_stream(buffer,temp,&block,
1317                                      opt.keyserver_options.export_options)==-1)
1318               iobuf_close(buffer);
1319             else
1320               {
1321                 KBNODE node;
1322
1323                 iobuf_flush_temp(buffer);
1324
1325                 merge_keys_and_selfsig(block);
1326
1327                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
1328                         (ulong)block->pkt->pkt.public_key->keyid[0],
1329                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1330
1331                 for(node=block;node;node=node->next)
1332                   {
1333                     switch(node->pkt->pkttype)
1334                       {
1335                       default:
1336                         continue;
1337
1338                       case PKT_PUBLIC_KEY:
1339                       case PKT_PUBLIC_SUBKEY:
1340                         {
1341                           PKT_public_key *pk=node->pkt->pkt.public_key;
1342
1343                           keyid_from_pk(pk,NULL);
1344
1345                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
1346                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
1347                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
1348                                   pk->pubkey_algo,
1349                                   nbits_from_pk(pk),
1350                                   pk->timestamp,
1351                                   pk->expiredate);
1352
1353                           if(pk->is_revoked)
1354                             fprintf(spawn->tochild,"r");
1355                           if(pk->has_expired)
1356                             fprintf(spawn->tochild,"e");
1357
1358                           fprintf(spawn->tochild,"\n");
1359                         }
1360                         break;
1361
1362                       case PKT_USER_ID:
1363                         {
1364                           PKT_user_id *uid=node->pkt->pkt.user_id;
1365                           int r;
1366
1367                           if(uid->attrib_data)
1368                             continue;
1369
1370                           fprintf(spawn->tochild,"uid:");
1371
1372                           /* Quote ':', '%', and any 8-bit
1373                              characters */
1374                           for(r=0;r<uid->len;r++)
1375                             {
1376                               if(uid->name[r]==':' || uid->name[r]=='%'
1377                                  || uid->name[r]&0x80)
1378                                 fprintf(spawn->tochild,"%%%02X",
1379                                         (byte)uid->name[r]);
1380                               else
1381                                 fprintf(spawn->tochild,"%c",uid->name[r]);
1382                             }
1383
1384                           fprintf(spawn->tochild,":%u:%u:",
1385                                   uid->created,uid->expiredate);
1386
1387                           if(uid->is_revoked)
1388                             fprintf(spawn->tochild,"r");
1389                           if(uid->is_expired)
1390                             fprintf(spawn->tochild,"e");
1391
1392                           fprintf(spawn->tochild,"\n");
1393                         }
1394                         break;
1395
1396                         /* This bit is really for the benefit of
1397                            people who store their keys in LDAP
1398                            servers.  It makes it easy to do queries
1399                            for things like "all keys signed by
1400                            Isabella". */
1401                       case PKT_SIGNATURE:
1402                         {
1403                           PKT_signature *sig=node->pkt->pkt.signature;
1404
1405                           if(!IS_UID_SIG(sig))
1406                             continue;
1407
1408                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1409                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1410                                   sig->sig_class,sig->timestamp,
1411                                   sig->expiredate);
1412                         }
1413                         break;
1414                       }
1415                   }
1416
1417                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1418                         (ulong)block->pkt->pkt.public_key->keyid[0],
1419                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1420
1421                 fprintf(spawn->tochild,"KEY %08lX%08lX BEGIN\n",
1422                         (ulong)block->pkt->pkt.public_key->keyid[0],
1423                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1424                 fwrite(iobuf_get_temp_buffer(buffer),
1425                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1426                 fprintf(spawn->tochild,"KEY %08lX%08lX END\n",
1427                         (ulong)block->pkt->pkt.public_key->keyid[0],
1428                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1429
1430                 iobuf_close(buffer);
1431
1432                 if(keyserver->host)
1433                   log_info(_("sending key %s to %s server %s\n"),
1434                            keystr(block->pkt->pkt.public_key->keyid),
1435                            keyserver->scheme,keyserver->host);
1436                 else
1437                   log_info(_("sending key %s to %s\n"),
1438                            keystr(block->pkt->pkt.public_key->keyid),
1439                            keyserver->uri);
1440
1441                 release_kbnode(block);
1442               }
1443
1444             free_strlist(temp);
1445           }
1446
1447         break;
1448       }
1449
1450     case KS_SEARCH:
1451       {
1452         strlist_t key;
1453
1454         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1455
1456         /* Which keys do we want?  Remember that the gpgkeys_ program
1457            is going to lump these together into a search string. */
1458
1459         for(key=list;key!=NULL;key=key->next)
1460           {
1461             fprintf(spawn->tochild,"%s\n",key->d);
1462             if(key!=list)
1463               {
1464                 searchstr=xrealloc(searchstr,
1465                                     strlen(searchstr)+strlen(key->d)+2);
1466                 strcat(searchstr," ");
1467               }
1468             else
1469               {
1470                 searchstr=xmalloc(strlen(key->d)+1);
1471                 searchstr[0]='\0';
1472               }
1473
1474             strcat(searchstr,key->d);
1475           }
1476
1477         fprintf(spawn->tochild,"\n");
1478
1479         if(keyserver->host)
1480           log_info(_("searching for \"%s\" from %s server %s\n"),
1481                    searchstr,keyserver->scheme,keyserver->host);
1482         else
1483           log_info(_("searching for \"%s\" from %s\n"),
1484                    searchstr,keyserver->uri);
1485
1486         break;
1487       }
1488
1489     default:
1490       log_fatal(_("no keyserver action!\n"));
1491       break;
1492     }
1493
1494   /* Done sending, so start reading. */
1495   ret=exec_read(spawn);
1496   if(ret)
1497     goto fail;
1498
1499   /* Now handle the response */
1500
1501   for(;;)
1502     {
1503       int plen;
1504       char *ptr;
1505
1506       maxlen=1024;
1507       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1508         {
1509           ret = gpg_error_from_syserror ();
1510           goto fail; /* i.e. EOF */
1511         }
1512
1513       ptr=line;
1514
1515       /* remove trailing whitespace */
1516       plen=strlen(ptr);
1517       while(plen>0 && ascii_isspace(ptr[plen-1]))
1518         plen--;
1519       plen[ptr]='\0';
1520
1521       if(*ptr=='\0')
1522         break;
1523
1524       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1525         {
1526           gotversion=1;
1527
1528           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1529             {
1530               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1531                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1532               goto fail;
1533             }
1534         }
1535       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1536         {
1537           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1538             log_info(_("WARNING: keyserver handler from a different"
1539                        " version of GnuPG (%s)\n"),&ptr[8]);
1540         }
1541       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1542         outofband=1; /* Currently the only OPTION */
1543     }
1544
1545   if(!gotversion)
1546     {
1547       log_error(_("keyserver did not send VERSION\n"));
1548       goto fail;
1549     }
1550
1551   if(!outofband)
1552     switch(action)
1553       {
1554       case KS_GET:
1555       case KS_GETNAME:
1556         {
1557           void *stats_handle;
1558           struct ks_retrieval_filter_arg_s filterarg;
1559
1560           stats_handle=import_new_stats_handle();
1561
1562           /* Slurp up all the key data.  In the future, it might be
1563              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1564              It's harmless to ignore them, but ignoring them does make
1565              gpg complain about "no valid OpenPGP data found".  One
1566              way to do this could be to continue parsing this
1567              line-by-line and make a temp iobuf for each key.  Note
1568              that we don't allow the import of secret keys from a
1569              keyserver.  Keyservers should never accept or send them
1570              but we better protect against rogue keyservers. */
1571           filterarg.desc = desc;
1572           filterarg.ndesc = count;
1573           import_keys_stream (spawn->fromchild, stats_handle, fpr, fpr_len,
1574                              (opt.keyserver_options.import_options
1575                               | IMPORT_NO_SECKEY),
1576                               keyserver_retrieval_filter, &filterarg);
1577
1578           import_print_stats(stats_handle);
1579           import_release_stats_handle(stats_handle);
1580
1581           break;
1582         }
1583
1584         /* Nothing to do here */
1585       case KS_SEND:
1586         break;
1587
1588       case KS_SEARCH:
1589         keyserver_search_prompt(spawn->fromchild,searchstr);
1590         break;
1591
1592       default:
1593         log_fatal(_("no keyserver action!\n"));
1594         break;
1595       }
1596
1597  fail:
1598   xfree(line);
1599   xfree(searchstr);
1600
1601
1602   *prog=exec_finish(spawn);
1603
1604   return ret;
1605 }
1606
1607
1608 static int
1609 keyserver_work (enum ks_action action, strlist_t list, KEYDB_SEARCH_DESC *desc,
1610                 int count, unsigned char **fpr, size_t *fpr_len,
1611                 struct keyserver_spec *keyserver)
1612 {
1613   int rc = 0;
1614   int ret = 0;
1615
1616   if(!keyserver)
1617     {
1618       log_error(_("no keyserver known (use option --keyserver)\n"));
1619       return G10ERR_BAD_URI;
1620     }
1621
1622 #ifdef DISABLE_KEYSERVER_HELPERS
1623
1624   log_error(_("external keyserver calls are not supported in this build\n"));
1625   return G10ERR_KEYSERVER;
1626
1627 #else
1628   /* Spawn a handler */
1629
1630   rc=keyserver_spawn(action,list,desc,count,&ret,fpr,fpr_len,keyserver);
1631   if(ret)
1632     {
1633       switch(ret)
1634         {
1635         case KEYSERVER_SCHEME_NOT_FOUND:
1636           log_error(_("no handler for keyserver scheme `%s'\n"),
1637                     keyserver->scheme);
1638           break;
1639
1640         case KEYSERVER_NOT_SUPPORTED:
1641           log_error(_("action `%s' not supported with keyserver "
1642                       "scheme `%s'\n"),
1643                     action==KS_GET?"get":action==KS_SEND?"send":
1644                     action==KS_SEARCH?"search":"unknown",
1645                     keyserver->scheme);
1646           break;
1647
1648         case KEYSERVER_VERSION_ERROR:
1649           log_error(_(GPGKEYS_PREFIX "%s does not support"
1650                       " handler version %d\n"),
1651                     keyserver_typemap(keyserver->scheme),
1652                     KEYSERVER_PROTO_VERSION);
1653           break;
1654
1655         case KEYSERVER_TIMEOUT:
1656           log_error(_("keyserver timed out\n"));
1657           break;
1658
1659         case KEYSERVER_INTERNAL_ERROR:
1660         default:
1661           log_error(_("keyserver internal error\n"));
1662           break;
1663         }
1664
1665       return G10ERR_KEYSERVER;
1666     }
1667
1668   if(rc)
1669     {
1670       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1671
1672       return rc;
1673     }
1674
1675   return 0;
1676 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1677 }
1678
1679
1680 int
1681 keyserver_export(strlist_t users)
1682 {
1683   strlist_t sl=NULL;
1684   KEYDB_SEARCH_DESC desc;
1685   int rc=0;
1686
1687   /* Weed out descriptors that we don't support sending */
1688   for(;users;users=users->next)
1689     {
1690       classify_user_id (users->d, &desc);
1691       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1692          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1693          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1694          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1695         {
1696           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1697           continue;
1698         }
1699       else
1700         append_to_strlist(&sl,users->d);
1701     }
1702
1703   if(sl)
1704     {
1705       rc=keyserver_work(KS_SEND,sl,NULL,0,NULL,NULL,opt.keyserver);
1706       free_strlist(sl);
1707     }
1708
1709   return rc;
1710 }
1711
1712
1713 int
1714 keyserver_import(strlist_t users)
1715 {
1716   KEYDB_SEARCH_DESC *desc;
1717   int num=100,count=0;
1718   int rc=0;
1719
1720   /* Build a list of key ids */
1721   desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1722
1723   for(;users;users=users->next)
1724     {
1725       classify_user_id (users->d, &desc[count]);
1726       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1727          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1728          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1729          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1730         {
1731           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1732           continue;
1733         }
1734
1735       count++;
1736       if(count==num)
1737         {
1738           num+=100;
1739           desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1740         }
1741     }
1742
1743   if(count>0)
1744     rc=keyserver_work(KS_GET,NULL,desc,count,NULL,NULL,opt.keyserver);
1745
1746   xfree(desc);
1747
1748   return rc;
1749 }
1750
1751 int
1752 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1753                         struct keyserver_spec *keyserver)
1754 {
1755   KEYDB_SEARCH_DESC desc;
1756
1757   memset(&desc,0,sizeof(desc));
1758
1759   if(fprint_len==16)
1760     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1761   else if(fprint_len==20)
1762     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1763   else
1764     return -1;
1765
1766   memcpy(desc.u.fpr,fprint,fprint_len);
1767
1768   /* TODO: Warn here if the fingerprint we got doesn't match the one
1769      we asked for? */
1770   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1771 }
1772
1773 int
1774 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1775 {
1776   KEYDB_SEARCH_DESC desc;
1777
1778   memset(&desc,0,sizeof(desc));
1779
1780   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1781   desc.u.kid[0]=keyid[0];
1782   desc.u.kid[1]=keyid[1];
1783
1784   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1785 }
1786
1787
1788 /* Code mostly stolen from do_export_stream */
1789 static int
1790 keyidlist(strlist_t users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1791 {
1792   int rc = 0;
1793   int num = 100;
1794   int ndesc;
1795   KBNODE keyblock=NULL,node;
1796   KEYDB_HANDLE kdbhd;
1797   KEYDB_SEARCH_DESC *desc;
1798   strlist_t sl;
1799
1800   *count=0;
1801
1802   *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1803
1804   kdbhd=keydb_new(0);
1805
1806   if(!users)
1807     {
1808       ndesc = 1;
1809       desc = xmalloc_clear ( ndesc * sizeof *desc);
1810       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1811     }
1812   else
1813     {
1814       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1815         ;
1816       desc = xmalloc ( ndesc * sizeof *desc);
1817
1818       for (ndesc=0, sl=users; sl; sl = sl->next)
1819         {
1820           if(classify_user_id (sl->d, desc+ndesc))
1821             ndesc++;
1822           else
1823             log_error (_("key \"%s\" not found: %s\n"),
1824                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1825         }
1826     }
1827
1828   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1829     {
1830       if (!users)
1831         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1832
1833       /* read the keyblock */
1834       rc = keydb_get_keyblock (kdbhd, &keyblock );
1835       if( rc )
1836         {
1837           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1838           goto leave;
1839         }
1840
1841       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1842         {
1843           /* This is to work around a bug in some keyservers (pksd and
1844              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1845              The answer is to refresh both the correct v4 keyid
1846              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1847              This only happens for key refresh using the HKP scheme
1848              and if the refresh-add-fake-v3-keyids keyserver option is
1849              set. */
1850           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1851              node->pkt->pkt.public_key->version>=4)
1852             {
1853               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1854               v3_keyid (node->pkt->pkt.public_key->pkey[0],
1855                         (*klist)[*count].u.kid);
1856               (*count)++;
1857
1858               if(*count==num)
1859                 {
1860                   num+=100;
1861                   *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1862                 }
1863             }
1864
1865           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1866              This is because it's easy to calculate any sort of keyid
1867              from a v4 fingerprint, but not a v3 fingerprint. */
1868
1869           if(node->pkt->pkt.public_key->version<4)
1870             {
1871               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1872               keyid_from_pk(node->pkt->pkt.public_key,
1873                             (*klist)[*count].u.kid);
1874             }
1875           else
1876             {
1877               size_t dummy;
1878
1879               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1880               fingerprint_from_pk(node->pkt->pkt.public_key,
1881                                   (*klist)[*count].u.fpr,&dummy);
1882             }
1883
1884           /* This is a little hackish, using the skipfncvalue as a
1885              void* pointer to the keyserver spec, but we don't need
1886              the skipfnc here, and it saves having an additional field
1887              for this (which would be wasted space most of the
1888              time). */
1889
1890           (*klist)[*count].skipfncvalue=NULL;
1891
1892           /* Are we honoring preferred keyservers? */
1893           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1894             {
1895               PKT_user_id *uid=NULL;
1896               PKT_signature *sig=NULL;
1897
1898               merge_keys_and_selfsig(keyblock);
1899
1900               for(node=node->next;node;node=node->next)
1901                 {
1902                   if(node->pkt->pkttype==PKT_USER_ID
1903                      && node->pkt->pkt.user_id->is_primary)
1904                     uid=node->pkt->pkt.user_id;
1905                   else if(node->pkt->pkttype==PKT_SIGNATURE
1906                           && node->pkt->pkt.signature->
1907                           flags.chosen_selfsig && uid)
1908                     {
1909                       sig=node->pkt->pkt.signature;
1910                       break;
1911                     }
1912                 }
1913
1914               /* Try and parse the keyserver URL.  If it doesn't work,
1915                  then we end up writing NULL which indicates we are
1916                  the same as any other key. */
1917               if(sig)
1918                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1919             }
1920
1921           (*count)++;
1922
1923           if(*count==num)
1924             {
1925               num+=100;
1926               *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1927             }
1928         }
1929     }
1930
1931   if(rc==-1)
1932     rc=0;
1933
1934  leave:
1935   if(rc)
1936     xfree(*klist);
1937   xfree(desc);
1938   keydb_release(kdbhd);
1939   release_kbnode(keyblock);
1940
1941   return rc;
1942 }
1943
1944 /* Note this is different than the original HKP refresh.  It allows
1945    usernames to refresh only part of the keyring. */
1946
1947 int
1948 keyserver_refresh(strlist_t users)
1949 {
1950   int rc,count,numdesc,fakev3=0;
1951   KEYDB_SEARCH_DESC *desc;
1952   unsigned int options=opt.keyserver_options.import_options;
1953
1954   /* We switch merge-only on during a refresh, as 'refresh' should
1955      never import new keys, even if their keyids match. */
1956   opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY;
1957
1958   /* Similarly, we switch on fast-import, since refresh may make
1959      multiple import sets (due to preferred keyserver URLs).  We don't
1960      want each set to rebuild the trustdb.  Instead we do it once at
1961      the end here. */
1962   opt.keyserver_options.import_options|=IMPORT_FAST;
1963
1964   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1965      scheme, then enable fake v3 keyid generation. */
1966   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1967      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1968          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1969     fakev3=1;
1970
1971   rc=keyidlist(users,&desc,&numdesc,fakev3);
1972   if(rc)
1973     return rc;
1974
1975   count=numdesc;
1976   if(count>0)
1977     {
1978       int i;
1979
1980       /* Try to handle preferred keyserver keys first */
1981       for(i=0;i<numdesc;i++)
1982         {
1983           if(desc[i].skipfncvalue)
1984             {
1985               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1986
1987               /* We use the keyserver structure we parsed out before.
1988                  Note that a preferred keyserver without a scheme://
1989                  will be interpreted as hkp:// */
1990
1991               rc=keyserver_work(KS_GET,NULL,&desc[i],1,NULL,NULL,keyserver);
1992               if(rc)
1993                 log_info(_("WARNING: unable to refresh key %s"
1994                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
1995                          keyserver->uri,g10_errstr(rc));
1996               else
1997                 {
1998                   /* We got it, so mark it as NONE so we don't try and
1999                      get it again from the regular keyserver. */
2000
2001                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
2002                   count--;
2003                 }
2004
2005               free_keyserver_spec(keyserver);
2006             }
2007         }
2008     }
2009
2010   if(count>0)
2011     {
2012       if(opt.keyserver)
2013         {
2014           if(count==1)
2015             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
2016           else
2017             log_info(_("refreshing %d keys from %s\n"),
2018                      count,opt.keyserver->uri);
2019         }
2020
2021       rc=keyserver_work(KS_GET,NULL,desc,numdesc,NULL,NULL,opt.keyserver);
2022     }
2023
2024   xfree(desc);
2025
2026   opt.keyserver_options.import_options=options;
2027
2028   /* If the original options didn't have fast import, and the trustdb
2029      is dirty, rebuild. */
2030   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
2031     trustdb_check_or_update();
2032
2033   return rc;
2034 }
2035
2036 int
2037 keyserver_search(strlist_t tokens)
2038 {
2039   if(tokens)
2040     return keyserver_work(KS_SEARCH,tokens,NULL,0,NULL,NULL,opt.keyserver);
2041   else
2042     return 0;
2043 }
2044
2045 int
2046 keyserver_fetch(strlist_t urilist)
2047 {
2048   KEYDB_SEARCH_DESC desc;
2049   strlist_t sl;
2050   unsigned int options=opt.keyserver_options.import_options;
2051
2052   /* Switch on fast-import, since fetch can handle more than one
2053      import and we don't want each set to rebuild the trustdb.
2054      Instead we do it once at the end. */
2055   opt.keyserver_options.import_options|=IMPORT_FAST;
2056
2057   /* A dummy desc since we're not actually fetching a particular key
2058      ID */
2059   memset(&desc,0,sizeof(desc));
2060   desc.mode=KEYDB_SEARCH_MODE_EXACT;
2061
2062   for(sl=urilist;sl;sl=sl->next)
2063     {
2064       struct keyserver_spec *spec;
2065
2066       spec=parse_keyserver_uri(sl->d,1,NULL,0);
2067       if(spec)
2068         {
2069           int rc;
2070
2071           rc=keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,spec);
2072           if(rc)
2073             log_info (_("WARNING: unable to fetch URI %s: %s\n"),
2074                      sl->d,g10_errstr(rc));
2075
2076           free_keyserver_spec(spec);
2077         }
2078       else
2079         log_info (_("WARNING: unable to parse URI %s\n"),sl->d);
2080     }
2081
2082   opt.keyserver_options.import_options=options;
2083
2084   /* If the original options didn't have fast import, and the trustdb
2085      is dirty, rebuild. */
2086   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
2087     trustdb_check_or_update();
2088
2089   return 0;
2090 }
2091
2092 /* Import key in a CERT or pointed to by a CERT */
2093 int
2094 keyserver_import_cert(const char *name,unsigned char **fpr,size_t *fpr_len)
2095 {
2096   char *domain,*look,*url;
2097   IOBUF key;
2098   int type,rc=G10ERR_GENERAL;
2099
2100   look=xstrdup(name);
2101
2102   domain=strrchr(look,'@');
2103   if(domain)
2104     *domain='.';
2105
2106   type=get_dns_cert(look,max_cert_size,&key,fpr,fpr_len,&url);
2107   if (!type || type == -1)
2108     {
2109       /* There might be an error in res_query which leads to an error
2110          return (-1) in the case that nothing was found.  Thus we take
2111          all errors as key not found.  */
2112       rc = G10ERR_NO_PUBKEY;
2113     }
2114   else if (type==1)
2115     {
2116       int armor_status=opt.no_armor;
2117
2118       /* CERTs are always in binary format */
2119       opt.no_armor=1;
2120
2121       rc=import_keys_stream (key, NULL, fpr, fpr_len,
2122                              (opt.keyserver_options.import_options
2123                               | IMPORT_NO_SECKEY), NULL, NULL);
2124
2125       opt.no_armor=armor_status;
2126
2127       iobuf_close(key);
2128     }
2129   else if(type==2 && *fpr)
2130     {
2131       /* We only consider the IPGP type if a fingerprint was provided.
2132          This lets us select the right key regardless of what a URL
2133          points to, or get the key from a keyserver. */
2134       if(url)
2135         {
2136           struct keyserver_spec *spec;
2137
2138           spec=parse_keyserver_uri(url,1,NULL,0);
2139           if(spec)
2140             {
2141               rc=keyserver_import_fprint(*fpr,*fpr_len,spec);
2142               free_keyserver_spec(spec);
2143             }
2144         }
2145       else if(opt.keyserver)
2146         {
2147           /* If only a fingerprint is provided, try and fetch it from
2148              our --keyserver */
2149
2150           rc=keyserver_import_fprint(*fpr,*fpr_len,opt.keyserver);
2151         }
2152       else
2153         log_info(_("no keyserver known (use option --keyserver)\n"));
2154
2155       /* Give a better string here? "CERT fingerprint for \"%s\"
2156          found, but no keyserver" " known (use option
2157          --keyserver)\n" ? */
2158
2159       xfree(url);
2160     }
2161
2162   xfree(look);
2163
2164   return rc;
2165 }
2166
2167 /* Import key pointed to by a PKA record. Return the requested
2168    fingerprint in fpr. */
2169 int
2170 keyserver_import_pka(const char *name,unsigned char **fpr,size_t *fpr_len)
2171 {
2172   char *uri;
2173   int rc = G10ERR_NO_PUBKEY;
2174
2175   *fpr = xmalloc (20);
2176   *fpr_len = 20;
2177
2178   uri = get_pka_info (name, *fpr);
2179   if (uri && *uri)
2180     {
2181       /* An URI is available.  Lookup the key. */
2182       struct keyserver_spec *spec;
2183       spec = parse_keyserver_uri (uri, 1, NULL, 0);
2184       if (spec)
2185         {
2186           rc = keyserver_import_fprint (*fpr, 20, spec);
2187           free_keyserver_spec (spec);
2188         }
2189       xfree (uri);
2190     }
2191
2192   if (rc)
2193     {
2194       xfree(*fpr);
2195       *fpr = NULL;
2196     }
2197
2198   return rc;
2199 }
2200
2201 /* Import all keys that match name */
2202 int
2203 keyserver_import_name(const char *name,unsigned char **fpr,size_t *fpr_len,
2204                       struct keyserver_spec *keyserver)
2205 {
2206   strlist_t list=NULL;
2207   int rc;
2208
2209   append_to_strlist(&list,name);
2210
2211   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2212
2213   free_strlist(list);
2214
2215   return rc;
2216 }
2217
2218 /* Import a key by name using LDAP */
2219 int
2220 keyserver_import_ldap(const char *name,unsigned char **fpr,size_t *fpr_len)
2221 {
2222   char *domain;
2223   struct keyserver_spec *keyserver;
2224   strlist_t list=NULL;
2225   int rc,hostlen=1;
2226 #ifdef USE_DNS_SRV
2227   struct srventry *srvlist=NULL;
2228   int srvcount,i;
2229   char srvname[MAXDNAME];
2230 #endif
2231
2232   /* Parse out the domain */
2233   domain=strrchr(name,'@');
2234   if(!domain)
2235     return G10ERR_GENERAL;
2236
2237   domain++;
2238
2239   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
2240   keyserver->scheme=xstrdup("ldap");
2241   keyserver->host=xmalloc(1);
2242   keyserver->host[0]='\0';
2243
2244 #ifdef USE_DNS_SRV
2245   snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain);
2246
2247   srvcount=getsrv(srvname,&srvlist);
2248
2249   for(i=0;i<srvcount;i++)
2250     {
2251       hostlen+=strlen(srvlist[i].target)+1;
2252       keyserver->host=xrealloc(keyserver->host,hostlen);
2253
2254       strcat(keyserver->host,srvlist[i].target);
2255
2256       if(srvlist[i].port!=389)
2257         {
2258           char port[7];
2259
2260           hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */
2261           keyserver->host=xrealloc(keyserver->host,hostlen);
2262
2263           snprintf(port,7,":%u",srvlist[i].port);
2264           strcat(keyserver->host,port);
2265         }
2266
2267       strcat(keyserver->host," ");
2268     }
2269
2270   free(srvlist);
2271 #endif
2272
2273   /* If all else fails, do the PGP Universal trick of
2274      ldap://keys.(domain) */
2275
2276   hostlen+=5+strlen(domain);
2277   keyserver->host=xrealloc(keyserver->host,hostlen);
2278   strcat(keyserver->host,"keys.");
2279   strcat(keyserver->host,domain);
2280
2281   append_to_strlist(&list,name);
2282
2283   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2284
2285   free_strlist(list);
2286
2287   free_keyserver_spec(keyserver);
2288
2289   return rc;
2290 }