* passphrase.c (agent_get_passphrase): Use keystrs for agent strings, and
[gnupg.git] / g10 / keyserver.c
1 /* keyserver.c - generic keyserver code
2  * Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * GnuPG is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * GnuPG is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
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 "filter.h"
28 #include "keydb.h"
29 #include "status.h"
30 #include "exec.h"
31 #include "main.h"
32 #include "i18n.h"
33 #include "iobuf.h"
34 #include "memory.h"
35 #include "ttyio.h"
36 #include "options.h"
37 #include "packet.h"
38 #include "keyserver-internal.h"
39 #include "util.h"
40
41 #define GET    0
42 #define SEND   1
43 #define SEARCH 2
44
45 struct keyrec
46 {
47   KEYDB_SEARCH_DESC desc;
48   u32 createtime,expiretime;
49   int size,flags;
50   byte type;
51   IOBUF uidbuf;
52   unsigned int lines;
53 };
54
55 /* Tell remote processes about these options */
56 #define REMOTE_TELL (KEYSERVER_INCLUDE_REVOKED|KEYSERVER_INCLUDE_DISABLED|KEYSERVER_INCLUDE_SUBKEYS|KEYSERVER_TRY_DNS_SRV)
57
58 static struct parse_options keyserver_opts[]=
59   {
60     {"include-revoked",KEYSERVER_INCLUDE_REVOKED,NULL},      
61     {"include-disabled",KEYSERVER_INCLUDE_DISABLED,NULL},
62     {"include-subkeys",KEYSERVER_INCLUDE_SUBKEYS,NULL},
63     {"keep-temp-files",KEYSERVER_KEEP_TEMP_FILES,NULL},
64     {"refresh-add-fake-v3-keyids",KEYSERVER_ADD_FAKE_V3,NULL},
65     {"auto-key-retrieve",KEYSERVER_AUTO_KEY_RETRIEVE,NULL},
66     {"try-dns-srv",KEYSERVER_TRY_DNS_SRV,NULL},
67     {"honor-keyserver-url",KEYSERVER_HONOR_KEYSERVER_URL,NULL},
68     {NULL,0,NULL}
69   };
70
71 static int keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
72                           int count,struct keyserver_spec *keyserver);
73
74 int
75 parse_keyserver_options(char *options)
76 {
77   int ret=1;
78   char *tok;
79
80   while((tok=optsep(&options)))
81     {
82       if(tok[0]=='\0')
83         continue;
84
85       /* We accept quite a few possible options here - some options to
86          handle specially, the keyserver_options list, and import and
87          export options that pertain to keyserver operations.  Note
88          that you must use strncasecmp here as there might be an
89          =argument attached which will foil the use of strcasecmp. */
90
91       if(ascii_strncasecmp(tok,"verbose",7)==0)
92         opt.keyserver_options.verbose++;
93       else if(ascii_strncasecmp(tok,"no-verbose",10)==0)
94         opt.keyserver_options.verbose--;
95 #ifdef EXEC_TEMPFILE_ONLY
96       else if(ascii_strncasecmp(tok,"use-temp-files",14)==0 ||
97               ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
98         log_info(_("WARNING: keyserver option `%s' is not used"
99                    " on this platform\n"),tok);
100 #else
101       else if(ascii_strncasecmp(tok,"use-temp-files",14)==0)
102         opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
103       else if(ascii_strncasecmp(tok,"no-use-temp-files",17)==0)
104         opt.keyserver_options.options&=~KEYSERVER_USE_TEMP_FILES;
105 #endif
106       else if(!parse_options(tok,&opt.keyserver_options.options,
107                              keyserver_opts,0)
108          && !parse_import_options(tok,
109                                   &opt.keyserver_options.import_options,0)
110          && !parse_export_options(tok,
111                                   &opt.keyserver_options.export_options,0))
112         {
113           /* All of the standard options have failed, so the option is
114              destined for a keyserver plugin. */
115           char *arg=argsplit(tok);
116
117           if(arg)
118             {
119               char *joined;
120
121               joined=m_alloc(strlen(tok)+1+strlen(arg)+1);
122               /* Make a canonical name=value form with no
123                  spaces */
124               strcpy(joined,tok);
125               strcat(joined,"=");
126               strcat(joined,arg);
127               add_to_strlist(&opt.keyserver_options.other,joined);
128               m_free(joined);
129             }
130           else
131             add_to_strlist(&opt.keyserver_options.other,tok);
132         }
133     }
134
135   return ret;
136 }
137
138 void
139 free_keyserver_spec(struct keyserver_spec *keyserver)
140 {
141   m_free(keyserver->uri);
142   m_free(keyserver->host);
143   m_free(keyserver->port);
144   m_free(keyserver->path);
145   m_free(keyserver->opaque);
146   m_free(keyserver);
147 }
148
149 struct keyserver_spec *
150 parse_keyserver_uri(const char *uri,int require_scheme,
151                     const char *configname,unsigned int configlineno)
152 {
153   int assume_hkp=0;
154   struct keyserver_spec *keyserver;
155   const char *idx;
156   int count;
157
158   assert(uri!=NULL);
159
160   keyserver=m_alloc_clear(sizeof(struct keyserver_spec));
161
162   keyserver->uri=m_strdup(uri);
163
164   /* Get the scheme */
165
166   for(idx=uri,count=0;*idx && *idx!=':';idx++)
167     count++;
168
169   if(count==0)
170     goto fail;
171
172   if(*idx=='\0')
173     {
174       if(require_scheme)
175         return NULL;
176
177       /* Assume HKP if there is no scheme */
178       assume_hkp=1;
179       keyserver->scheme=m_strdup("hkp");
180     }
181   else
182     {
183       int i;
184
185       keyserver->scheme=m_alloc(count+1);
186
187       /* Force to lowercase */
188       for(i=0;i<count;i++)
189         keyserver->scheme[i]=ascii_tolower(uri[i]);
190
191       keyserver->scheme[i]='\0';
192
193       /* Skip past the scheme and colon */
194       uri+=count+1;
195     }
196
197   if(ascii_strcasecmp(keyserver->scheme,"x-broken-hkp")==0)
198     {
199       deprecated_warning(configname,configlineno,"x-broken-hkp",
200                          "--keyserver-options ","broken-http-proxy");
201       m_free(keyserver->scheme);
202       keyserver->scheme=m_strdup("hkp");
203       add_to_strlist(&opt.keyserver_options.other,"broken-http-proxy");
204     }
205   else if(ascii_strcasecmp(keyserver->scheme,"x-hkp")==0)
206     {
207       /* Canonicalize this to "hkp" so it works with both the internal
208          and external keyserver interface. */
209       m_free(keyserver->scheme);
210       keyserver->scheme=m_strdup("hkp");
211     }
212
213   if(assume_hkp || (uri[0]=='/' && uri[1]=='/'))
214     {
215       /* Two slashes means network path. */
216
217       /* Skip over the "//", if any */
218       if(!assume_hkp)
219         uri+=2;
220
221       for(idx=uri,count=0;*idx && *idx!=':' && *idx!='/';idx++)
222         count++;
223
224       if(count==0)
225         goto fail;
226
227       keyserver->host=m_alloc(count+1);
228       strncpy(keyserver->host,uri,count);
229       keyserver->host[count]='\0';
230
231       /* Skip past the host */
232       uri+=count;
233
234       if(*uri==':')
235         {
236           /* It would seem to be reasonable to limit the range of the
237              ports to values between 1-65535, but RFC 1738 and 1808
238              imply there is no limit.  Of course, the real world has
239              limits. */
240
241           for(idx=uri+1,count=0;*idx && *idx!='/';idx++)
242             {
243               count++;
244
245               /* Ports are digits only */
246               if(!digitp(idx))
247                 goto fail;
248             }
249
250           keyserver->port=m_alloc(count+1);
251           strncpy(keyserver->port,uri+1,count);
252           keyserver->port[count]='\0';
253
254           /* Skip past the colon and port number */
255           uri+=1+count;
256         }
257
258       /* Everything else is the path */
259       if(*uri)
260         keyserver->path=m_strdup(uri);
261       else
262         keyserver->path=m_strdup("/");
263     }
264   else if(uri[0]!='/')
265     {
266       /* No slash means opaque.  Just record the opaque blob and get
267          out. */
268       keyserver->opaque=m_strdup(uri);
269     }
270   else
271     {
272       /* One slash means absolute path.  We don't need to support that
273          yet. */
274       goto fail;
275     }
276
277   return keyserver;
278
279  fail:
280   free_keyserver_spec(keyserver);
281
282   return NULL;
283 }
284
285 struct keyserver_spec *
286 parse_preferred_keyserver(PKT_signature *sig)
287 {
288   struct keyserver_spec *spec=NULL;
289   const byte *p;
290   size_t plen;
291
292   p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&plen);
293   if(p && plen)
294     {
295       byte *dupe=m_alloc(plen+1);
296
297       memcpy(dupe,p,plen);
298       dupe[plen]='\0';
299       spec=parse_keyserver_uri(dupe,0,NULL,0);
300       m_free(dupe);
301     }
302
303   return spec;
304 }
305
306 static void
307 print_keyrec(int number,struct keyrec *keyrec)
308 {
309   int i;
310
311   iobuf_writebyte(keyrec->uidbuf,0);
312   iobuf_flush_temp(keyrec->uidbuf);
313   printf("(%d)\t%s  ",number,iobuf_get_temp_buffer(keyrec->uidbuf));
314
315   if(keyrec->size>0)
316     printf("%d bit ",keyrec->size);
317
318   if(keyrec->type)
319     {
320       const char *str=pubkey_algo_to_string(keyrec->type);
321
322       if(str)
323         printf("%s ",str);
324       else
325         printf("unknown ");
326     }
327
328   switch(keyrec->desc.mode)
329     {
330       /* If the keyserver helper gave us a short keyid, we have no
331          choice but to use it.  Do check --keyid-format to add a 0x if
332          needed. */
333     case KEYDB_SEARCH_MODE_SHORT_KID:
334       printf("key %s%08lX",
335              (opt.keyid_format==KF_0xSHORT
336               || opt.keyid_format==KF_0xLONG)?"0x":"",
337              (ulong)keyrec->desc.u.kid[1]);
338       break;
339
340       /* However, if it gave us a long keyid, we can honor
341          --keyid-format */
342     case KEYDB_SEARCH_MODE_LONG_KID:
343       printf("key %s",keystr(keyrec->desc.u.kid));
344       break;
345
346     case KEYDB_SEARCH_MODE_FPR16:
347       printf("key ");
348       for(i=0;i<16;i++)
349         printf("%02X",keyrec->desc.u.fpr[i]);
350       break;
351
352     case KEYDB_SEARCH_MODE_FPR20:
353       printf("key ");
354       for(i=0;i<20;i++)
355         printf("%02X",keyrec->desc.u.fpr[i]);
356       break;
357
358     default:
359       BUG();
360       break;
361     }
362
363   if(keyrec->createtime>0)
364     {
365       printf(", ");
366       printf(_("created: %s"),strtimestamp(keyrec->createtime));
367     }
368
369   if(keyrec->expiretime>0)
370     printf(", %s: %s",_("expires"),strtimestamp(keyrec->expiretime));
371
372   if(keyrec->flags&1)
373     printf(" (%s)",_("revoked"));
374   if(keyrec->flags&2)
375     printf(" (%s)",_("disabled"));
376   if(keyrec->flags&4)
377     printf(" (%s)",_("expired"));
378
379   printf("\n");
380 }
381
382 /* Returns a keyrec (which must be freed) once a key is complete, and
383    NULL otherwise.  Call with a NULL keystring once key parsing is
384    complete to return any unfinished keys. */
385 static struct keyrec *
386 parse_keyrec(char *keystring)
387 {
388   static struct keyrec *work=NULL;
389   struct keyrec *ret=NULL;
390   char *record;
391   int i;
392
393   if(keystring==NULL)
394     {
395       if(work==NULL)
396         return NULL;
397       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
398         {
399           m_free(work);
400           return NULL;
401         }
402       else
403         {
404           ret=work;
405           work=NULL;
406           return ret;
407         }
408     }
409
410   if(work==NULL)
411     {
412       work=m_alloc_clear(sizeof(struct keyrec));
413       work->uidbuf=iobuf_temp();
414     }
415
416   /* Remove trailing whitespace */
417   for(i=strlen(keystring);i>0;i--)
418     if(ascii_isspace(keystring[i-1]))
419       keystring[i-1]='\0';
420     else
421       break;
422
423   if((record=strsep(&keystring,":"))==NULL)
424     return ret;
425
426   if(ascii_strcasecmp("pub",record)==0)
427     {
428       char *tok;
429
430       if(work->desc.mode)
431         {
432           ret=work;
433           work=m_alloc_clear(sizeof(struct keyrec));
434           work->uidbuf=iobuf_temp();
435         }
436
437       if((tok=strsep(&keystring,":"))==NULL)
438         return ret;
439
440       classify_user_id(tok,&work->desc);
441       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
442          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
443          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
444          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
445         {
446           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
447           return ret;
448         }
449
450       /* Note all items after this are optional.  This allows us to
451          have a pub line as simple as pub:keyid and nothing else. */
452
453       work->lines++;
454
455       if((tok=strsep(&keystring,":"))==NULL)
456         return ret;
457
458       work->type=atoi(tok);
459
460       if((tok=strsep(&keystring,":"))==NULL)
461         return ret;
462
463       work->size=atoi(tok);
464
465       if((tok=strsep(&keystring,":"))==NULL)
466         return ret;
467
468       if(atoi(tok)<=0)
469         work->createtime=0;
470       else
471         work->createtime=atoi(tok);
472
473       if((tok=strsep(&keystring,":"))==NULL)
474         return ret;
475
476       if(atoi(tok)<=0)
477         work->expiretime=0;
478       else
479         {
480           work->expiretime=atoi(tok);
481           /* Force the 'e' flag on if this key is expired. */
482           if(work->expiretime<=make_timestamp())
483             work->flags|=4;
484         }
485
486       if((tok=strsep(&keystring,":"))==NULL)
487         return ret;
488
489       while(*tok)
490         switch(*tok++)
491           {
492           case 'r':
493           case 'R':
494             work->flags|=1;
495             break;
496             
497           case 'd':
498           case 'D':
499             work->flags|=2;
500             break;
501
502           case 'e':
503           case 'E':
504             work->flags|=4;
505             break;
506           }
507     }
508   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
509     {
510       char *userid,*tok,*decoded;
511
512       if((tok=strsep(&keystring,":"))==NULL)
513         return ret;
514
515       if(strlen(tok)==0)
516         return ret;
517
518       userid=tok;
519
520       /* By definition, de-%-encoding is always smaller than the
521          original string so we can decode in place. */
522
523       i=0;
524
525       while(*tok)
526         if(tok[0]=='%' && tok[1] && tok[2])
527           {
528             if((userid[i]=hextobyte(&tok[1]))==-1)
529               userid[i]='?';
530
531             i++;
532             tok+=3;
533           }
534         else
535           userid[i++]=*tok++;
536
537       /* We don't care about the other info provided in the uid: line
538          since no keyserver supports marking userids with timestamps
539          or revoked/expired/disabled yet. */
540
541       /* No need to check for control characters, as utf8_to_native
542          does this for us. */
543
544       decoded=utf8_to_native(userid,i,0);
545       if(strlen(decoded)>opt.screen_columns-10)
546         decoded[opt.screen_columns-10]='\0';
547       iobuf_writestr(work->uidbuf,decoded);
548       m_free(decoded);
549       iobuf_writestr(work->uidbuf,"\n\t");
550       work->lines++;
551     }
552
553   /* Ignore any records other than "pri" and "uid" for easy future
554      growth. */
555
556   return ret;
557 }
558
559 /* TODO: do this as a list sent to keyserver_work rather than calling
560    it once for each key to get the correct counts after the import
561    (cosmetics, really) and to better take advantage of the keyservers
562    that can do multiple fetches in one go (LDAP). */
563 static int
564 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
565 {
566   char *answer;
567
568   if(count && opt.command_fd==-1)
569     {
570       static int from=1;
571       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
572       from=numdesc+1;
573     }
574
575   answer=cpr_get_no_help("keysearch.prompt",
576                          _("Enter number(s), N)ext, or Q)uit > "));
577   /* control-d */
578   if(answer[0]=='\x04')
579     {
580       printf("Q\n");
581       answer[0]='q';
582     }
583
584   if(answer[0]=='q' || answer[0]=='Q')
585     {
586       m_free(answer);
587       return 1;
588     }
589   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
590     {
591       char *split=answer,*num;
592
593       while((num=strsep(&split," ,"))!=NULL)
594         if(atoi(num)>=1 && atoi(num)<=numdesc)
595           keyserver_work(GET,NULL,&desc[atoi(num)-1],1,opt.keyserver);
596
597       m_free(answer);
598       return 1;
599     }
600
601   return 0;
602 }
603
604 /* Count and searchstr are just for cosmetics.  If the count is too
605    small, it will grow safely.  If negative it disables the "Key x-y
606    of z" messages.  searchstr should be UTF-8 (rather than native). */
607 static void
608 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
609 {
610   int i=0,validcount=0,started=0,header=0,count=1;
611   unsigned int maxlen,buflen,numlines=0;
612   KEYDB_SEARCH_DESC *desc;
613   byte *line=NULL;
614   char *localstr=NULL;
615
616   if(searchstr)
617     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
618
619   desc=m_alloc(count*sizeof(KEYDB_SEARCH_DESC));
620
621   for(;;)
622     {
623       struct keyrec *keyrec;
624       int rl;
625
626       maxlen=1024;
627       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
628
629       if(opt.with_colons)
630         {
631           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
632              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
633             {
634               header=1;
635               continue;
636             }
637           else if(ascii_strncasecmp("SEARCH ",line,7)==0
638                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
639             continue;
640
641           printf("%s",line);
642         }
643
644       /* Look for an info: line.  The only current info: values
645          defined are the version and key count. */
646       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
647         {
648           char *tok,*str=&line[5];
649
650           if((tok=strsep(&str,":"))!=NULL)
651             {
652               int version;
653
654               if(sscanf(tok,"%d",&version)!=1)
655                 version=1;
656
657               if(version!=1)
658                 {
659                   log_error(_("invalid keyserver protocol "
660                               "(us %d!=handler %d)\n"),1,version);
661                   break;
662                 }
663             }
664
665           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
666             {
667               if(count==0)
668                 goto notfound;
669               else if(count<0)
670                 count=10;
671               else
672                 validcount=1;
673
674               desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
675             }
676
677           started=1;
678           continue;
679         }
680
681       if(rl==0)
682         {
683           keyrec=parse_keyrec(NULL);
684
685           if(keyrec==NULL)
686             {
687               if(i==0)
688                 {
689                   count=0;
690                   break;
691                 }
692
693               if(i!=count)
694                 validcount=0;
695
696               for(;;)
697                 {
698                   if(show_prompt(desc,i,validcount?count:0,localstr))
699                     break;
700                   validcount=0;
701                 }
702
703               break;
704             }
705         }
706       else
707         keyrec=parse_keyrec(line);
708
709       if(i==count)
710         {
711           /* keyserver helper sent more keys than they claimed in the
712              info: line. */
713           count+=10;
714           desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
715           validcount=0;
716         }
717
718       if(keyrec)
719         {
720           desc[i]=keyrec->desc;
721
722           if(!opt.with_colons)
723             {
724               /* screen_lines - 1 for the prompt. */
725               if(numlines+keyrec->lines>opt.screen_lines-1)
726                 {
727                   if(show_prompt(desc,i,validcount?count:0,localstr))
728                     break;
729                   else
730                     numlines=0;
731                 }
732
733               print_keyrec(i+1,keyrec);
734             }
735
736           numlines+=keyrec->lines;
737           iobuf_close(keyrec->uidbuf);
738           m_free(keyrec);
739
740           started=1;
741           i++;
742         }
743     }
744
745  notfound:
746   if(count==0)
747     {
748       if(localstr)
749         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
750       else
751         log_info(_("key not found on keyserver\n"));
752     }
753
754   m_free(localstr);
755   m_free(desc);
756   m_free(line);
757 }
758
759 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
760 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
761
762 static int 
763 keyserver_spawn(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
764                 int count,int *prog,struct keyserver_spec *keyserver)
765 {
766   int ret=0,i,gotversion=0,outofband=0;
767   STRLIST temp;
768   unsigned int maxlen,buflen;
769   char *command=NULL,*searchstr=NULL;
770   byte *line=NULL;
771   struct parse_options *kopts;
772   struct exec_info *spawn;
773
774   assert(keyserver);
775
776 #ifdef EXEC_TEMPFILE_ONLY
777   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
778 #endif
779
780   /* Push the libexecdir into path.  If DISABLE_KEYSERVER_PATH is set,
781      use the 0 arg to replace the path. */
782 #ifdef DISABLE_KEYSERVER_PATH
783   set_exec_path(GNUPG_LIBEXECDIR,0);
784 #else
785   set_exec_path(GNUPG_LIBEXECDIR,opt.exec_path_set);
786 #endif
787
788   /* Build the filename for the helper to execute */
789   command=m_alloc(strlen("gpgkeys_")+strlen(keyserver->scheme)+1);
790   strcpy(command,"gpgkeys_");
791   strcat(command,keyserver->scheme);
792
793   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
794     {
795       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
796         {
797           command=m_realloc(command,strlen(command)+
798                             strlen(KEYSERVER_ARGS_KEEP)+1);
799           strcat(command,KEYSERVER_ARGS_KEEP);
800         }
801       else
802         {
803           command=m_realloc(command,strlen(command)+
804                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
805           strcat(command,KEYSERVER_ARGS_NOKEEP);  
806         }
807
808       ret=exec_write(&spawn,NULL,command,NULL,0,0);
809     }
810   else
811     ret=exec_write(&spawn,command,NULL,NULL,0,0);
812
813   if(ret)
814     return ret;
815
816   fprintf(spawn->tochild,
817           "# This is a GnuPG %s keyserver communications file\n",VERSION);
818   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
819   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
820   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
821
822   if(keyserver->opaque)
823     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
824   else
825     {
826       if(keyserver->host)
827         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
828
829       if(keyserver->port)
830         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
831
832       if(keyserver->path)
833         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
834     }
835
836   /* Write options */
837
838   for(i=0,kopts=keyserver_opts;kopts[i].name;i++)
839     if(opt.keyserver_options.options & kopts[i].bit & REMOTE_TELL)
840       fprintf(spawn->tochild,"OPTION %s\n",kopts[i].name);
841
842   for(i=0;i<opt.keyserver_options.verbose;i++)
843     fprintf(spawn->tochild,"OPTION verbose\n");
844
845   for(temp=opt.keyserver_options.other;temp;temp=temp->next)
846     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
847
848   switch(action)
849     {
850     case GET:
851       {
852         fprintf(spawn->tochild,"COMMAND GET\n\n");
853
854         /* Which keys do we want? */
855
856         for(i=0;i<count;i++)
857           {
858             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
859               {
860                 int f;
861
862                 fprintf(spawn->tochild,"0x");
863
864                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
865                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
866
867                 fprintf(spawn->tochild,"\n");
868               }
869             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
870               {
871                 int f;
872
873                 fprintf(spawn->tochild,"0x");
874
875                 for(f=0;f<16;f++)
876                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
877
878                 fprintf(spawn->tochild,"\n");
879               }
880             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
881               fprintf(spawn->tochild,"0x%08lX%08lX\n",
882                       (ulong)desc[i].u.kid[0],
883                       (ulong)desc[i].u.kid[1]);
884             else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
885               fprintf(spawn->tochild,"0x%08lX\n",
886                       (ulong)desc[i].u.kid[1]);
887             else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
888               continue;
889             else
890               BUG();
891
892             log_info(_("requesting key %s from %s server %s\n"),
893                      keystr_from_desc(&desc[i]),
894                      keyserver->scheme,keyserver->host);
895           }
896
897         fprintf(spawn->tochild,"\n");
898
899         break;
900       }
901
902     case SEND:
903       {
904         STRLIST key;
905
906         /* Note the extra \n here to send an empty keylist block */
907         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
908
909         for(key=list;key!=NULL;key=key->next)
910           {
911             armor_filter_context_t afx;
912             IOBUF buffer=iobuf_temp();
913             KBNODE block;
914
915             temp=NULL;
916             add_to_strlist(&temp,key->d);
917
918             memset(&afx,0,sizeof(afx));
919             afx.what=1;
920             iobuf_push_filter(buffer,armor_filter,&afx);
921
922             /* TODO: Remove Comment: lines from keys exported this
923                way? */
924
925             if(export_pubkeys_stream(buffer,temp,&block,
926                                      opt.keyserver_options.export_options)==-1)
927               iobuf_close(buffer);
928             else
929               {
930                 KBNODE node;
931
932                 iobuf_flush_temp(buffer);
933
934                 merge_keys_and_selfsig(block);
935
936                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
937                         (ulong)block->pkt->pkt.public_key->keyid[0],
938                         (ulong)block->pkt->pkt.public_key->keyid[1]);
939
940                 for(node=block;node;node=node->next)
941                   {
942                     switch(node->pkt->pkttype)
943                       {
944                       default:
945                         continue;
946
947                       case PKT_PUBLIC_KEY:
948                       case PKT_PUBLIC_SUBKEY:
949                         {
950                           PKT_public_key *pk=node->pkt->pkt.public_key;
951
952                           keyid_from_pk(pk,NULL);
953
954                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
955                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
956                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
957                                   pk->pubkey_algo,
958                                   nbits_from_pk(pk),
959                                   pk->timestamp,
960                                   pk->expiredate);
961
962                           if(pk->is_revoked)
963                             fprintf(spawn->tochild,"r");
964                           if(pk->has_expired)
965                             fprintf(spawn->tochild,"e");
966
967                           fprintf(spawn->tochild,"\n");
968                         }
969                         break;
970
971                       case PKT_USER_ID:
972                         {
973                           PKT_user_id *uid=node->pkt->pkt.user_id;
974                           int r;
975
976                           if(uid->attrib_data)
977                             continue;
978
979                           fprintf(spawn->tochild,"uid:");
980
981                           /* Quote ':', '%', and any 8-bit
982                              characters */
983                           for(r=0;r<uid->len;r++)
984                             {
985                               if(uid->name[r]==':' || uid->name[r]=='%'
986                                  || uid->name[r]&0x80)
987                                 fprintf(spawn->tochild,"%%%02X",
988                                         (byte)uid->name[r]);
989                               else
990                                 fprintf(spawn->tochild,"%c",uid->name[r]);
991                             }
992
993                           fprintf(spawn->tochild,":%u:%u:",
994                                   uid->created,uid->expiredate);
995
996                           if(uid->is_revoked)
997                             fprintf(spawn->tochild,"r");
998                           if(uid->is_expired)
999                             fprintf(spawn->tochild,"e");
1000
1001                           fprintf(spawn->tochild,"\n");
1002                         }
1003                         break;
1004
1005                         /* This bit is really for the benefit of
1006                            people who store their keys in LDAP
1007                            servers.  It makes it easy to do queries
1008                            for things like "all keys signed by
1009                            Isabella". */
1010                       case PKT_SIGNATURE:
1011                         {
1012                           PKT_signature *sig=node->pkt->pkt.signature;
1013
1014                           if(!IS_UID_SIG(sig))
1015                             continue;
1016
1017                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1018                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1019                                   sig->sig_class,sig->timestamp,
1020                                   sig->expiredate);
1021                         }
1022                         break;
1023                       }
1024                   }
1025
1026                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1027                         (ulong)block->pkt->pkt.public_key->keyid[0],
1028                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1029
1030                 fprintf(spawn->tochild,"KEY %s BEGIN\n",key->d);
1031                 fwrite(iobuf_get_temp_buffer(buffer),
1032                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1033                 fprintf(spawn->tochild,"KEY %s END\n",key->d);
1034
1035                 iobuf_close(buffer);
1036
1037                 log_info(_("sending key %s to %s server %s\n"),
1038                          keystr(block->pkt->pkt.public_key->keyid),
1039                          keyserver->scheme,keyserver->host);
1040
1041                 release_kbnode(block);
1042               }
1043
1044             free_strlist(temp);
1045           }
1046
1047         break;
1048       }
1049
1050     case SEARCH:
1051       {
1052         STRLIST key;
1053
1054         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1055
1056         /* Which keys do we want?  Remember that the gpgkeys_ program
1057            is going to lump these together into a search string. */
1058
1059         for(key=list;key!=NULL;key=key->next)
1060           {
1061             fprintf(spawn->tochild,"%s\n",key->d);
1062             if(key!=list)
1063               {
1064                 searchstr=m_realloc(searchstr,
1065                                     strlen(searchstr)+strlen(key->d)+2);
1066                 strcat(searchstr," ");
1067               }
1068             else
1069               {
1070                 searchstr=m_alloc(strlen(key->d)+1);
1071                 searchstr[0]='\0';
1072               }
1073
1074             strcat(searchstr,key->d);
1075           }
1076
1077         fprintf(spawn->tochild,"\n");
1078
1079         log_info(_("searching for \"%s\" from %s server %s\n"),
1080                  searchstr,keyserver->scheme,keyserver->host);
1081
1082         break;
1083       }
1084
1085     default:
1086       log_fatal(_("no keyserver action!\n"));
1087       break;
1088     }
1089
1090   /* Done sending, so start reading. */
1091   ret=exec_read(spawn);
1092   if(ret)
1093     goto fail;
1094
1095   /* Now handle the response */
1096
1097   for(;;)
1098     {
1099       int plen;
1100       char *ptr;
1101
1102       maxlen=1024;
1103       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1104         {
1105           ret=G10ERR_READ_FILE;
1106           goto fail; /* i.e. EOF */
1107         }
1108
1109       ptr=line;
1110
1111       /* remove trailing whitespace */
1112       plen=strlen(ptr);
1113       while(plen>0 && ascii_isspace(ptr[plen-1]))
1114         plen--;
1115       plen[ptr]='\0';
1116
1117       if(*ptr=='\0')
1118         break;
1119
1120       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1121         {
1122           gotversion=1;
1123
1124           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1125             {
1126               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1127                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1128               goto fail;
1129             }
1130         }
1131       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1132         {
1133           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1134             log_info(_("WARNING: keyserver handler from a different"
1135                        " version of GnuPG (%s)\n"),&ptr[8]);
1136         }
1137       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1138         outofband=1; /* Currently the only OPTION */
1139     }
1140
1141   if(!gotversion)
1142     {
1143       log_error(_("keyserver did not send VERSION\n"));
1144       goto fail;
1145     }
1146
1147   if(!outofband)
1148     switch(action)
1149       {
1150       case GET:
1151         {
1152           void *stats_handle;
1153
1154           stats_handle=import_new_stats_handle();
1155
1156           /* Slurp up all the key data.  In the future, it might be
1157              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1158              It's harmless to ignore them, but ignoring them does make
1159              gpg complain about "no valid OpenPGP data found".  One
1160              way to do this could be to continue parsing this
1161              line-by-line and make a temp iobuf for each key. */
1162
1163           import_keys_stream(spawn->fromchild,stats_handle,
1164                              opt.keyserver_options.import_options);
1165
1166           import_print_stats(stats_handle);
1167           import_release_stats_handle(stats_handle);
1168
1169           break;
1170         }
1171
1172         /* Nothing to do here */
1173       case SEND:
1174         break;
1175
1176       case SEARCH:
1177         keyserver_search_prompt(spawn->fromchild,searchstr);
1178         break;
1179
1180       default:
1181         log_fatal(_("no keyserver action!\n"));
1182         break;
1183       }
1184
1185  fail:
1186   m_free(line);
1187   m_free(searchstr);
1188
1189   *prog=exec_finish(spawn);
1190
1191   return ret;
1192 }
1193
1194 static int 
1195 keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
1196                int count,struct keyserver_spec *keyserver)
1197 {
1198   int rc=0,ret=0;
1199
1200   if(!keyserver)
1201     {
1202       log_error(_("no keyserver known (use option --keyserver)\n"));
1203       return G10ERR_BAD_URI;
1204     }
1205
1206 #ifdef DISABLE_KEYSERVER_HELPERS
1207
1208   log_error(_("external keyserver calls are not supported in this build\n"));
1209   return G10ERR_KEYSERVER;
1210
1211 #else
1212   /* Spawn a handler */
1213
1214   rc=keyserver_spawn(action,list,desc,count,&ret,keyserver);
1215   if(ret)
1216     {
1217       switch(ret)
1218         {
1219         case KEYSERVER_SCHEME_NOT_FOUND:
1220           log_error(_("no handler for keyserver scheme `%s'\n"),
1221                     keyserver->scheme);
1222           break;
1223
1224         case KEYSERVER_NOT_SUPPORTED:
1225           log_error(_("action `%s' not supported with keyserver "
1226                       "scheme `%s'\n"),
1227                     action==GET?"get":action==SEND?"send":
1228                     action==SEARCH?"search":"unknown",
1229                     keyserver->scheme);
1230           break;
1231
1232         case KEYSERVER_VERSION_ERROR:
1233           log_error(_("gpgkeys_%s does not support handler version %d\n"),
1234                     keyserver->scheme,KEYSERVER_PROTO_VERSION);
1235           break;
1236
1237         case KEYSERVER_INTERNAL_ERROR:
1238         default:
1239           log_error(_("keyserver internal error\n"));
1240           break;
1241         }
1242
1243       return G10ERR_KEYSERVER;
1244     }
1245
1246   if(rc)
1247     {
1248       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1249
1250       return rc;
1251     }
1252
1253   return 0;
1254 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1255 }
1256
1257 int 
1258 keyserver_export(STRLIST users)
1259 {
1260   STRLIST sl=NULL;
1261   KEYDB_SEARCH_DESC desc;
1262   int rc=0;
1263
1264   /* Weed out descriptors that we don't support sending */
1265   for(;users;users=users->next)
1266     {
1267       classify_user_id (users->d, &desc);
1268       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1269          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1270          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1271          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1272         {
1273           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1274           continue;
1275         }
1276       else
1277         append_to_strlist(&sl,users->d);
1278     }
1279
1280   if(sl)
1281     {
1282       rc=keyserver_work(SEND,sl,NULL,0,opt.keyserver);
1283       free_strlist(sl);
1284     }
1285
1286   return rc;
1287 }
1288
1289 int 
1290 keyserver_import(STRLIST users)
1291 {
1292   KEYDB_SEARCH_DESC *desc;
1293   int num=100,count=0;
1294   int rc=0;
1295
1296   /* Build a list of key ids */
1297   desc=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1298
1299   for(;users;users=users->next)
1300     {
1301       classify_user_id (users->d, &desc[count]);
1302       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1303          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1304          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1305          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1306         {
1307           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1308           continue;
1309         }
1310
1311       count++;
1312       if(count==num)
1313         {
1314           num+=100;
1315           desc=m_realloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1316         }
1317     }
1318
1319   if(count>0)
1320     rc=keyserver_work(GET,NULL,desc,count,opt.keyserver);
1321
1322   m_free(desc);
1323
1324   return rc;
1325 }
1326
1327 int
1328 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1329                         struct keyserver_spec *keyserver)
1330 {
1331   KEYDB_SEARCH_DESC desc;
1332
1333   memset(&desc,0,sizeof(desc));
1334
1335   if(fprint_len==16)
1336     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1337   else if(fprint_len==20)
1338     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1339   else
1340     return -1;
1341
1342   memcpy(desc.u.fpr,fprint,fprint_len);
1343
1344   return keyserver_work(GET,NULL,&desc,1,keyserver);
1345 }
1346
1347 int 
1348 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1349 {
1350   KEYDB_SEARCH_DESC desc;
1351
1352   memset(&desc,0,sizeof(desc));
1353
1354   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1355   desc.u.kid[0]=keyid[0];
1356   desc.u.kid[1]=keyid[1];
1357
1358   return keyserver_work(GET,NULL,&desc,1,keyserver);
1359 }
1360
1361 /* code mostly stolen from do_export_stream */
1362 static int 
1363 keyidlist(STRLIST users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1364 {
1365   int rc=0,ndesc,num=100;
1366   KBNODE keyblock=NULL,node;
1367   KEYDB_HANDLE kdbhd;
1368   KEYDB_SEARCH_DESC *desc;
1369   STRLIST sl;
1370
1371   *count=0;
1372
1373   *klist=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1374
1375   kdbhd=keydb_new(0);
1376
1377   if(!users)
1378     {
1379       ndesc = 1;
1380       desc = m_alloc_clear ( ndesc * sizeof *desc);
1381       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1382     }
1383   else
1384     {
1385       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
1386         ;
1387       desc = m_alloc ( ndesc * sizeof *desc);
1388         
1389       for (ndesc=0, sl=users; sl; sl = sl->next)
1390         {
1391           if(classify_user_id (sl->d, desc+ndesc))
1392             ndesc++;
1393           else
1394             log_error (_("key \"%s\" not found: %s\n"),
1395                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1396         }
1397     }
1398
1399   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1400     {
1401       if (!users) 
1402         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1403
1404       /* read the keyblock */
1405       rc = keydb_get_keyblock (kdbhd, &keyblock );
1406       if( rc )
1407         {
1408           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1409           goto leave;
1410         }
1411
1412       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1413         {
1414           /* This is to work around a bug in some keyservers (pksd and
1415              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1416              The answer is to refresh both the correct v4 keyid
1417              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1418              This only happens for key refresh using the HKP scheme
1419              and if the refresh-add-fake-v3-keyids keyserver option is
1420              set. */
1421           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1422              node->pkt->pkt.public_key->version>=4)
1423             {
1424               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1425               mpi_get_keyid(node->pkt->pkt.public_key->pkey[0],
1426                             (*klist)[*count].u.kid);
1427               (*count)++;
1428
1429               if(*count==num)
1430                 {
1431                   num+=100;
1432                   *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1433                 }
1434             }
1435
1436           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1437              This is because it's easy to calculate any sort of keyid
1438              from a v4 fingerprint, but not a v3 fingerprint. */
1439
1440           if(node->pkt->pkt.public_key->version<4)
1441             {
1442               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1443               keyid_from_pk(node->pkt->pkt.public_key,
1444                             (*klist)[*count].u.kid);
1445             }
1446           else
1447             {
1448               size_t dummy;
1449
1450               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1451               fingerprint_from_pk(node->pkt->pkt.public_key,
1452                                   (*klist)[*count].u.fpr,&dummy);
1453             }
1454
1455           /* This is a little hackish, using the skipfncvalue as a
1456              void* pointer to the keyserver spec, but we don't need
1457              the skipfnc here, and it saves having an additional field
1458              for this (which would be wasted space most of the
1459              time). */
1460
1461           (*klist)[*count].skipfncvalue=NULL;
1462
1463           /* Are we honoring preferred keyservers? */
1464           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1465             {
1466               PKT_user_id *uid=NULL;
1467               PKT_signature *sig=NULL;
1468
1469               merge_keys_and_selfsig(keyblock);
1470
1471               for(node=node->next;node;node=node->next)
1472                 {
1473                   if(node->pkt->pkttype==PKT_USER_ID
1474                      && node->pkt->pkt.user_id->is_primary)
1475                     uid=node->pkt->pkt.user_id;
1476                   else if(node->pkt->pkttype==PKT_SIGNATURE
1477                           && node->pkt->pkt.signature->
1478                           flags.chosen_selfsig && uid)
1479                     {
1480                       sig=node->pkt->pkt.signature;
1481                       break;
1482                     }
1483                 }
1484
1485               /* Try and parse the keyserver URL.  If it doesn't work,
1486                  then we end up writing NULL which indicates we are
1487                  the same as any other key. */
1488               if(uid && sig)
1489                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1490             }
1491
1492           (*count)++;
1493
1494           if(*count==num)
1495             {
1496               num+=100;
1497               *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1498             }
1499         }
1500     }
1501
1502   if(rc==-1)
1503     rc=0;
1504   
1505  leave:
1506   if(rc)
1507     m_free(*klist);
1508   m_free(desc);
1509   keydb_release(kdbhd);
1510   release_kbnode(keyblock);
1511
1512   return rc;
1513 }
1514
1515 /* Note this is different than the original HKP refresh.  It allows
1516    usernames to refresh only part of the keyring. */
1517
1518 int 
1519 keyserver_refresh(STRLIST users)
1520 {
1521   int rc,count,numdesc,fakev3=0;
1522   KEYDB_SEARCH_DESC *desc;
1523
1524   /* We switch merge_only on during a refresh, as 'refresh' should
1525      never import new keys, even if their keyids match.  Is it worth
1526      preserving the old merge_only value here? */
1527   opt.import_options|=IMPORT_MERGE_ONLY;
1528
1529   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1530      scheme, then enable fake v3 keyid generation. */
1531   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1532      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1533          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1534     fakev3=1;
1535
1536   rc=keyidlist(users,&desc,&numdesc,fakev3);
1537   if(rc)
1538     return rc;
1539
1540   count=numdesc;
1541   if(count>0)
1542     {
1543       int i;
1544
1545       /* Try to handle preferred keyserver keys first */
1546       for(i=0;i<count;i++)
1547         {
1548           if(desc[i].skipfncvalue)
1549             {
1550               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1551
1552               /* We use the keyserver structure we parsed out before.
1553                  Note that a preferred keyserver without a scheme://
1554                  will be interpreted as hkp:// */
1555
1556               rc=keyserver_work(GET,NULL,&desc[i],1,keyserver);
1557               if(rc)
1558                 log_info(_("WARNING: unable to refresh key %s"
1559                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
1560                          keyserver->uri,g10_errstr(rc));
1561               else
1562                 {
1563                   /* We got it, so mark it as NONE so we don't try and
1564                      get it again from the regular keyserver. */
1565
1566                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
1567                   count--;
1568                 }
1569
1570               free_keyserver_spec(keyserver);
1571             }
1572         }
1573     }
1574
1575   if(count>0)
1576     {
1577       if(opt.keyserver)
1578         {
1579           if(count==1)
1580             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
1581           else
1582             log_info(_("refreshing %d keys from %s\n"),
1583                      count,opt.keyserver->uri);
1584         }
1585
1586       rc=keyserver_work(GET,NULL,desc,numdesc,opt.keyserver);
1587     }
1588
1589   m_free(desc);
1590
1591   return rc;
1592 }
1593
1594 int
1595 keyserver_search(STRLIST tokens)
1596 {
1597   if(tokens)
1598     return keyserver_work(SEARCH,tokens,NULL,0,opt.keyserver);
1599   else
1600     return 0;
1601 }