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