gpg: Print better diagnostics for keyserver operations.
[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 (kbnode_t keyblock, void *opaque)
998 {
999   struct ks_retrieval_filter_arg_s *arg = opaque;
1000   KEYDB_SEARCH_DESC *desc = arg->desc;
1001   int ndesc = arg->ndesc;
1002   kbnode_t node;
1003   PKT_public_key *pk;
1004   int n;
1005   u32 keyid[2];
1006   byte fpr[MAX_FINGERPRINT_LEN];
1007   size_t fpr_len = 0;
1008
1009   /* Secret keys are not expected from a keyserver.  We do not
1010      care about secret subkeys because the import code takes care
1011      of skipping them.  Not allowing an import of a public key
1012      with a secret subkey would make it too easy to inhibit the
1013      downloading of a public key.  Recall that keyservers do only
1014      limited checks.  */
1015   node = find_kbnode (keyblock, PKT_SECRET_KEY);
1016   if (node)
1017     return G10ERR_GENERAL;   /* Do not import. */
1018
1019   if (!ndesc)
1020     return 0; /* Okay if no description given.  */
1021
1022   /* Loop over all key packets.  */
1023   for (node = keyblock; node; node = node->next)
1024     {
1025       if (node->pkt->pkttype != PKT_PUBLIC_KEY
1026           && node->pkt->pkttype != PKT_PUBLIC_SUBKEY)
1027         continue;
1028
1029       pk = node->pkt->pkt.public_key;
1030       fingerprint_from_pk (pk, fpr, &fpr_len);
1031       keyid_from_pk (pk, keyid);
1032
1033       /* Compare requested and returned fingerprints if available. */
1034       for (n = 0; n < ndesc; n++)
1035         {
1036           if (desc[n].mode == KEYDB_SEARCH_MODE_FPR20)
1037             {
1038               if (fpr_len == 20 && !memcmp (fpr, desc[n].u.fpr, 20))
1039                 return 0;
1040             }
1041           else if (desc[n].mode == KEYDB_SEARCH_MODE_FPR16)
1042             {
1043               if (fpr_len == 16 && !memcmp (fpr, desc[n].u.fpr, 16))
1044                 return 0;
1045             }
1046           else if (desc[n].mode == KEYDB_SEARCH_MODE_LONG_KID)
1047             {
1048               if (keyid[0] == desc[n].u.kid[0] && keyid[1] == desc[n].u.kid[1])
1049                 return 0;
1050             }
1051           else if (desc[n].mode == KEYDB_SEARCH_MODE_SHORT_KID)
1052             {
1053               if (keyid[1] == desc[n].u.kid[1])
1054                 return 0;
1055             }
1056           else /* No keyid or fingerprint - can't check.  */
1057             return 0; /* allow import.  */
1058         }
1059     }
1060
1061   return G10ERR_GENERAL;
1062 }
1063
1064
1065 static const char *
1066 keyserver_errstr (int code)
1067 {
1068   const char *s;
1069
1070   switch (code)
1071     {
1072     case KEYSERVER_OK:            s = "success"; break;
1073     case KEYSERVER_INTERNAL_ERROR:s = "keyserver helper internal error"; break;
1074     case KEYSERVER_NOT_SUPPORTED: s =gpg_strerror (GPG_ERR_NOT_SUPPORTED);break;
1075     case KEYSERVER_VERSION_ERROR: s = "keyserver helper version mismatch";break;
1076     case KEYSERVER_GENERAL_ERROR: s = "keyserver helper general error"; break;
1077     case KEYSERVER_NO_MEMORY:     s = "keyserver helper is out of core"; break;
1078     case KEYSERVER_KEY_NOT_FOUND: s =gpg_strerror (GPG_ERR_NOT_FOUND); break;
1079     case KEYSERVER_KEY_EXISTS:    s = "key exists"; break;
1080     case KEYSERVER_KEY_INCOMPLETE:s = "key incomplete (EOF)"; break;
1081     case KEYSERVER_UNREACHABLE:   s =gpg_strerror (GPG_ERR_UNKNOWN_HOST);break;
1082     case KEYSERVER_TIMEOUT:       s =gpg_strerror (GPG_ERR_TIMEOUT); break;
1083     default:                      s = "?"; break;
1084     }
1085   return s;
1086 }
1087
1088
1089 static int
1090 keyserver_spawn (enum ks_action action, strlist_t list, KEYDB_SEARCH_DESC *desc,
1091                  int count, int *prog, unsigned char **fpr, size_t *fpr_len,
1092                  struct keyserver_spec *keyserver)
1093 {
1094   int ret=0,i,gotversion=0,outofband=0;
1095   strlist_t temp;
1096   unsigned int maxlen,buflen;
1097   char *command,*end,*searchstr=NULL;
1098   byte *line=NULL;
1099   struct exec_info *spawn;
1100   const char *scheme;
1101   const char *libexecdir = gnupg_libexecdir ();
1102
1103   assert(keyserver);
1104
1105 #ifdef EXEC_TEMPFILE_ONLY
1106   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
1107 #endif
1108
1109   /* Build the filename for the helper to execute */
1110   scheme=keyserver_typemap(keyserver->scheme);
1111
1112 #ifdef DISABLE_KEYSERVER_PATH
1113   /* Destroy any path we might have.  This is a little tricky,
1114      portability-wise.  It's not correct to delete the PATH
1115      environment variable, as that may fall back to a system built-in
1116      PATH.  Similarly, it is not correct to set PATH to the null
1117      string (PATH="") since this actually deletes the PATH environment
1118      variable under MinGW.  The safest thing to do here is to force
1119      PATH to be GNUPG_LIBEXECDIR.  All this is not that meaningful on
1120      Unix-like systems (since we're going to give a full path to
1121      gpgkeys_foo), but on W32 it prevents loading any DLLs from
1122      directories in %PATH%.
1123
1124      After some more thinking about this we came to the conclusion
1125      that it is better to load the helpers from the directory where
1126      the program of this process lives.  Fortunately Windows provides
1127      a way to retrieve this and our gnupg_libexecdir function has been
1128      modified to return just this.  Setting the exec-path is not
1129      anymore required.
1130        set_exec_path(libexecdir);
1131  */
1132 #else
1133   if(opt.exec_path_set)
1134     {
1135       /* If exec-path was set, and DISABLE_KEYSERVER_PATH is
1136          undefined, then don't specify a full path to gpgkeys_foo, so
1137          that the PATH can work. */
1138       command=xmalloc(GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1139       command[0]='\0';
1140     }
1141   else
1142 #endif
1143     {
1144       /* Specify a full path to gpgkeys_foo. */
1145       command=xmalloc(strlen(libexecdir)+strlen(DIRSEP_S)+
1146                       GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1147       strcpy(command,libexecdir);
1148       strcat(command,DIRSEP_S);
1149     }
1150
1151   end=command+strlen(command);
1152
1153   /* Build a path for the keyserver helper.  If it is direct_uri
1154      (i.e. an object fetch and not a keyserver), then add "_uri" to
1155      the end to distinguish the keyserver helper from an object
1156      fetcher that can speak that protocol (this is a problem for
1157      LDAP). */
1158
1159   strcat(command,GPGKEYS_PREFIX);
1160   strcat(command,scheme);
1161
1162   /* This "_uri" thing is in case we need to call a direct handler
1163      instead of the keyserver handler.  This lets us use gpgkeys_curl
1164      or gpgkeys_ldap_uri (we don't provide it, but a user might)
1165      instead of gpgkeys_ldap to fetch things like
1166      ldap://keyserver.pgp.com/o=PGP%20keys?pgpkey?sub?pgpkeyid=99242560 */
1167
1168   if(direct_uri_map(scheme,keyserver->flags.direct_uri))
1169     strcat(command,"_uri");
1170
1171   strcat(command,EXEEXT);
1172
1173   /* Can we execute it?  If not, try curl as our catchall. */
1174   if(path_access(command,X_OK)!=0)
1175     strcpy(end,GPGKEYS_CURL);
1176
1177   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
1178     {
1179       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
1180         {
1181           command=xrealloc(command,strlen(command)+
1182                             strlen(KEYSERVER_ARGS_KEEP)+1);
1183           strcat(command,KEYSERVER_ARGS_KEEP);
1184         }
1185       else
1186         {
1187           command=xrealloc(command,strlen(command)+
1188                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
1189           strcat(command,KEYSERVER_ARGS_NOKEEP);
1190         }
1191
1192       ret=exec_write(&spawn,NULL,command,NULL,0,0);
1193     }
1194   else
1195     ret=exec_write(&spawn,command,NULL,NULL,0,0);
1196
1197   xfree(command);
1198
1199   if(ret)
1200     return ret;
1201
1202   fprintf(spawn->tochild,
1203           "# This is a GnuPG %s keyserver communications file\n",VERSION);
1204   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1205   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
1206   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
1207
1208   if(keyserver->opaque)
1209     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
1210   else
1211     {
1212       if(keyserver->auth)
1213         fprintf(spawn->tochild,"AUTH %s\n",keyserver->auth);
1214
1215       if(keyserver->host)
1216         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
1217
1218       if(keyserver->port)
1219         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
1220
1221       if(keyserver->path)
1222         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
1223     }
1224
1225   /* Write global options */
1226
1227   for(temp=opt.keyserver_options.other;temp;temp=temp->next)
1228     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1229
1230   /* Write per-keyserver options */
1231
1232   for(temp=keyserver->options;temp;temp=temp->next)
1233     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1234
1235   switch(action)
1236     {
1237     case KS_GET:
1238       {
1239         fprintf(spawn->tochild,"COMMAND GET\n\n");
1240
1241         /* Which keys do we want? */
1242
1243         for(i=0;i<count;i++)
1244           {
1245             int quiet=0;
1246
1247             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
1248               {
1249                 int f;
1250
1251                 fprintf(spawn->tochild,"0x");
1252
1253                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
1254                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1255
1256                 fprintf(spawn->tochild,"\n");
1257               }
1258             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
1259               {
1260                 int f;
1261
1262                 fprintf(spawn->tochild,"0x");
1263
1264                 for(f=0;f<16;f++)
1265                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1266
1267                 fprintf(spawn->tochild,"\n");
1268               }
1269             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
1270               fprintf(spawn->tochild,"0x%08lX%08lX\n",
1271                       (ulong)desc[i].u.kid[0],
1272                       (ulong)desc[i].u.kid[1]);
1273             else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
1274               fprintf(spawn->tochild,"0x%08lX\n",
1275                       (ulong)desc[i].u.kid[1]);
1276             else if(desc[i].mode==KEYDB_SEARCH_MODE_EXACT)
1277               {
1278                 fprintf(spawn->tochild,"0x0000000000000000\n");
1279                 quiet=1;
1280               }
1281             else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
1282               continue;
1283             else
1284               BUG();
1285
1286             if(!quiet)
1287               {
1288                 if(keyserver->host)
1289                   log_info(_("requesting key %s from %s server %s\n"),
1290                            keystr_from_desc(&desc[i]),
1291                            keyserver->scheme,keyserver->host);
1292                 else
1293                   log_info(_("requesting key %s from %s\n"),
1294                            keystr_from_desc(&desc[i]),keyserver->uri);
1295               }
1296           }
1297
1298         fprintf(spawn->tochild,"\n");
1299
1300         break;
1301       }
1302
1303     case KS_GETNAME:
1304       {
1305         strlist_t key;
1306
1307         fprintf(spawn->tochild,"COMMAND GETNAME\n\n");
1308
1309         /* Which names do we want? */
1310
1311         for(key=list;key!=NULL;key=key->next)
1312           fprintf(spawn->tochild,"%s\n",key->d);
1313
1314         fprintf(spawn->tochild,"\n");
1315
1316         if(keyserver->host)
1317           log_info(_("searching for names from %s server %s\n"),
1318                    keyserver->scheme,keyserver->host);
1319         else
1320           log_info(_("searching for names from %s\n"),keyserver->uri);
1321
1322         break;
1323       }
1324
1325     case KS_SEND:
1326       {
1327         strlist_t key;
1328
1329         /* Note the extra \n here to send an empty keylist block */
1330         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
1331
1332         for(key=list;key!=NULL;key=key->next)
1333           {
1334             armor_filter_context_t *afx;
1335             IOBUF buffer = iobuf_temp ();
1336             KBNODE block;
1337
1338             temp=NULL;
1339             add_to_strlist(&temp,key->d);
1340
1341             afx = new_armor_context ();
1342             afx->what = 1;
1343             /* Tell the armor filter to use Unix-style \n line
1344                endings, since we're going to fprintf this to a file
1345                that (on Win32) is open in text mode.  The win32 stdio
1346                will transform the \n to \r\n and we'll end up with the
1347                proper line endings on win32.  This is a no-op on
1348                Unix. */
1349             afx->eol[0] = '\n';
1350             push_armor_filter (afx, buffer);
1351             release_armor_context (afx);
1352
1353             /* TODO: Remove Comment: lines from keys exported this
1354                way? */
1355
1356             if(export_pubkeys_stream(buffer,temp,&block,
1357                                      opt.keyserver_options.export_options)==-1)
1358               iobuf_close(buffer);
1359             else
1360               {
1361                 KBNODE node;
1362
1363                 iobuf_flush_temp(buffer);
1364
1365                 merge_keys_and_selfsig(block);
1366
1367                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
1368                         (ulong)block->pkt->pkt.public_key->keyid[0],
1369                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1370
1371                 for(node=block;node;node=node->next)
1372                   {
1373                     switch(node->pkt->pkttype)
1374                       {
1375                       default:
1376                         continue;
1377
1378                       case PKT_PUBLIC_KEY:
1379                       case PKT_PUBLIC_SUBKEY:
1380                         {
1381                           PKT_public_key *pk=node->pkt->pkt.public_key;
1382
1383                           keyid_from_pk(pk,NULL);
1384
1385                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
1386                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
1387                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
1388                                   pk->pubkey_algo,
1389                                   nbits_from_pk(pk),
1390                                   pk->timestamp,
1391                                   pk->expiredate);
1392
1393                           if(pk->is_revoked)
1394                             fprintf(spawn->tochild,"r");
1395                           if(pk->has_expired)
1396                             fprintf(spawn->tochild,"e");
1397
1398                           fprintf(spawn->tochild,"\n");
1399                         }
1400                         break;
1401
1402                       case PKT_USER_ID:
1403                         {
1404                           PKT_user_id *uid=node->pkt->pkt.user_id;
1405                           int r;
1406
1407                           if(uid->attrib_data)
1408                             continue;
1409
1410                           fprintf(spawn->tochild,"uid:");
1411
1412                           /* Quote ':', '%', and any 8-bit
1413                              characters */
1414                           for(r=0;r<uid->len;r++)
1415                             {
1416                               if(uid->name[r]==':' || uid->name[r]=='%'
1417                                  || uid->name[r]&0x80)
1418                                 fprintf(spawn->tochild,"%%%02X",
1419                                         (byte)uid->name[r]);
1420                               else
1421                                 fprintf(spawn->tochild,"%c",uid->name[r]);
1422                             }
1423
1424                           fprintf(spawn->tochild,":%u:%u:",
1425                                   uid->created,uid->expiredate);
1426
1427                           if(uid->is_revoked)
1428                             fprintf(spawn->tochild,"r");
1429                           if(uid->is_expired)
1430                             fprintf(spawn->tochild,"e");
1431
1432                           fprintf(spawn->tochild,"\n");
1433                         }
1434                         break;
1435
1436                         /* This bit is really for the benefit of
1437                            people who store their keys in LDAP
1438                            servers.  It makes it easy to do queries
1439                            for things like "all keys signed by
1440                            Isabella". */
1441                       case PKT_SIGNATURE:
1442                         {
1443                           PKT_signature *sig=node->pkt->pkt.signature;
1444
1445                           if(!IS_UID_SIG(sig))
1446                             continue;
1447
1448                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1449                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1450                                   sig->sig_class,sig->timestamp,
1451                                   sig->expiredate);
1452                         }
1453                         break;
1454                       }
1455                   }
1456
1457                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1458                         (ulong)block->pkt->pkt.public_key->keyid[0],
1459                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1460
1461                 fprintf(spawn->tochild,"KEY %08lX%08lX BEGIN\n",
1462                         (ulong)block->pkt->pkt.public_key->keyid[0],
1463                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1464                 fwrite(iobuf_get_temp_buffer(buffer),
1465                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1466                 fprintf(spawn->tochild,"KEY %08lX%08lX END\n",
1467                         (ulong)block->pkt->pkt.public_key->keyid[0],
1468                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1469
1470                 iobuf_close(buffer);
1471
1472                 if(keyserver->host)
1473                   log_info(_("sending key %s to %s server %s\n"),
1474                            keystr(block->pkt->pkt.public_key->keyid),
1475                            keyserver->scheme,keyserver->host);
1476                 else
1477                   log_info(_("sending key %s to %s\n"),
1478                            keystr(block->pkt->pkt.public_key->keyid),
1479                            keyserver->uri);
1480
1481                 release_kbnode(block);
1482               }
1483
1484             free_strlist(temp);
1485           }
1486
1487         break;
1488       }
1489
1490     case KS_SEARCH:
1491       {
1492         strlist_t key;
1493
1494         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1495
1496         /* Which keys do we want?  Remember that the gpgkeys_ program
1497            is going to lump these together into a search string. */
1498
1499         for(key=list;key!=NULL;key=key->next)
1500           {
1501             fprintf(spawn->tochild,"%s\n",key->d);
1502             if(key!=list)
1503               {
1504                 searchstr=xrealloc(searchstr,
1505                                     strlen(searchstr)+strlen(key->d)+2);
1506                 strcat(searchstr," ");
1507               }
1508             else
1509               {
1510                 searchstr=xmalloc(strlen(key->d)+1);
1511                 searchstr[0]='\0';
1512               }
1513
1514             strcat(searchstr,key->d);
1515           }
1516
1517         fprintf(spawn->tochild,"\n");
1518
1519         if(keyserver->host)
1520           log_info(_("searching for \"%s\" from %s server %s\n"),
1521                    searchstr,keyserver->scheme,keyserver->host);
1522         else
1523           log_info(_("searching for \"%s\" from %s\n"),
1524                    searchstr,keyserver->uri);
1525
1526         break;
1527       }
1528
1529     default:
1530       log_fatal(_("no keyserver action!\n"));
1531       break;
1532     }
1533
1534   /* Done sending, so start reading. */
1535   ret=exec_read(spawn);
1536   if(ret)
1537     goto fail;
1538
1539   /* Now handle the response */
1540
1541   for(;;)
1542     {
1543       int plen;
1544       char *ptr;
1545
1546       maxlen=1024;
1547       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1548         {
1549           ret = gpg_error_from_syserror ();
1550           goto fail; /* i.e. EOF */
1551         }
1552
1553       ptr=line;
1554
1555       /* remove trailing whitespace */
1556       plen=strlen(ptr);
1557       while(plen>0 && ascii_isspace(ptr[plen-1]))
1558         plen--;
1559       plen[ptr]='\0';
1560
1561       /* Stop at the first empty line but not if we are sending keys.
1562          In the latter case we won't continue reading later and thus
1563          we need to watch out for errors right in this loop.  */
1564       if(*ptr=='\0' && action != KS_SEND)
1565         break;
1566
1567       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1568         {
1569           gotversion=1;
1570
1571           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1572             {
1573               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1574                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1575               goto fail;
1576             }
1577         }
1578       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1579         {
1580           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1581             log_info(_("WARNING: keyserver handler from a different"
1582                        " version of GnuPG (%s)\n"),&ptr[8]);
1583         }
1584       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1585         outofband=1; /* Currently the only OPTION */
1586       else if (action == KS_SEND
1587                && ascii_strncasecmp(ptr,"KEY ",4)==0)
1588         {
1589           ret = parse_key_failed_line (ptr+4, strlen (ptr+4));
1590           break;  /* We stop at the first KEY line so that we won't
1591                      run into an EOF which would return an unspecified
1592                      error message (due to iobuf_read_line).  */
1593         }
1594     }
1595
1596   if(!gotversion)
1597     {
1598       log_error(_("keyserver did not send VERSION\n"));
1599       goto fail;
1600     }
1601
1602   if(!outofband)
1603     switch(action)
1604       {
1605       case KS_GET:
1606       case KS_GETNAME:
1607         {
1608           void *stats_handle;
1609           struct ks_retrieval_filter_arg_s filterarg;
1610           int gpgkeys_err;
1611
1612           stats_handle=import_new_stats_handle();
1613
1614           /* Slurp up all the key data.  In the future, it might be
1615              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1616              It's harmless to ignore them, but ignoring them does make
1617              gpg complain about "no valid OpenPGP data found".  One
1618              way to do this could be to continue parsing this
1619              line-by-line and make a temp iobuf for each key.  Note
1620              that we don't allow the import of secret keys from a
1621              keyserver.  Keyservers should never accept or send them
1622              but we better protect against rogue keyservers. */
1623           filterarg.desc = desc;
1624           filterarg.ndesc = count;
1625           gpgkeys_err = 0;
1626           import_keys_stream (spawn->fromchild, stats_handle, fpr, fpr_len,
1627                              (opt.keyserver_options.import_options
1628                               | IMPORT_NO_SECKEY),
1629                               keyserver_retrieval_filter, &filterarg,
1630                               &gpgkeys_err);
1631
1632           import_print_stats(stats_handle);
1633           import_release_stats_handle(stats_handle);
1634           if (gpgkeys_err)
1635             {
1636               log_error (_("keyserver communications error: %s\n"),
1637                          keyserver_errstr (gpgkeys_err));
1638               ret = gpgkeys_err;
1639             }
1640           break;
1641         }
1642
1643         /* Nothing to do here */
1644       case KS_SEND:
1645         break;
1646
1647       case KS_SEARCH:
1648         keyserver_search_prompt(spawn->fromchild,searchstr);
1649         break;
1650
1651       default:
1652         log_fatal(_("no keyserver action!\n"));
1653         break;
1654       }
1655
1656  fail:
1657   xfree(line);
1658   xfree(searchstr);
1659
1660   *prog=exec_finish(spawn);
1661
1662   return ret;
1663 }
1664
1665
1666 static int
1667 keyserver_work (enum ks_action action, strlist_t list, KEYDB_SEARCH_DESC *desc,
1668                 int count, unsigned char **fpr, size_t *fpr_len,
1669                 struct keyserver_spec *keyserver)
1670 {
1671   int rc = 0;
1672   int ret = 0;
1673
1674   if(!keyserver)
1675     {
1676       log_error(_("no keyserver known (use option --keyserver)\n"));
1677       return G10ERR_BAD_URI;
1678     }
1679
1680 #ifdef DISABLE_KEYSERVER_HELPERS
1681
1682   log_error(_("external keyserver calls are not supported in this build\n"));
1683   return G10ERR_KEYSERVER;
1684
1685 #else
1686   /* Spawn a handler.  The use of RC and RET is a mess.  We use a
1687      kludge to return a suitable error message.  */
1688   rc=keyserver_spawn(action,list,desc,count,&ret,fpr,fpr_len,keyserver);
1689   if (ret == KEYSERVER_INTERNAL_ERROR && rc)
1690     ret = rc;
1691   if(ret)
1692     {
1693       switch(ret)
1694         {
1695         case KEYSERVER_SCHEME_NOT_FOUND:
1696           log_error(_("no handler for keyserver scheme `%s'\n"),
1697                     keyserver->scheme);
1698           break;
1699
1700         case KEYSERVER_NOT_SUPPORTED:
1701           log_error(_("action `%s' not supported with keyserver "
1702                       "scheme `%s'\n"),
1703                     action==KS_GET?"get":action==KS_SEND?"send":
1704                     action==KS_SEARCH?"search":"unknown",
1705                     keyserver->scheme);
1706           break;
1707
1708         case KEYSERVER_VERSION_ERROR:
1709           log_error(_(GPGKEYS_PREFIX "%s does not support"
1710                       " handler version %d\n"),
1711                     keyserver_typemap(keyserver->scheme),
1712                     KEYSERVER_PROTO_VERSION);
1713           break;
1714
1715         case KEYSERVER_TIMEOUT:
1716           log_error(_("keyserver timed out\n"));
1717           break;
1718
1719         case KEYSERVER_UNREACHABLE:
1720           return gpg_error (GPG_ERR_UNKNOWN_HOST);
1721
1722         case KEYSERVER_INTERNAL_ERROR:
1723         default:
1724           log_error(_("keyserver internal error\n"));
1725           break;
1726         }
1727
1728       return G10ERR_KEYSERVER;
1729     }
1730
1731   if(rc)
1732     {
1733       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1734
1735       return rc;
1736     }
1737
1738   return 0;
1739 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1740 }
1741
1742
1743 int
1744 keyserver_export(strlist_t users)
1745 {
1746   strlist_t sl=NULL;
1747   KEYDB_SEARCH_DESC desc;
1748   int rc=0;
1749
1750   /* Weed out descriptors that we don't support sending */
1751   for(;users;users=users->next)
1752     {
1753       classify_user_id (users->d, &desc);
1754       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1755          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1756          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1757          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1758         {
1759           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1760           continue;
1761         }
1762       else
1763         append_to_strlist(&sl,users->d);
1764     }
1765
1766   if(sl)
1767     {
1768       rc=keyserver_work(KS_SEND,sl,NULL,0,NULL,NULL,opt.keyserver);
1769       free_strlist(sl);
1770     }
1771
1772   return rc;
1773 }
1774
1775
1776 int
1777 keyserver_import(strlist_t users)
1778 {
1779   KEYDB_SEARCH_DESC *desc;
1780   int num=100,count=0;
1781   int rc=0;
1782
1783   /* Build a list of key ids */
1784   desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1785
1786   for(;users;users=users->next)
1787     {
1788       classify_user_id (users->d, &desc[count]);
1789       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1790          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1791          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1792          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1793         {
1794           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1795           continue;
1796         }
1797
1798       count++;
1799       if(count==num)
1800         {
1801           num+=100;
1802           desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1803         }
1804     }
1805
1806   if(count>0)
1807     rc=keyserver_work(KS_GET,NULL,desc,count,NULL,NULL,opt.keyserver);
1808
1809   xfree(desc);
1810
1811   return rc;
1812 }
1813
1814 int
1815 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1816                         struct keyserver_spec *keyserver)
1817 {
1818   KEYDB_SEARCH_DESC desc;
1819
1820   memset(&desc,0,sizeof(desc));
1821
1822   if(fprint_len==16)
1823     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1824   else if(fprint_len==20)
1825     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1826   else
1827     return -1;
1828
1829   memcpy(desc.u.fpr,fprint,fprint_len);
1830
1831   /* TODO: Warn here if the fingerprint we got doesn't match the one
1832      we asked for? */
1833   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1834 }
1835
1836 int
1837 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1838 {
1839   KEYDB_SEARCH_DESC desc;
1840
1841   memset(&desc,0,sizeof(desc));
1842
1843   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1844   desc.u.kid[0]=keyid[0];
1845   desc.u.kid[1]=keyid[1];
1846
1847   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1848 }
1849
1850
1851 /* Code mostly stolen from do_export_stream */
1852 static int
1853 keyidlist(strlist_t users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1854 {
1855   int rc = 0;
1856   int num = 100;
1857   int ndesc;
1858   KBNODE keyblock=NULL,node;
1859   KEYDB_HANDLE kdbhd;
1860   KEYDB_SEARCH_DESC *desc;
1861   strlist_t sl;
1862
1863   *count=0;
1864
1865   *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1866
1867   kdbhd=keydb_new(0);
1868
1869   if(!users)
1870     {
1871       ndesc = 1;
1872       desc = xmalloc_clear ( ndesc * sizeof *desc);
1873       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1874     }
1875   else
1876     {
1877       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++)
1878         ;
1879       desc = xmalloc ( ndesc * sizeof *desc);
1880
1881       for (ndesc=0, sl=users; sl; sl = sl->next)
1882         {
1883           if(classify_user_id (sl->d, desc+ndesc))
1884             ndesc++;
1885           else
1886             log_error (_("key \"%s\" not found: %s\n"),
1887                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1888         }
1889     }
1890
1891   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1892     {
1893       if (!users)
1894         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1895
1896       /* read the keyblock */
1897       rc = keydb_get_keyblock (kdbhd, &keyblock );
1898       if( rc )
1899         {
1900           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1901           goto leave;
1902         }
1903
1904       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1905         {
1906           /* This is to work around a bug in some keyservers (pksd and
1907              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1908              The answer is to refresh both the correct v4 keyid
1909              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1910              This only happens for key refresh using the HKP scheme
1911              and if the refresh-add-fake-v3-keyids keyserver option is
1912              set. */
1913           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1914              node->pkt->pkt.public_key->version>=4)
1915             {
1916               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1917               v3_keyid (node->pkt->pkt.public_key->pkey[0],
1918                         (*klist)[*count].u.kid);
1919               (*count)++;
1920
1921               if(*count==num)
1922                 {
1923                   num+=100;
1924                   *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1925                 }
1926             }
1927
1928           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1929              This is because it's easy to calculate any sort of keyid
1930              from a v4 fingerprint, but not a v3 fingerprint. */
1931
1932           if(node->pkt->pkt.public_key->version<4)
1933             {
1934               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1935               keyid_from_pk(node->pkt->pkt.public_key,
1936                             (*klist)[*count].u.kid);
1937             }
1938           else
1939             {
1940               size_t dummy;
1941
1942               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1943               fingerprint_from_pk(node->pkt->pkt.public_key,
1944                                   (*klist)[*count].u.fpr,&dummy);
1945             }
1946
1947           /* This is a little hackish, using the skipfncvalue as a
1948              void* pointer to the keyserver spec, but we don't need
1949              the skipfnc here, and it saves having an additional field
1950              for this (which would be wasted space most of the
1951              time). */
1952
1953           (*klist)[*count].skipfncvalue=NULL;
1954
1955           /* Are we honoring preferred keyservers? */
1956           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1957             {
1958               PKT_user_id *uid=NULL;
1959               PKT_signature *sig=NULL;
1960
1961               merge_keys_and_selfsig(keyblock);
1962
1963               for(node=node->next;node;node=node->next)
1964                 {
1965                   if(node->pkt->pkttype==PKT_USER_ID
1966                      && node->pkt->pkt.user_id->is_primary)
1967                     uid=node->pkt->pkt.user_id;
1968                   else if(node->pkt->pkttype==PKT_SIGNATURE
1969                           && node->pkt->pkt.signature->
1970                           flags.chosen_selfsig && uid)
1971                     {
1972                       sig=node->pkt->pkt.signature;
1973                       break;
1974                     }
1975                 }
1976
1977               /* Try and parse the keyserver URL.  If it doesn't work,
1978                  then we end up writing NULL which indicates we are
1979                  the same as any other key. */
1980               if(sig)
1981                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1982             }
1983
1984           (*count)++;
1985
1986           if(*count==num)
1987             {
1988               num+=100;
1989               *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1990             }
1991         }
1992     }
1993
1994   if(rc==-1)
1995     rc=0;
1996
1997  leave:
1998   if(rc)
1999     xfree(*klist);
2000   xfree(desc);
2001   keydb_release(kdbhd);
2002   release_kbnode(keyblock);
2003
2004   return rc;
2005 }
2006
2007 /* Note this is different than the original HKP refresh.  It allows
2008    usernames to refresh only part of the keyring. */
2009
2010 int
2011 keyserver_refresh(strlist_t users)
2012 {
2013   int rc,count,numdesc,fakev3=0;
2014   KEYDB_SEARCH_DESC *desc;
2015   unsigned int options=opt.keyserver_options.import_options;
2016
2017   /* We switch merge-only on during a refresh, as 'refresh' should
2018      never import new keys, even if their keyids match. */
2019   opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY;
2020
2021   /* Similarly, we switch on fast-import, since refresh may make
2022      multiple import sets (due to preferred keyserver URLs).  We don't
2023      want each set to rebuild the trustdb.  Instead we do it once at
2024      the end here. */
2025   opt.keyserver_options.import_options|=IMPORT_FAST;
2026
2027   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
2028      scheme, then enable fake v3 keyid generation. */
2029   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
2030      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
2031          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
2032     fakev3=1;
2033
2034   rc=keyidlist(users,&desc,&numdesc,fakev3);
2035   if(rc)
2036     return rc;
2037
2038   count=numdesc;
2039   if(count>0)
2040     {
2041       int i;
2042
2043       /* Try to handle preferred keyserver keys first */
2044       for(i=0;i<numdesc;i++)
2045         {
2046           if(desc[i].skipfncvalue)
2047             {
2048               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
2049
2050               /* We use the keyserver structure we parsed out before.
2051                  Note that a preferred keyserver without a scheme://
2052                  will be interpreted as hkp:// */
2053
2054               rc=keyserver_work(KS_GET,NULL,&desc[i],1,NULL,NULL,keyserver);
2055               if(rc)
2056                 log_info(_("WARNING: unable to refresh key %s"
2057                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
2058                          keyserver->uri,g10_errstr(rc));
2059               else
2060                 {
2061                   /* We got it, so mark it as NONE so we don't try and
2062                      get it again from the regular keyserver. */
2063
2064                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
2065                   count--;
2066                 }
2067
2068               free_keyserver_spec(keyserver);
2069             }
2070         }
2071     }
2072
2073   if(count>0)
2074     {
2075       if(opt.keyserver)
2076         {
2077           if(count==1)
2078             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
2079           else
2080             log_info(_("refreshing %d keys from %s\n"),
2081                      count,opt.keyserver->uri);
2082         }
2083
2084       rc=keyserver_work(KS_GET,NULL,desc,numdesc,NULL,NULL,opt.keyserver);
2085     }
2086
2087   xfree(desc);
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 rc;
2097 }
2098
2099 int
2100 keyserver_search(strlist_t tokens)
2101 {
2102   if(tokens)
2103     return keyserver_work(KS_SEARCH,tokens,NULL,0,NULL,NULL,opt.keyserver);
2104   else
2105     return 0;
2106 }
2107
2108 int
2109 keyserver_fetch(strlist_t urilist)
2110 {
2111   KEYDB_SEARCH_DESC desc;
2112   strlist_t sl;
2113   unsigned int options=opt.keyserver_options.import_options;
2114
2115   /* Switch on fast-import, since fetch can handle more than one
2116      import and we don't want each set to rebuild the trustdb.
2117      Instead we do it once at the end. */
2118   opt.keyserver_options.import_options|=IMPORT_FAST;
2119
2120   /* A dummy desc since we're not actually fetching a particular key
2121      ID */
2122   memset(&desc,0,sizeof(desc));
2123   desc.mode=KEYDB_SEARCH_MODE_EXACT;
2124
2125   for(sl=urilist;sl;sl=sl->next)
2126     {
2127       struct keyserver_spec *spec;
2128
2129       spec=parse_keyserver_uri(sl->d,1,NULL,0);
2130       if(spec)
2131         {
2132           int rc;
2133
2134           rc=keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,spec);
2135           if(rc)
2136             log_info (_("WARNING: unable to fetch URI %s: %s\n"),
2137                      sl->d,g10_errstr(rc));
2138
2139           free_keyserver_spec(spec);
2140         }
2141       else
2142         log_info (_("WARNING: unable to parse URI %s\n"),sl->d);
2143     }
2144
2145   opt.keyserver_options.import_options=options;
2146
2147   /* If the original options didn't have fast import, and the trustdb
2148      is dirty, rebuild. */
2149   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
2150     trustdb_check_or_update();
2151
2152   return 0;
2153 }
2154
2155 /* Import key in a CERT or pointed to by a CERT */
2156 int
2157 keyserver_import_cert(const char *name,unsigned char **fpr,size_t *fpr_len)
2158 {
2159   char *domain,*look,*url;
2160   IOBUF key;
2161   int type,rc=G10ERR_GENERAL;
2162
2163   look=xstrdup(name);
2164
2165   domain=strrchr(look,'@');
2166   if(domain)
2167     *domain='.';
2168
2169   type=get_dns_cert(look,max_cert_size,&key,fpr,fpr_len,&url);
2170   if (!type || type == -1)
2171     {
2172       /* There might be an error in res_query which leads to an error
2173          return (-1) in the case that nothing was found.  Thus we take
2174          all errors as key not found.  */
2175       rc = G10ERR_NO_PUBKEY;
2176     }
2177   else if (type==1)
2178     {
2179       int armor_status=opt.no_armor;
2180
2181       /* CERTs are always in binary format */
2182       opt.no_armor=1;
2183
2184       rc=import_keys_stream (key, NULL, fpr, fpr_len,
2185                              (opt.keyserver_options.import_options
2186                               | IMPORT_NO_SECKEY), NULL, NULL, NULL);
2187
2188       opt.no_armor=armor_status;
2189
2190       iobuf_close(key);
2191     }
2192   else if(type==2 && *fpr)
2193     {
2194       /* We only consider the IPGP type if a fingerprint was provided.
2195          This lets us select the right key regardless of what a URL
2196          points to, or get the key from a keyserver. */
2197       if(url)
2198         {
2199           struct keyserver_spec *spec;
2200
2201           spec=parse_keyserver_uri(url,1,NULL,0);
2202           if(spec)
2203             {
2204               rc=keyserver_import_fprint(*fpr,*fpr_len,spec);
2205               free_keyserver_spec(spec);
2206             }
2207         }
2208       else if(opt.keyserver)
2209         {
2210           /* If only a fingerprint is provided, try and fetch it from
2211              our --keyserver */
2212
2213           rc=keyserver_import_fprint(*fpr,*fpr_len,opt.keyserver);
2214         }
2215       else
2216         log_info(_("no keyserver known (use option --keyserver)\n"));
2217
2218       /* Give a better string here? "CERT fingerprint for \"%s\"
2219          found, but no keyserver" " known (use option
2220          --keyserver)\n" ? */
2221
2222       xfree(url);
2223     }
2224
2225   xfree(look);
2226
2227   return rc;
2228 }
2229
2230 /* Import key pointed to by a PKA record. Return the requested
2231    fingerprint in fpr. */
2232 int
2233 keyserver_import_pka(const char *name,unsigned char **fpr,size_t *fpr_len)
2234 {
2235   char *uri;
2236   int rc = G10ERR_NO_PUBKEY;
2237
2238   *fpr = xmalloc (20);
2239   *fpr_len = 20;
2240
2241   uri = get_pka_info (name, *fpr);
2242   if (uri && *uri)
2243     {
2244       /* An URI is available.  Lookup the key. */
2245       struct keyserver_spec *spec;
2246       spec = parse_keyserver_uri (uri, 1, NULL, 0);
2247       if (spec)
2248         {
2249           rc = keyserver_import_fprint (*fpr, 20, spec);
2250           free_keyserver_spec (spec);
2251         }
2252       xfree (uri);
2253     }
2254
2255   if (rc)
2256     {
2257       xfree(*fpr);
2258       *fpr = NULL;
2259     }
2260
2261   return rc;
2262 }
2263
2264 /* Import all keys that match name */
2265 int
2266 keyserver_import_name(const char *name,unsigned char **fpr,size_t *fpr_len,
2267                       struct keyserver_spec *keyserver)
2268 {
2269   strlist_t list=NULL;
2270   int rc;
2271
2272   append_to_strlist(&list,name);
2273
2274   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2275
2276   free_strlist(list);
2277
2278   return rc;
2279 }
2280
2281 /* Import a key by name using LDAP */
2282 int
2283 keyserver_import_ldap(const char *name,unsigned char **fpr,size_t *fpr_len)
2284 {
2285   char *domain;
2286   struct keyserver_spec *keyserver;
2287   strlist_t list=NULL;
2288   int rc,hostlen=1;
2289 #ifdef USE_DNS_SRV
2290   struct srventry *srvlist=NULL;
2291   int srvcount,i;
2292   char srvname[MAXDNAME];
2293 #endif
2294
2295   /* Parse out the domain */
2296   domain=strrchr(name,'@');
2297   if(!domain)
2298     return G10ERR_GENERAL;
2299
2300   domain++;
2301
2302   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
2303   keyserver->scheme=xstrdup("ldap");
2304   keyserver->host=xmalloc(1);
2305   keyserver->host[0]='\0';
2306
2307 #ifdef USE_DNS_SRV
2308   snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain);
2309
2310   srvcount=getsrv(srvname,&srvlist);
2311
2312   for(i=0;i<srvcount;i++)
2313     {
2314       hostlen+=strlen(srvlist[i].target)+1;
2315       keyserver->host=xrealloc(keyserver->host,hostlen);
2316
2317       strcat(keyserver->host,srvlist[i].target);
2318
2319       if(srvlist[i].port!=389)
2320         {
2321           char port[7];
2322
2323           hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */
2324           keyserver->host=xrealloc(keyserver->host,hostlen);
2325
2326           snprintf(port,7,":%u",srvlist[i].port);
2327           strcat(keyserver->host,port);
2328         }
2329
2330       strcat(keyserver->host," ");
2331     }
2332
2333   free(srvlist);
2334 #endif
2335
2336   /* If all else fails, do the PGP Universal trick of
2337      ldap://keys.(domain) */
2338
2339   hostlen+=5+strlen(domain);
2340   keyserver->host=xrealloc(keyserver->host,hostlen);
2341   strcat(keyserver->host,"keys.");
2342   strcat(keyserver->host,domain);
2343
2344   append_to_strlist(&list,name);
2345
2346   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2347
2348   free_strlist(list);
2349
2350   free_keyserver_spec(keyserver);
2351
2352   return rc;
2353 }