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