Ask to insert the right OpenPGP card.
[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
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 = gcry_pk_algo_name (keyrec->type);
487
488       if(str)
489         printf("%s ",str);
490       else
491         printf("unknown ");
492     }
493
494   switch(keyrec->desc.mode)
495     {
496       /* If the keyserver helper gave us a short keyid, we have no
497          choice but to use it.  Do check --keyid-format to add a 0x if
498          needed. */
499     case KEYDB_SEARCH_MODE_SHORT_KID:
500       printf("key %s%08lX",
501              (opt.keyid_format==KF_0xSHORT
502               || opt.keyid_format==KF_0xLONG)?"0x":"",
503              (ulong)keyrec->desc.u.kid[1]);
504       break;
505
506       /* However, if it gave us a long keyid, we can honor
507          --keyid-format */
508     case KEYDB_SEARCH_MODE_LONG_KID:
509       printf("key %s",keystr(keyrec->desc.u.kid));
510       break;
511
512     case KEYDB_SEARCH_MODE_FPR16:
513       printf("key ");
514       for(i=0;i<16;i++)
515         printf("%02X",keyrec->desc.u.fpr[i]);
516       break;
517
518     case KEYDB_SEARCH_MODE_FPR20:
519       printf("key ");
520       for(i=0;i<20;i++)
521         printf("%02X",keyrec->desc.u.fpr[i]);
522       break;
523
524     default:
525       BUG();
526       break;
527     }
528
529   if(keyrec->createtime>0)
530     {
531       printf(", ");
532       printf(_("created: %s"),strtimestamp(keyrec->createtime));
533     }
534
535   if(keyrec->expiretime>0)
536     {
537       printf(", ");
538       printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
539     }
540
541   if(keyrec->flags&1)
542     printf(" (%s)",_("revoked"));
543   if(keyrec->flags&2)
544     printf(" (%s)",_("disabled"));
545   if(keyrec->flags&4)
546     printf(" (%s)",_("expired"));
547
548   printf("\n");
549 }
550
551 /* Returns a keyrec (which must be freed) once a key is complete, and
552    NULL otherwise.  Call with a NULL keystring once key parsing is
553    complete to return any unfinished keys. */
554 static struct keyrec *
555 parse_keyrec(char *keystring)
556 {
557   static struct keyrec *work=NULL;
558   struct keyrec *ret=NULL;
559   char *record;
560   int i;
561
562   if(keystring==NULL)
563     {
564       if(work==NULL)
565         return NULL;
566       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
567         {
568           xfree(work);
569           return NULL;
570         }
571       else
572         {
573           ret=work;
574           work=NULL;
575           return ret;
576         }
577     }
578
579   if(work==NULL)
580     {
581       work=xmalloc_clear(sizeof(struct keyrec));
582       work->uidbuf=iobuf_temp();
583     }
584
585   /* Remove trailing whitespace */
586   for(i=strlen(keystring);i>0;i--)
587     if(ascii_isspace(keystring[i-1]))
588       keystring[i-1]='\0';
589     else
590       break;
591
592   if((record=strsep(&keystring,":"))==NULL)
593     return ret;
594
595   if(ascii_strcasecmp("pub",record)==0)
596     {
597       char *tok;
598
599       if(work->desc.mode)
600         {
601           ret=work;
602           work=xmalloc_clear(sizeof(struct keyrec));
603           work->uidbuf=iobuf_temp();
604         }
605
606       if((tok=strsep(&keystring,":"))==NULL)
607         return ret;
608
609       classify_user_id(tok,&work->desc);
610       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
611          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
612          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
613          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
614         {
615           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
616           return ret;
617         }
618
619       /* Note all items after this are optional.  This allows us to
620          have a pub line as simple as pub:keyid and nothing else. */
621
622       work->lines++;
623
624       if((tok=strsep(&keystring,":"))==NULL)
625         return ret;
626
627       work->type=atoi(tok);
628
629       if((tok=strsep(&keystring,":"))==NULL)
630         return ret;
631
632       work->size=atoi(tok);
633
634       if((tok=strsep(&keystring,":"))==NULL)
635         return ret;
636
637       if(atoi(tok)<=0)
638         work->createtime=0;
639       else
640         work->createtime=atoi(tok);
641
642       if((tok=strsep(&keystring,":"))==NULL)
643         return ret;
644
645       if(atoi(tok)<=0)
646         work->expiretime=0;
647       else
648         {
649           work->expiretime=atoi(tok);
650           /* Force the 'e' flag on if this key is expired. */
651           if(work->expiretime<=make_timestamp())
652             work->flags|=4;
653         }
654
655       if((tok=strsep(&keystring,":"))==NULL)
656         return ret;
657
658       while(*tok)
659         switch(*tok++)
660           {
661           case 'r':
662           case 'R':
663             work->flags|=1;
664             break;
665             
666           case 'd':
667           case 'D':
668             work->flags|=2;
669             break;
670
671           case 'e':
672           case 'E':
673             work->flags|=4;
674             break;
675           }
676     }
677   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
678     {
679       char *userid,*tok,*decoded;
680
681       if((tok=strsep(&keystring,":"))==NULL)
682         return ret;
683
684       if(strlen(tok)==0)
685         return ret;
686
687       userid=tok;
688
689       /* By definition, de-%-encoding is always smaller than the
690          original string so we can decode in place. */
691
692       i=0;
693
694       while(*tok)
695         if(tok[0]=='%' && tok[1] && tok[2])
696           {
697             int c;
698
699             userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c;
700             i++;
701             tok+=3;
702           }
703         else
704           userid[i++]=*tok++;
705
706       /* We don't care about the other info provided in the uid: line
707          since no keyserver supports marking userids with timestamps
708          or revoked/expired/disabled yet. */
709
710       /* No need to check for control characters, as utf8_to_native
711          does this for us. */
712
713       decoded=utf8_to_native(userid,i,0);
714       if(strlen(decoded)>opt.screen_columns-10)
715         decoded[opt.screen_columns-10]='\0';
716       iobuf_writestr(work->uidbuf,decoded);
717       xfree(decoded);
718       iobuf_writestr(work->uidbuf,"\n\t");
719       work->lines++;
720     }
721
722   /* Ignore any records other than "pri" and "uid" for easy future
723      growth. */
724
725   return ret;
726 }
727
728 /* TODO: do this as a list sent to keyserver_work rather than calling
729    it once for each key to get the correct counts after the import
730    (cosmetics, really) and to better take advantage of the keyservers
731    that can do multiple fetches in one go (LDAP). */
732 static int
733 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
734 {
735   char *answer;
736
737   fflush (stdout);
738
739   if(count && opt.command_fd==-1)
740     {
741       static int from=1;
742       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
743       from=numdesc+1;
744     }
745
746   answer=cpr_get_no_help("keysearch.prompt",
747                          _("Enter number(s), N)ext, or Q)uit > "));
748   /* control-d */
749   if(answer[0]=='\x04')
750     {
751       printf("Q\n");
752       answer[0]='q';
753     }
754
755   if(answer[0]=='q' || answer[0]=='Q')
756     {
757       xfree(answer);
758       return 1;
759     }
760   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
761     {
762       char *split=answer,*num;
763
764       while((num=strsep(&split," ,"))!=NULL)
765         if(atoi(num)>=1 && atoi(num)<=numdesc)
766           keyserver_work(KS_GET,NULL,&desc[atoi(num)-1],1,
767                          NULL,NULL,opt.keyserver);
768
769       xfree(answer);
770       return 1;
771     }
772
773   return 0;
774 }
775
776 /* Count and searchstr are just for cosmetics.  If the count is too
777    small, it will grow safely.  If negative it disables the "Key x-y
778    of z" messages.  searchstr should be UTF-8 (rather than native). */
779 static void
780 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
781 {
782   int i=0,validcount=0,started=0,header=0,count=1;
783   unsigned int maxlen,buflen,numlines=0;
784   KEYDB_SEARCH_DESC *desc;
785   byte *line=NULL;
786   char *localstr=NULL;
787
788   if(searchstr)
789     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
790
791   desc=xmalloc(count*sizeof(KEYDB_SEARCH_DESC));
792
793   for(;;)
794     {
795       struct keyrec *keyrec;
796       int rl;
797
798       maxlen=1024;
799       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
800
801       if(opt.with_colons)
802         {
803           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
804              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
805             {
806               header=1;
807               continue;
808             }
809           else if(ascii_strncasecmp("SEARCH ",line,7)==0
810                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
811             continue;
812
813           printf("%s",line);
814         }
815
816       /* Look for an info: line.  The only current info: values
817          defined are the version and key count. */
818       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
819         {
820           char *tok,*str=&line[5];
821
822           if((tok=strsep(&str,":"))!=NULL)
823             {
824               int version;
825
826               if(sscanf(tok,"%d",&version)!=1)
827                 version=1;
828
829               if(version!=1)
830                 {
831                   log_error(_("invalid keyserver protocol "
832                               "(us %d!=handler %d)\n"),1,version);
833                   break;
834                 }
835             }
836
837           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
838             {
839               if(count==0)
840                 goto notfound;
841               else if(count<0)
842                 count=10;
843               else
844                 validcount=1;
845
846               desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
847             }
848
849           started=1;
850           continue;
851         }
852
853       if(rl==0)
854         {
855           keyrec=parse_keyrec(NULL);
856
857           if(keyrec==NULL)
858             {
859               if(i==0)
860                 {
861                   count=0;
862                   break;
863                 }
864
865               if(i!=count)
866                 validcount=0;
867
868               if (opt.with_colons && opt.batch)
869                 break;
870                 
871               for(;;)
872                 {
873                   if(show_prompt(desc,i,validcount?count:0,localstr))
874                     break;
875                   validcount=0;
876                 }
877
878               break;
879             }
880         }
881       else
882         keyrec=parse_keyrec(line);
883
884       if(i==count)
885         {
886           /* keyserver helper sent more keys than they claimed in the
887              info: line. */
888           count+=10;
889           desc=xrealloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
890           validcount=0;
891         }
892
893       if(keyrec)
894         {
895           desc[i]=keyrec->desc;
896
897           if(!opt.with_colons)
898             {
899               /* screen_lines - 1 for the prompt. */
900               if(numlines+keyrec->lines>opt.screen_lines-1)
901                 {
902                   if(show_prompt(desc,i,validcount?count:0,localstr))
903                     break;
904                   else
905                     numlines=0;
906                 }
907
908               print_keyrec(i+1,keyrec);
909             }
910
911           numlines+=keyrec->lines;
912           iobuf_close(keyrec->uidbuf);
913           xfree(keyrec);
914
915           started=1;
916           i++;
917         }
918     }
919
920  notfound:
921   /* Leave this commented out or now, and perhaps for a very long
922      time.  All HKPish servers return HTML error messages for
923      no-key-found. */
924   /* 
925      if(!started)
926      log_info(_("keyserver does not support searching\n"));
927      else
928   */
929   if(count==0)
930     {
931       if(localstr)
932         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
933       else
934         log_info(_("key not found on keyserver\n"));
935     }
936
937   xfree(localstr);
938   xfree(desc);
939   xfree(line);
940 }
941
942 /* We sometimes want to use a different gpgkeys_xxx for a given
943    protocol (for example, ldaps is handled by gpgkeys_ldap).  Map
944    these here. */
945 static const char *
946 keyserver_typemap(const char *type)
947 {
948   if(strcmp(type,"ldaps")==0)
949     return "ldap";
950   else if(strcmp(type,"hkps")==0)
951     return "hkp";
952   else
953     return type;
954 }
955
956 /* The PGP LDAP and the curl fetch-a-LDAP-object methodologies are
957    sufficiently different that we can't use curl to do LDAP. */
958 static int
959 direct_uri_map(const char *scheme,unsigned int is_direct)
960 {
961   if(is_direct && strcmp(scheme,"ldap")==0)
962     return 1;
963
964   return 0;
965 }
966
967 #if GNUPG_MAJOR_VERSION == 2
968 #define GPGKEYS_PREFIX "gpg2keys_"
969 #else
970 #define GPGKEYS_PREFIX "gpgkeys_"
971 #endif
972 #define GPGKEYS_CURL GPGKEYS_PREFIX "curl" EXEEXT
973 #define GPGKEYS_PREFIX_LEN (strlen(GPGKEYS_CURL))
974 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
975 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
976
977 static int 
978 keyserver_spawn(enum ks_action action,strlist_t list,KEYDB_SEARCH_DESC *desc,
979                 int count,int *prog,unsigned char **fpr,size_t *fpr_len,
980                 struct keyserver_spec *keyserver)
981 {
982   int ret=0,i,gotversion=0,outofband=0;
983   strlist_t temp;
984   unsigned int maxlen,buflen;
985   char *command,*end,*searchstr=NULL;
986   byte *line=NULL;
987   struct exec_info *spawn;
988   const char *scheme;
989   const char *libexecdir = gnupg_libexecdir ();
990
991   assert(keyserver);
992
993 #ifdef EXEC_TEMPFILE_ONLY
994   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
995 #endif
996
997   /* Build the filename for the helper to execute */
998   scheme=keyserver_typemap(keyserver->scheme);
999
1000 #ifdef DISABLE_KEYSERVER_PATH
1001   /* Destroy any path we might have.  This is a little tricky,
1002      portability-wise.  It's not correct to delete the PATH
1003      environment variable, as that may fall back to a system built-in
1004      PATH.  Similarly, it is not correct to set PATH to the null
1005      string (PATH="") since this actually deletes the PATH environment
1006      variable under MinGW.  The safest thing to do here is to force
1007      PATH to be GNUPG_LIBEXECDIR.  All this is not that meaningful on
1008      Unix-like systems (since we're going to give a full path to
1009      gpgkeys_foo), but on W32 it prevents loading any DLLs from
1010      directories in %PATH%.
1011
1012      After some more thinking about this we came to the conclusion
1013      that it is better to load the helpers from the directory where
1014      the program of this process lives.  Fortunately Windows provides
1015      a way to retrieve this and our gnupg_libexecdir function has been
1016      modified to return just this.  Setting the exec-path is not
1017      anymore required.  
1018        set_exec_path(libexecdir);
1019  */
1020 #else
1021   if(opt.exec_path_set)
1022     {
1023       /* If exec-path was set, and DISABLE_KEYSERVER_PATH is
1024          undefined, then don't specify a full path to gpgkeys_foo, so
1025          that the PATH can work. */
1026       command=xmalloc(GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1027       command[0]='\0';
1028     }
1029   else
1030 #endif
1031     {
1032       /* Specify a full path to gpgkeys_foo. */
1033       command=xmalloc(strlen(libexecdir)+strlen(DIRSEP_S)+
1034                       GPGKEYS_PREFIX_LEN+strlen(scheme)+3+strlen(EXEEXT)+1);
1035       strcpy(command,libexecdir);
1036       strcat(command,DIRSEP_S);
1037     }
1038
1039   end=command+strlen(command);
1040
1041   /* Build a path for the keyserver helper.  If it is direct_uri
1042      (i.e. an object fetch and not a keyserver), then add "_uri" to
1043      the end to distinguish the keyserver helper from an object
1044      fetcher that can speak that protocol (this is a problem for
1045      LDAP). */
1046
1047   strcat(command,GPGKEYS_PREFIX); 
1048   strcat(command,scheme);
1049
1050   /* This "_uri" thing is in case we need to call a direct handler
1051      instead of the keyserver handler.  This lets us use gpgkeys_curl
1052      or gpgkeys_ldap_uri (we don't provide it, but a user might)
1053      instead of gpgkeys_ldap to fetch things like
1054      ldap://keyserver.pgp.com/o=PGP%20keys?pgpkey?sub?pgpkeyid=99242560 */
1055
1056   if(direct_uri_map(scheme,keyserver->flags.direct_uri))
1057     strcat(command,"_uri");
1058
1059   strcat(command,EXEEXT);
1060
1061   /* Can we execute it?  If not, try curl as our catchall. */
1062   if(path_access(command,X_OK)!=0)
1063     strcpy(end,GPGKEYS_CURL);
1064
1065   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
1066     {
1067       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
1068         {
1069           command=xrealloc(command,strlen(command)+
1070                             strlen(KEYSERVER_ARGS_KEEP)+1);
1071           strcat(command,KEYSERVER_ARGS_KEEP);
1072         }
1073       else
1074         {
1075           command=xrealloc(command,strlen(command)+
1076                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
1077           strcat(command,KEYSERVER_ARGS_NOKEEP);  
1078         }
1079
1080       ret=exec_write(&spawn,NULL,command,NULL,0,0);
1081     }
1082   else
1083     ret=exec_write(&spawn,command,NULL,NULL,0,0);
1084
1085   xfree(command);
1086
1087   if(ret)
1088     return ret;
1089
1090   fprintf(spawn->tochild,
1091           "# This is a GnuPG %s keyserver communications file\n",VERSION);
1092   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1093   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
1094   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
1095
1096   if(keyserver->opaque)
1097     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
1098   else
1099     {
1100       if(keyserver->auth)
1101         fprintf(spawn->tochild,"AUTH %s\n",keyserver->auth);
1102
1103       if(keyserver->host)
1104         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
1105
1106       if(keyserver->port)
1107         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
1108
1109       if(keyserver->path)
1110         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
1111     }
1112
1113   /* Write global options */
1114
1115   for(temp=opt.keyserver_options.other;temp;temp=temp->next)
1116     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1117
1118   /* Write per-keyserver options */
1119
1120   for(temp=keyserver->options;temp;temp=temp->next)
1121     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
1122
1123   switch(action)
1124     {
1125     case KS_GET:
1126       {
1127         fprintf(spawn->tochild,"COMMAND GET\n\n");
1128
1129         /* Which keys do we want? */
1130
1131         for(i=0;i<count;i++)
1132           {
1133             int quiet=0;
1134
1135             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
1136               {
1137                 int f;
1138
1139                 fprintf(spawn->tochild,"0x");
1140
1141                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
1142                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1143
1144                 fprintf(spawn->tochild,"\n");
1145               }
1146             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
1147               {
1148                 int f;
1149
1150                 fprintf(spawn->tochild,"0x");
1151
1152                 for(f=0;f<16;f++)
1153                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
1154
1155                 fprintf(spawn->tochild,"\n");
1156               }
1157             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
1158               fprintf(spawn->tochild,"0x%08lX%08lX\n",
1159                       (ulong)desc[i].u.kid[0],
1160                       (ulong)desc[i].u.kid[1]);
1161             else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
1162               fprintf(spawn->tochild,"0x%08lX\n",
1163                       (ulong)desc[i].u.kid[1]);
1164             else if(desc[i].mode==KEYDB_SEARCH_MODE_EXACT)
1165               {
1166                 fprintf(spawn->tochild,"0x0000000000000000\n");
1167                 quiet=1;
1168               }
1169             else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
1170               continue;
1171             else
1172               BUG();
1173
1174             if(!quiet)
1175               {
1176                 if(keyserver->host)
1177                   log_info(_("requesting key %s from %s server %s\n"),
1178                            keystr_from_desc(&desc[i]),
1179                            keyserver->scheme,keyserver->host);
1180                 else
1181                   log_info(_("requesting key %s from %s\n"),
1182                            keystr_from_desc(&desc[i]),keyserver->uri);
1183               }
1184           }
1185
1186         fprintf(spawn->tochild,"\n");
1187
1188         break;
1189       }
1190
1191     case KS_GETNAME:
1192       {
1193         strlist_t key;
1194
1195         fprintf(spawn->tochild,"COMMAND GETNAME\n\n");
1196
1197         /* Which names do we want? */
1198
1199         for(key=list;key!=NULL;key=key->next)
1200           fprintf(spawn->tochild,"%s\n",key->d);
1201
1202         fprintf(spawn->tochild,"\n");
1203
1204         if(keyserver->host)
1205           log_info(_("searching for names from %s server %s\n"),
1206                    keyserver->scheme,keyserver->host);
1207         else
1208           log_info(_("searching for names from %s\n"),keyserver->uri);
1209
1210         break;
1211       }
1212
1213     case KS_SEND:
1214       {
1215         strlist_t key;
1216
1217         /* Note the extra \n here to send an empty keylist block */
1218         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
1219
1220         for(key=list;key!=NULL;key=key->next)
1221           {
1222             armor_filter_context_t *afx;
1223             IOBUF buffer = iobuf_temp ();
1224             KBNODE block;
1225
1226             temp=NULL;
1227             add_to_strlist(&temp,key->d);
1228
1229             afx = new_armor_context ();
1230             afx->what = 1;
1231             /* Tell the armor filter to use Unix-style \n line
1232                endings, since we're going to fprintf this to a file
1233                that (on Win32) is open in text mode.  The win32 stdio
1234                will transform the \n to \r\n and we'll end up with the
1235                proper line endings on win32.  This is a no-op on
1236                Unix. */
1237             afx->eol[0] = '\n';
1238             push_armor_filter (afx, buffer);
1239             release_armor_context (afx);
1240
1241             /* TODO: Remove Comment: lines from keys exported this
1242                way? */
1243
1244             if(export_pubkeys_stream(buffer,temp,&block,
1245                                      opt.keyserver_options.export_options)==-1)
1246               iobuf_close(buffer);
1247             else
1248               {
1249                 KBNODE node;
1250
1251                 iobuf_flush_temp(buffer);
1252
1253                 merge_keys_and_selfsig(block);
1254
1255                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
1256                         (ulong)block->pkt->pkt.public_key->keyid[0],
1257                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1258
1259                 for(node=block;node;node=node->next)
1260                   {
1261                     switch(node->pkt->pkttype)
1262                       {
1263                       default:
1264                         continue;
1265
1266                       case PKT_PUBLIC_KEY:
1267                       case PKT_PUBLIC_SUBKEY:
1268                         {
1269                           PKT_public_key *pk=node->pkt->pkt.public_key;
1270
1271                           keyid_from_pk(pk,NULL);
1272
1273                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
1274                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
1275                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
1276                                   pk->pubkey_algo,
1277                                   nbits_from_pk(pk),
1278                                   pk->timestamp,
1279                                   pk->expiredate);
1280
1281                           if(pk->is_revoked)
1282                             fprintf(spawn->tochild,"r");
1283                           if(pk->has_expired)
1284                             fprintf(spawn->tochild,"e");
1285
1286                           fprintf(spawn->tochild,"\n");
1287                         }
1288                         break;
1289
1290                       case PKT_USER_ID:
1291                         {
1292                           PKT_user_id *uid=node->pkt->pkt.user_id;
1293                           int r;
1294
1295                           if(uid->attrib_data)
1296                             continue;
1297
1298                           fprintf(spawn->tochild,"uid:");
1299
1300                           /* Quote ':', '%', and any 8-bit
1301                              characters */
1302                           for(r=0;r<uid->len;r++)
1303                             {
1304                               if(uid->name[r]==':' || uid->name[r]=='%'
1305                                  || uid->name[r]&0x80)
1306                                 fprintf(spawn->tochild,"%%%02X",
1307                                         (byte)uid->name[r]);
1308                               else
1309                                 fprintf(spawn->tochild,"%c",uid->name[r]);
1310                             }
1311
1312                           fprintf(spawn->tochild,":%u:%u:",
1313                                   uid->created,uid->expiredate);
1314
1315                           if(uid->is_revoked)
1316                             fprintf(spawn->tochild,"r");
1317                           if(uid->is_expired)
1318                             fprintf(spawn->tochild,"e");
1319
1320                           fprintf(spawn->tochild,"\n");
1321                         }
1322                         break;
1323
1324                         /* This bit is really for the benefit of
1325                            people who store their keys in LDAP
1326                            servers.  It makes it easy to do queries
1327                            for things like "all keys signed by
1328                            Isabella". */
1329                       case PKT_SIGNATURE:
1330                         {
1331                           PKT_signature *sig=node->pkt->pkt.signature;
1332
1333                           if(!IS_UID_SIG(sig))
1334                             continue;
1335
1336                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1337                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1338                                   sig->sig_class,sig->timestamp,
1339                                   sig->expiredate);
1340                         }
1341                         break;
1342                       }
1343                   }
1344
1345                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1346                         (ulong)block->pkt->pkt.public_key->keyid[0],
1347                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1348
1349                 fprintf(spawn->tochild,"KEY %08lX%08lX BEGIN\n",
1350                         (ulong)block->pkt->pkt.public_key->keyid[0],
1351                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1352                 fwrite(iobuf_get_temp_buffer(buffer),
1353                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1354                 fprintf(spawn->tochild,"KEY %08lX%08lX END\n",
1355                         (ulong)block->pkt->pkt.public_key->keyid[0],
1356                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1357
1358                 iobuf_close(buffer);
1359
1360                 if(keyserver->host)
1361                   log_info(_("sending key %s to %s server %s\n"),
1362                            keystr(block->pkt->pkt.public_key->keyid),
1363                            keyserver->scheme,keyserver->host);
1364                 else
1365                   log_info(_("sending key %s to %s\n"),
1366                            keystr(block->pkt->pkt.public_key->keyid),
1367                            keyserver->uri);
1368
1369                 release_kbnode(block);
1370               }
1371
1372             free_strlist(temp);
1373           }
1374
1375         break;
1376       }
1377
1378     case KS_SEARCH:
1379       {
1380         strlist_t key;
1381
1382         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1383
1384         /* Which keys do we want?  Remember that the gpgkeys_ program
1385            is going to lump these together into a search string. */
1386
1387         for(key=list;key!=NULL;key=key->next)
1388           {
1389             fprintf(spawn->tochild,"%s\n",key->d);
1390             if(key!=list)
1391               {
1392                 searchstr=xrealloc(searchstr,
1393                                     strlen(searchstr)+strlen(key->d)+2);
1394                 strcat(searchstr," ");
1395               }
1396             else
1397               {
1398                 searchstr=xmalloc(strlen(key->d)+1);
1399                 searchstr[0]='\0';
1400               }
1401
1402             strcat(searchstr,key->d);
1403           }
1404
1405         fprintf(spawn->tochild,"\n");
1406
1407         if(keyserver->host)
1408           log_info(_("searching for \"%s\" from %s server %s\n"),
1409                    searchstr,keyserver->scheme,keyserver->host);
1410         else
1411           log_info(_("searching for \"%s\" from %s\n"),
1412                    searchstr,keyserver->uri);
1413
1414         break;
1415       }
1416
1417     default:
1418       log_fatal(_("no keyserver action!\n"));
1419       break;
1420     }
1421
1422   /* Done sending, so start reading. */
1423   ret=exec_read(spawn);
1424   if(ret)
1425     goto fail;
1426
1427   /* Now handle the response */
1428
1429   for(;;)
1430     {
1431       int plen;
1432       char *ptr;
1433
1434       maxlen=1024;
1435       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1436         {
1437           ret = gpg_error_from_syserror ();
1438           goto fail; /* i.e. EOF */
1439         }
1440
1441       ptr=line;
1442
1443       /* remove trailing whitespace */
1444       plen=strlen(ptr);
1445       while(plen>0 && ascii_isspace(ptr[plen-1]))
1446         plen--;
1447       plen[ptr]='\0';
1448
1449       if(*ptr=='\0')
1450         break;
1451
1452       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1453         {
1454           gotversion=1;
1455
1456           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1457             {
1458               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1459                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1460               goto fail;
1461             }
1462         }
1463       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1464         {
1465           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1466             log_info(_("WARNING: keyserver handler from a different"
1467                        " version of GnuPG (%s)\n"),&ptr[8]);
1468         }
1469       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1470         outofband=1; /* Currently the only OPTION */
1471     }
1472
1473   if(!gotversion)
1474     {
1475       log_error(_("keyserver did not send VERSION\n"));
1476       goto fail;
1477     }
1478
1479   if(!outofband)
1480     switch(action)
1481       {
1482       case KS_GET:
1483       case KS_GETNAME:
1484         {
1485           void *stats_handle;
1486
1487           stats_handle=import_new_stats_handle();
1488
1489           /* Slurp up all the key data.  In the future, it might be
1490              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1491              It's harmless to ignore them, but ignoring them does make
1492              gpg complain about "no valid OpenPGP data found".  One
1493              way to do this could be to continue parsing this
1494              line-by-line and make a temp iobuf for each key. */
1495
1496           import_keys_stream(spawn->fromchild,stats_handle,fpr,fpr_len,
1497                              opt.keyserver_options.import_options);
1498
1499           import_print_stats(stats_handle);
1500           import_release_stats_handle(stats_handle);
1501
1502           break;
1503         }
1504
1505         /* Nothing to do here */
1506       case KS_SEND:
1507         break;
1508
1509       case KS_SEARCH:
1510         keyserver_search_prompt(spawn->fromchild,searchstr);
1511         break;
1512
1513       default:
1514         log_fatal(_("no keyserver action!\n"));
1515         break;
1516       }
1517
1518  fail:
1519   xfree(line);
1520   xfree(searchstr);
1521
1522
1523   *prog=exec_finish(spawn);
1524
1525   return ret;
1526 }
1527
1528 static int 
1529 keyserver_work(enum ks_action action,strlist_t list,KEYDB_SEARCH_DESC *desc,
1530                int count,unsigned char **fpr,size_t *fpr_len,
1531                struct keyserver_spec *keyserver)
1532 {
1533   int rc=0,ret=0;
1534
1535   if(!keyserver)
1536     {
1537       log_error(_("no keyserver known (use option --keyserver)\n"));
1538       return G10ERR_BAD_URI;
1539     }
1540
1541 #ifdef DISABLE_KEYSERVER_HELPERS
1542
1543   log_error(_("external keyserver calls are not supported in this build\n"));
1544   return G10ERR_KEYSERVER;
1545
1546 #else
1547   /* Spawn a handler */
1548
1549   rc=keyserver_spawn(action,list,desc,count,&ret,fpr,fpr_len,keyserver);
1550   if(ret)
1551     {
1552       switch(ret)
1553         {
1554         case KEYSERVER_SCHEME_NOT_FOUND:
1555           log_error(_("no handler for keyserver scheme `%s'\n"),
1556                     keyserver->scheme);
1557           break;
1558
1559         case KEYSERVER_NOT_SUPPORTED:
1560           log_error(_("action `%s' not supported with keyserver "
1561                       "scheme `%s'\n"),
1562                     action==KS_GET?"get":action==KS_SEND?"send":
1563                     action==KS_SEARCH?"search":"unknown",
1564                     keyserver->scheme);
1565           break;
1566
1567         case KEYSERVER_VERSION_ERROR:
1568           log_error(_(GPGKEYS_PREFIX "%s does not support"
1569                       " handler version %d\n"),
1570                     keyserver_typemap(keyserver->scheme),
1571                     KEYSERVER_PROTO_VERSION);
1572           break;
1573
1574         case KEYSERVER_TIMEOUT:
1575           log_error(_("keyserver timed out\n"));
1576           break;
1577
1578         case KEYSERVER_INTERNAL_ERROR:
1579         default:
1580           log_error(_("keyserver internal error\n"));
1581           break;
1582         }
1583
1584       return G10ERR_KEYSERVER;
1585     }
1586
1587   if(rc)
1588     {
1589       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1590
1591       return rc;
1592     }
1593
1594   return 0;
1595 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1596 }
1597
1598 int 
1599 keyserver_export(strlist_t users)
1600 {
1601   strlist_t sl=NULL;
1602   KEYDB_SEARCH_DESC desc;
1603   int rc=0;
1604
1605   /* Weed out descriptors that we don't support sending */
1606   for(;users;users=users->next)
1607     {
1608       classify_user_id (users->d, &desc);
1609       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1610          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1611          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1612          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1613         {
1614           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1615           continue;
1616         }
1617       else
1618         append_to_strlist(&sl,users->d);
1619     }
1620
1621   if(sl)
1622     {
1623       rc=keyserver_work(KS_SEND,sl,NULL,0,NULL,NULL,opt.keyserver);
1624       free_strlist(sl);
1625     }
1626
1627   return rc;
1628 }
1629
1630 int 
1631 keyserver_import(strlist_t users)
1632 {
1633   KEYDB_SEARCH_DESC *desc;
1634   int num=100,count=0;
1635   int rc=0;
1636
1637   /* Build a list of key ids */
1638   desc=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1639
1640   for(;users;users=users->next)
1641     {
1642       classify_user_id (users->d, &desc[count]);
1643       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1644          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1645          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1646          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1647         {
1648           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1649           continue;
1650         }
1651
1652       count++;
1653       if(count==num)
1654         {
1655           num+=100;
1656           desc=xrealloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1657         }
1658     }
1659
1660   if(count>0)
1661     rc=keyserver_work(KS_GET,NULL,desc,count,NULL,NULL,opt.keyserver);
1662
1663   xfree(desc);
1664
1665   return rc;
1666 }
1667
1668 int
1669 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1670                         struct keyserver_spec *keyserver)
1671 {
1672   KEYDB_SEARCH_DESC desc;
1673
1674   memset(&desc,0,sizeof(desc));
1675
1676   if(fprint_len==16)
1677     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1678   else if(fprint_len==20)
1679     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1680   else
1681     return -1;
1682
1683   memcpy(desc.u.fpr,fprint,fprint_len);
1684
1685   /* TODO: Warn here if the fingerprint we got doesn't match the one
1686      we asked for? */
1687   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1688 }
1689
1690 int 
1691 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1692 {
1693   KEYDB_SEARCH_DESC desc;
1694
1695   memset(&desc,0,sizeof(desc));
1696
1697   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1698   desc.u.kid[0]=keyid[0];
1699   desc.u.kid[1]=keyid[1];
1700
1701   return keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,keyserver);
1702 }
1703
1704 /* code mostly stolen from do_export_stream */
1705 static int 
1706 keyidlist(strlist_t users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1707 {
1708   int rc=0,ndesc,num=100;
1709   KBNODE keyblock=NULL,node;
1710   KEYDB_HANDLE kdbhd;
1711   KEYDB_SEARCH_DESC *desc;
1712   strlist_t sl;
1713
1714   *count=0;
1715
1716   *klist=xmalloc(sizeof(KEYDB_SEARCH_DESC)*num);
1717
1718   kdbhd=keydb_new(0);
1719
1720   if(!users)
1721     {
1722       ndesc = 1;
1723       desc = xmalloc_clear ( ndesc * sizeof *desc);
1724       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1725     }
1726   else
1727     {
1728       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
1729         ;
1730       desc = xmalloc ( ndesc * sizeof *desc);
1731         
1732       for (ndesc=0, sl=users; sl; sl = sl->next)
1733         {
1734           if(classify_user_id (sl->d, desc+ndesc))
1735             ndesc++;
1736           else
1737             log_error (_("key \"%s\" not found: %s\n"),
1738                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1739         }
1740     }
1741
1742   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1743     {
1744       if (!users) 
1745         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1746
1747       /* read the keyblock */
1748       rc = keydb_get_keyblock (kdbhd, &keyblock );
1749       if( rc )
1750         {
1751           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1752           goto leave;
1753         }
1754
1755       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1756         {
1757           /* This is to work around a bug in some keyservers (pksd and
1758              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1759              The answer is to refresh both the correct v4 keyid
1760              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1761              This only happens for key refresh using the HKP scheme
1762              and if the refresh-add-fake-v3-keyids keyserver option is
1763              set. */
1764           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1765              node->pkt->pkt.public_key->version>=4)
1766             {
1767               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1768               v3_keyid (node->pkt->pkt.public_key->pkey[0],
1769                         (*klist)[*count].u.kid);
1770               (*count)++;
1771
1772               if(*count==num)
1773                 {
1774                   num+=100;
1775                   *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1776                 }
1777             }
1778
1779           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1780              This is because it's easy to calculate any sort of keyid
1781              from a v4 fingerprint, but not a v3 fingerprint. */
1782
1783           if(node->pkt->pkt.public_key->version<4)
1784             {
1785               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1786               keyid_from_pk(node->pkt->pkt.public_key,
1787                             (*klist)[*count].u.kid);
1788             }
1789           else
1790             {
1791               size_t dummy;
1792
1793               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1794               fingerprint_from_pk(node->pkt->pkt.public_key,
1795                                   (*klist)[*count].u.fpr,&dummy);
1796             }
1797
1798           /* This is a little hackish, using the skipfncvalue as a
1799              void* pointer to the keyserver spec, but we don't need
1800              the skipfnc here, and it saves having an additional field
1801              for this (which would be wasted space most of the
1802              time). */
1803
1804           (*klist)[*count].skipfncvalue=NULL;
1805
1806           /* Are we honoring preferred keyservers? */
1807           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1808             {
1809               PKT_user_id *uid=NULL;
1810               PKT_signature *sig=NULL;
1811
1812               merge_keys_and_selfsig(keyblock);
1813
1814               for(node=node->next;node;node=node->next)
1815                 {
1816                   if(node->pkt->pkttype==PKT_USER_ID
1817                      && node->pkt->pkt.user_id->is_primary)
1818                     uid=node->pkt->pkt.user_id;
1819                   else if(node->pkt->pkttype==PKT_SIGNATURE
1820                           && node->pkt->pkt.signature->
1821                           flags.chosen_selfsig && uid)
1822                     {
1823                       sig=node->pkt->pkt.signature;
1824                       break;
1825                     }
1826                 }
1827
1828               /* Try and parse the keyserver URL.  If it doesn't work,
1829                  then we end up writing NULL which indicates we are
1830                  the same as any other key. */
1831               if(sig)
1832                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1833             }
1834
1835           (*count)++;
1836
1837           if(*count==num)
1838             {
1839               num+=100;
1840               *klist=xrealloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1841             }
1842         }
1843     }
1844
1845   if(rc==-1)
1846     rc=0;
1847   
1848  leave:
1849   if(rc)
1850     xfree(*klist);
1851   xfree(desc);
1852   keydb_release(kdbhd);
1853   release_kbnode(keyblock);
1854
1855   return rc;
1856 }
1857
1858 /* Note this is different than the original HKP refresh.  It allows
1859    usernames to refresh only part of the keyring. */
1860
1861 int
1862 keyserver_refresh(strlist_t users)
1863 {
1864   int rc,count,numdesc,fakev3=0;
1865   KEYDB_SEARCH_DESC *desc;
1866   unsigned int options=opt.keyserver_options.import_options;
1867
1868   /* We switch merge-only on during a refresh, as 'refresh' should
1869      never import new keys, even if their keyids match. */
1870   opt.keyserver_options.import_options|=IMPORT_MERGE_ONLY;
1871
1872   /* Similarly, we switch on fast-import, since refresh may make
1873      multiple import sets (due to preferred keyserver URLs).  We don't
1874      want each set to rebuild the trustdb.  Instead we do it once at
1875      the end here. */
1876   opt.keyserver_options.import_options|=IMPORT_FAST;
1877
1878   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1879      scheme, then enable fake v3 keyid generation. */
1880   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1881      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1882          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1883     fakev3=1;
1884
1885   rc=keyidlist(users,&desc,&numdesc,fakev3);
1886   if(rc)
1887     return rc;
1888
1889   count=numdesc;
1890   if(count>0)
1891     {
1892       int i;
1893
1894       /* Try to handle preferred keyserver keys first */
1895       for(i=0;i<numdesc;i++)
1896         {
1897           if(desc[i].skipfncvalue)
1898             {
1899               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1900
1901               /* We use the keyserver structure we parsed out before.
1902                  Note that a preferred keyserver without a scheme://
1903                  will be interpreted as hkp:// */
1904
1905               rc=keyserver_work(KS_GET,NULL,&desc[i],1,NULL,NULL,keyserver);
1906               if(rc)
1907                 log_info(_("WARNING: unable to refresh key %s"
1908                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
1909                          keyserver->uri,g10_errstr(rc));
1910               else
1911                 {
1912                   /* We got it, so mark it as NONE so we don't try and
1913                      get it again from the regular keyserver. */
1914
1915                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
1916                   count--;
1917                 }
1918
1919               free_keyserver_spec(keyserver);
1920             }
1921         }
1922     }
1923
1924   if(count>0)
1925     {
1926       if(opt.keyserver)
1927         {
1928           if(count==1)
1929             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
1930           else
1931             log_info(_("refreshing %d keys from %s\n"),
1932                      count,opt.keyserver->uri);
1933         }
1934
1935       rc=keyserver_work(KS_GET,NULL,desc,numdesc,NULL,NULL,opt.keyserver);
1936     }
1937
1938   xfree(desc);
1939
1940   opt.keyserver_options.import_options=options;
1941
1942   /* If the original options didn't have fast import, and the trustdb
1943      is dirty, rebuild. */
1944   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
1945     trustdb_check_or_update();
1946
1947   return rc;
1948 }
1949
1950 int
1951 keyserver_search(strlist_t tokens)
1952 {
1953   if(tokens)
1954     return keyserver_work(KS_SEARCH,tokens,NULL,0,NULL,NULL,opt.keyserver);
1955   else
1956     return 0;
1957 }
1958
1959 int
1960 keyserver_fetch(strlist_t urilist)
1961 {
1962   KEYDB_SEARCH_DESC desc;
1963   strlist_t sl;
1964   unsigned int options=opt.keyserver_options.import_options;
1965
1966   /* Switch on fast-import, since fetch can handle more than one
1967      import and we don't want each set to rebuild the trustdb.
1968      Instead we do it once at the end. */
1969   opt.keyserver_options.import_options|=IMPORT_FAST;
1970
1971   /* A dummy desc since we're not actually fetching a particular key
1972      ID */
1973   memset(&desc,0,sizeof(desc));
1974   desc.mode=KEYDB_SEARCH_MODE_EXACT;
1975
1976   for(sl=urilist;sl;sl=sl->next)
1977     {
1978       struct keyserver_spec *spec;
1979
1980       spec=parse_keyserver_uri(sl->d,1,NULL,0);
1981       if(spec)
1982         {
1983           int rc;
1984
1985           rc=keyserver_work(KS_GET,NULL,&desc,1,NULL,NULL,spec);
1986           if(rc)
1987             log_info (_("WARNING: unable to fetch URI %s: %s\n"),
1988                      sl->d,g10_errstr(rc));
1989
1990           free_keyserver_spec(spec);
1991         }
1992       else
1993         log_info (_("WARNING: unable to parse URI %s\n"),sl->d);
1994     }
1995
1996   opt.keyserver_options.import_options=options;
1997
1998   /* If the original options didn't have fast import, and the trustdb
1999      is dirty, rebuild. */
2000   if(!(opt.keyserver_options.import_options&IMPORT_FAST))
2001     trustdb_check_or_update();
2002
2003   return 0;
2004 }
2005
2006 /* Import key in a CERT or pointed to by a CERT */
2007 int
2008 keyserver_import_cert(const char *name,unsigned char **fpr,size_t *fpr_len)
2009 {
2010   char *domain,*look,*url;
2011   IOBUF key;
2012   int type,rc=G10ERR_GENERAL;
2013
2014   look=xstrdup(name);
2015
2016   domain=strrchr(look,'@');
2017   if(domain)
2018     *domain='.';
2019
2020   type=get_dns_cert(look,max_cert_size,&key,fpr,fpr_len,&url);
2021   if (!type || type == -1)
2022     {
2023       /* There might be an error in res_query which leads to an error
2024          return (-1) in the case that nothing was found.  Thus we take
2025          all errors as key not found.  */
2026       rc = G10ERR_NO_PUBKEY;
2027     }
2028   else if (type==1)
2029     {
2030       int armor_status=opt.no_armor;
2031
2032       /* CERTs are always in binary format */
2033       opt.no_armor=1;
2034
2035       rc=import_keys_stream(key,NULL,fpr,fpr_len,
2036                             opt.keyserver_options.import_options);
2037
2038       opt.no_armor=armor_status;
2039
2040       iobuf_close(key);
2041     }
2042   else if(type==2 && *fpr)
2043     {
2044       /* We only consider the IPGP type if a fingerprint was provided.
2045          This lets us select the right key regardless of what a URL
2046          points to, or get the key from a keyserver. */
2047       if(url)
2048         {
2049           struct keyserver_spec *spec;
2050
2051           spec=parse_keyserver_uri(url,1,NULL,0);
2052           if(spec)
2053             {
2054               rc=keyserver_import_fprint(*fpr,*fpr_len,spec);
2055               free_keyserver_spec(spec);
2056             }
2057         }
2058       else if(opt.keyserver)
2059         {
2060           /* If only a fingerprint is provided, try and fetch it from
2061              our --keyserver */
2062
2063           rc=keyserver_import_fprint(*fpr,*fpr_len,opt.keyserver);
2064         }
2065       else
2066         log_info(_("no keyserver known (use option --keyserver)\n"));
2067
2068       /* Give a better string here? "CERT fingerprint for \"%s\"
2069          found, but no keyserver" " known (use option
2070          --keyserver)\n" ? */
2071
2072       xfree(url);
2073     }
2074
2075   xfree(look);
2076
2077   return rc;
2078 }
2079
2080 /* Import key pointed to by a PKA record. Return the requested
2081    fingerprint in fpr. */
2082 int
2083 keyserver_import_pka(const char *name,unsigned char **fpr,size_t *fpr_len)
2084 {
2085   char *uri;
2086   int rc = G10ERR_NO_PUBKEY;
2087
2088   *fpr = xmalloc (20);
2089   *fpr_len = 20;
2090
2091   uri = get_pka_info (name, *fpr);
2092   if (uri && *uri)
2093     {
2094       /* An URI is available.  Lookup the key. */
2095       struct keyserver_spec *spec;
2096       spec = parse_keyserver_uri (uri, 1, NULL, 0);
2097       if (spec)
2098         {
2099           rc = keyserver_import_fprint (*fpr, 20, spec);
2100           free_keyserver_spec (spec);
2101         }
2102       xfree (uri);
2103     }
2104
2105   if (rc)
2106     {
2107       xfree(*fpr);
2108       *fpr = NULL;
2109     }
2110
2111   return rc;
2112 }
2113
2114 /* Import all keys that match name */
2115 int
2116 keyserver_import_name(const char *name,unsigned char **fpr,size_t *fpr_len,
2117                       struct keyserver_spec *keyserver)
2118 {
2119   strlist_t list=NULL;
2120   int rc;
2121
2122   append_to_strlist(&list,name);
2123
2124   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2125
2126   free_strlist(list);
2127
2128   return rc;
2129 }
2130
2131 /* Import a key by name using LDAP */
2132 int
2133 keyserver_import_ldap(const char *name,unsigned char **fpr,size_t *fpr_len)
2134 {
2135   char *domain;
2136   struct keyserver_spec *keyserver;
2137   strlist_t list=NULL;
2138   int rc,hostlen=1;
2139 #ifdef USE_DNS_SRV
2140   struct srventry *srvlist=NULL;
2141   int srvcount,i;
2142   char srvname[MAXDNAME];
2143 #endif
2144
2145   /* Parse out the domain */
2146   domain=strrchr(name,'@');
2147   if(!domain)
2148     return G10ERR_GENERAL;
2149
2150   domain++;
2151
2152   keyserver=xmalloc_clear(sizeof(struct keyserver_spec));
2153   keyserver->scheme=xstrdup("ldap");
2154   keyserver->host=xmalloc(1);
2155   keyserver->host[0]='\0';
2156
2157 #ifdef USE_DNS_SRV
2158   snprintf(srvname,MAXDNAME,"_pgpkey-ldap._tcp.%s",domain);
2159
2160   srvcount=getsrv(srvname,&srvlist);
2161
2162   for(i=0;i<srvcount;i++)
2163     {
2164       hostlen+=strlen(srvlist[i].target)+1;
2165       keyserver->host=xrealloc(keyserver->host,hostlen);
2166
2167       strcat(keyserver->host,srvlist[i].target);
2168
2169       if(srvlist[i].port!=389)
2170         {
2171           char port[7];
2172
2173           hostlen+=6; /* a colon, plus 5 digits (unsigned 16-bit value) */
2174           keyserver->host=xrealloc(keyserver->host,hostlen);
2175
2176           snprintf(port,7,":%u",srvlist[i].port);
2177           strcat(keyserver->host,port);
2178         }
2179         
2180       strcat(keyserver->host," ");
2181     }
2182
2183   free(srvlist);
2184 #endif
2185
2186   /* If all else fails, do the PGP Universal trick of
2187      ldap://keys.(domain) */
2188
2189   hostlen+=5+strlen(domain);
2190   keyserver->host=xrealloc(keyserver->host,hostlen);
2191   strcat(keyserver->host,"keys.");
2192   strcat(keyserver->host,domain);
2193
2194   append_to_strlist(&list,name);
2195     
2196   rc=keyserver_work(KS_GETNAME,list,NULL,0,fpr,fpr_len,keyserver);
2197
2198   free_strlist(list);
2199
2200   free_keyserver_spec(keyserver);
2201
2202   return rc;
2203 }