* keygen.c (ask_key_flags): New. (ask_algo): Call it here in --expert mode
[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     {
371       printf(", ");
372       printf(_("expires: %s"),strtimestamp(keyrec->expiretime));
373     }
374
375   if(keyrec->flags&1)
376     printf(" (%s)",_("revoked"));
377   if(keyrec->flags&2)
378     printf(" (%s)",_("disabled"));
379   if(keyrec->flags&4)
380     printf(" (%s)",_("expired"));
381
382   printf("\n");
383 }
384
385 /* Returns a keyrec (which must be freed) once a key is complete, and
386    NULL otherwise.  Call with a NULL keystring once key parsing is
387    complete to return any unfinished keys. */
388 static struct keyrec *
389 parse_keyrec(char *keystring)
390 {
391   static struct keyrec *work=NULL;
392   struct keyrec *ret=NULL;
393   char *record;
394   int i;
395
396   if(keystring==NULL)
397     {
398       if(work==NULL)
399         return NULL;
400       else if(work->desc.mode==KEYDB_SEARCH_MODE_NONE)
401         {
402           m_free(work);
403           return NULL;
404         }
405       else
406         {
407           ret=work;
408           work=NULL;
409           return ret;
410         }
411     }
412
413   if(work==NULL)
414     {
415       work=m_alloc_clear(sizeof(struct keyrec));
416       work->uidbuf=iobuf_temp();
417     }
418
419   /* Remove trailing whitespace */
420   for(i=strlen(keystring);i>0;i--)
421     if(ascii_isspace(keystring[i-1]))
422       keystring[i-1]='\0';
423     else
424       break;
425
426   if((record=strsep(&keystring,":"))==NULL)
427     return ret;
428
429   if(ascii_strcasecmp("pub",record)==0)
430     {
431       char *tok;
432
433       if(work->desc.mode)
434         {
435           ret=work;
436           work=m_alloc_clear(sizeof(struct keyrec));
437           work->uidbuf=iobuf_temp();
438         }
439
440       if((tok=strsep(&keystring,":"))==NULL)
441         return ret;
442
443       classify_user_id(tok,&work->desc);
444       if(work->desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID
445          && work->desc.mode!=KEYDB_SEARCH_MODE_LONG_KID
446          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR16
447          && work->desc.mode!=KEYDB_SEARCH_MODE_FPR20)
448         {
449           work->desc.mode=KEYDB_SEARCH_MODE_NONE;
450           return ret;
451         }
452
453       /* Note all items after this are optional.  This allows us to
454          have a pub line as simple as pub:keyid and nothing else. */
455
456       work->lines++;
457
458       if((tok=strsep(&keystring,":"))==NULL)
459         return ret;
460
461       work->type=atoi(tok);
462
463       if((tok=strsep(&keystring,":"))==NULL)
464         return ret;
465
466       work->size=atoi(tok);
467
468       if((tok=strsep(&keystring,":"))==NULL)
469         return ret;
470
471       if(atoi(tok)<=0)
472         work->createtime=0;
473       else
474         work->createtime=atoi(tok);
475
476       if((tok=strsep(&keystring,":"))==NULL)
477         return ret;
478
479       if(atoi(tok)<=0)
480         work->expiretime=0;
481       else
482         {
483           work->expiretime=atoi(tok);
484           /* Force the 'e' flag on if this key is expired. */
485           if(work->expiretime<=make_timestamp())
486             work->flags|=4;
487         }
488
489       if((tok=strsep(&keystring,":"))==NULL)
490         return ret;
491
492       while(*tok)
493         switch(*tok++)
494           {
495           case 'r':
496           case 'R':
497             work->flags|=1;
498             break;
499             
500           case 'd':
501           case 'D':
502             work->flags|=2;
503             break;
504
505           case 'e':
506           case 'E':
507             work->flags|=4;
508             break;
509           }
510     }
511   else if(ascii_strcasecmp("uid",record)==0 && work->desc.mode)
512     {
513       char *userid,*tok,*decoded;
514
515       if((tok=strsep(&keystring,":"))==NULL)
516         return ret;
517
518       if(strlen(tok)==0)
519         return ret;
520
521       userid=tok;
522
523       /* By definition, de-%-encoding is always smaller than the
524          original string so we can decode in place. */
525
526       i=0;
527
528       while(*tok)
529         if(tok[0]=='%' && tok[1] && tok[2])
530           {
531             if((userid[i]=hextobyte(&tok[1]))==-1)
532               userid[i]='?';
533
534             i++;
535             tok+=3;
536           }
537         else
538           userid[i++]=*tok++;
539
540       /* We don't care about the other info provided in the uid: line
541          since no keyserver supports marking userids with timestamps
542          or revoked/expired/disabled yet. */
543
544       /* No need to check for control characters, as utf8_to_native
545          does this for us. */
546
547       decoded=utf8_to_native(userid,i,0);
548       if(strlen(decoded)>opt.screen_columns-10)
549         decoded[opt.screen_columns-10]='\0';
550       iobuf_writestr(work->uidbuf,decoded);
551       m_free(decoded);
552       iobuf_writestr(work->uidbuf,"\n\t");
553       work->lines++;
554     }
555
556   /* Ignore any records other than "pri" and "uid" for easy future
557      growth. */
558
559   return ret;
560 }
561
562 /* TODO: do this as a list sent to keyserver_work rather than calling
563    it once for each key to get the correct counts after the import
564    (cosmetics, really) and to better take advantage of the keyservers
565    that can do multiple fetches in one go (LDAP). */
566 static int
567 show_prompt(KEYDB_SEARCH_DESC *desc,int numdesc,int count,const char *search)
568 {
569   char *answer;
570
571   if(count && opt.command_fd==-1)
572     {
573       static int from=1;
574       tty_printf("Keys %d-%d of %d for \"%s\".  ",from,numdesc,count,search);
575       from=numdesc+1;
576     }
577
578   answer=cpr_get_no_help("keysearch.prompt",
579                          _("Enter number(s), N)ext, or Q)uit > "));
580   /* control-d */
581   if(answer[0]=='\x04')
582     {
583       printf("Q\n");
584       answer[0]='q';
585     }
586
587   if(answer[0]=='q' || answer[0]=='Q')
588     {
589       m_free(answer);
590       return 1;
591     }
592   else if(atoi(answer)>=1 && atoi(answer)<=numdesc)
593     {
594       char *split=answer,*num;
595
596       while((num=strsep(&split," ,"))!=NULL)
597         if(atoi(num)>=1 && atoi(num)<=numdesc)
598           keyserver_work(GET,NULL,&desc[atoi(num)-1],1,opt.keyserver);
599
600       m_free(answer);
601       return 1;
602     }
603
604   return 0;
605 }
606
607 /* Count and searchstr are just for cosmetics.  If the count is too
608    small, it will grow safely.  If negative it disables the "Key x-y
609    of z" messages.  searchstr should be UTF-8 (rather than native). */
610 static void
611 keyserver_search_prompt(IOBUF buffer,const char *searchstr)
612 {
613   int i=0,validcount=0,started=0,header=0,count=1;
614   unsigned int maxlen,buflen,numlines=0;
615   KEYDB_SEARCH_DESC *desc;
616   byte *line=NULL;
617   char *localstr=NULL;
618
619   if(searchstr)
620     localstr=utf8_to_native(searchstr,strlen(searchstr),0);
621
622   desc=m_alloc(count*sizeof(KEYDB_SEARCH_DESC));
623
624   for(;;)
625     {
626       struct keyrec *keyrec;
627       int rl;
628
629       maxlen=1024;
630       rl=iobuf_read_line(buffer,&line,&buflen,&maxlen);
631
632       if(opt.with_colons)
633         {
634           if(!header && ascii_strncasecmp("SEARCH ",line,7)==0
635              && ascii_strncasecmp(" BEGIN",&line[strlen(line)-7],6)==0)
636             {
637               header=1;
638               continue;
639             }
640           else if(ascii_strncasecmp("SEARCH ",line,7)==0
641                   && ascii_strncasecmp(" END",&line[strlen(line)-5],4)==0)
642             continue;
643
644           printf("%s",line);
645         }
646
647       /* Look for an info: line.  The only current info: values
648          defined are the version and key count. */
649       if(!started && rl>0 && ascii_strncasecmp("info:",line,5)==0)
650         {
651           char *tok,*str=&line[5];
652
653           if((tok=strsep(&str,":"))!=NULL)
654             {
655               int version;
656
657               if(sscanf(tok,"%d",&version)!=1)
658                 version=1;
659
660               if(version!=1)
661                 {
662                   log_error(_("invalid keyserver protocol "
663                               "(us %d!=handler %d)\n"),1,version);
664                   break;
665                 }
666             }
667
668           if((tok=strsep(&str,":"))!=NULL && sscanf(tok,"%d",&count)==1)
669             {
670               if(count==0)
671                 goto notfound;
672               else if(count<0)
673                 count=10;
674               else
675                 validcount=1;
676
677               desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
678             }
679
680           started=1;
681           continue;
682         }
683
684       if(rl==0)
685         {
686           keyrec=parse_keyrec(NULL);
687
688           if(keyrec==NULL)
689             {
690               if(i==0)
691                 {
692                   count=0;
693                   break;
694                 }
695
696               if(i!=count)
697                 validcount=0;
698
699               for(;;)
700                 {
701                   if(show_prompt(desc,i,validcount?count:0,localstr))
702                     break;
703                   validcount=0;
704                 }
705
706               break;
707             }
708         }
709       else
710         keyrec=parse_keyrec(line);
711
712       if(i==count)
713         {
714           /* keyserver helper sent more keys than they claimed in the
715              info: line. */
716           count+=10;
717           desc=m_realloc(desc,count*sizeof(KEYDB_SEARCH_DESC));
718           validcount=0;
719         }
720
721       if(keyrec)
722         {
723           desc[i]=keyrec->desc;
724
725           if(!opt.with_colons)
726             {
727               /* screen_lines - 1 for the prompt. */
728               if(numlines+keyrec->lines>opt.screen_lines-1)
729                 {
730                   if(show_prompt(desc,i,validcount?count:0,localstr))
731                     break;
732                   else
733                     numlines=0;
734                 }
735
736               print_keyrec(i+1,keyrec);
737             }
738
739           numlines+=keyrec->lines;
740           iobuf_close(keyrec->uidbuf);
741           m_free(keyrec);
742
743           started=1;
744           i++;
745         }
746     }
747
748  notfound:
749   if(count==0)
750     {
751       if(localstr)
752         log_info(_("key \"%s\" not found on keyserver\n"),localstr);
753       else
754         log_info(_("key not found on keyserver\n"));
755     }
756
757   m_free(localstr);
758   m_free(desc);
759   m_free(line);
760 }
761
762 #define KEYSERVER_ARGS_KEEP " -o \"%O\" \"%I\""
763 #define KEYSERVER_ARGS_NOKEEP " -o \"%o\" \"%i\""
764
765 static int 
766 keyserver_spawn(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
767                 int count,int *prog,struct keyserver_spec *keyserver)
768 {
769   int ret=0,i,gotversion=0,outofband=0;
770   STRLIST temp;
771   unsigned int maxlen,buflen;
772   char *command=NULL,*searchstr=NULL;
773   byte *line=NULL;
774   struct parse_options *kopts;
775   struct exec_info *spawn;
776
777   assert(keyserver);
778
779 #ifdef EXEC_TEMPFILE_ONLY
780   opt.keyserver_options.options|=KEYSERVER_USE_TEMP_FILES;
781 #endif
782
783   /* Push the libexecdir into path.  If DISABLE_KEYSERVER_PATH is set,
784      use the 0 arg to replace the path. */
785 #ifdef DISABLE_KEYSERVER_PATH
786   set_exec_path(GNUPG_LIBEXECDIR,0);
787 #else
788   set_exec_path(GNUPG_LIBEXECDIR,opt.exec_path_set);
789 #endif
790
791   /* Build the filename for the helper to execute */
792   command=m_alloc(strlen("gpgkeys_")+strlen(keyserver->scheme)+1);
793   strcpy(command,"gpgkeys_");
794   strcat(command,keyserver->scheme);
795
796   if(opt.keyserver_options.options&KEYSERVER_USE_TEMP_FILES)
797     {
798       if(opt.keyserver_options.options&KEYSERVER_KEEP_TEMP_FILES)
799         {
800           command=m_realloc(command,strlen(command)+
801                             strlen(KEYSERVER_ARGS_KEEP)+1);
802           strcat(command,KEYSERVER_ARGS_KEEP);
803         }
804       else
805         {
806           command=m_realloc(command,strlen(command)+
807                             strlen(KEYSERVER_ARGS_NOKEEP)+1);
808           strcat(command,KEYSERVER_ARGS_NOKEEP);  
809         }
810
811       ret=exec_write(&spawn,NULL,command,NULL,0,0);
812     }
813   else
814     ret=exec_write(&spawn,command,NULL,NULL,0,0);
815
816   if(ret)
817     return ret;
818
819   fprintf(spawn->tochild,
820           "# This is a GnuPG %s keyserver communications file\n",VERSION);
821   fprintf(spawn->tochild,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
822   fprintf(spawn->tochild,"PROGRAM %s\n",VERSION);
823   fprintf(spawn->tochild,"SCHEME %s\n",keyserver->scheme);
824
825   if(keyserver->opaque)
826     fprintf(spawn->tochild,"OPAQUE %s\n",keyserver->opaque);
827   else
828     {
829       if(keyserver->host)
830         fprintf(spawn->tochild,"HOST %s\n",keyserver->host);
831
832       if(keyserver->port)
833         fprintf(spawn->tochild,"PORT %s\n",keyserver->port);
834
835       if(keyserver->path)
836         fprintf(spawn->tochild,"PATH %s\n",keyserver->path);
837     }
838
839   /* Write options */
840
841   for(i=0,kopts=keyserver_opts;kopts[i].name;i++)
842     if(opt.keyserver_options.options & kopts[i].bit & REMOTE_TELL)
843       fprintf(spawn->tochild,"OPTION %s\n",kopts[i].name);
844
845   for(i=0;i<opt.keyserver_options.verbose;i++)
846     fprintf(spawn->tochild,"OPTION verbose\n");
847
848   for(temp=opt.keyserver_options.other;temp;temp=temp->next)
849     fprintf(spawn->tochild,"OPTION %s\n",temp->d);
850
851   switch(action)
852     {
853     case GET:
854       {
855         fprintf(spawn->tochild,"COMMAND GET\n\n");
856
857         /* Which keys do we want? */
858
859         for(i=0;i<count;i++)
860           {
861             if(desc[i].mode==KEYDB_SEARCH_MODE_FPR20)
862               {
863                 int f;
864
865                 fprintf(spawn->tochild,"0x");
866
867                 for(f=0;f<MAX_FINGERPRINT_LEN;f++)
868                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
869
870                 fprintf(spawn->tochild,"\n");
871               }
872             else if(desc[i].mode==KEYDB_SEARCH_MODE_FPR16)
873               {
874                 int f;
875
876                 fprintf(spawn->tochild,"0x");
877
878                 for(f=0;f<16;f++)
879                   fprintf(spawn->tochild,"%02X",desc[i].u.fpr[f]);
880
881                 fprintf(spawn->tochild,"\n");
882               }
883             else if(desc[i].mode==KEYDB_SEARCH_MODE_LONG_KID)
884               fprintf(spawn->tochild,"0x%08lX%08lX\n",
885                       (ulong)desc[i].u.kid[0],
886                       (ulong)desc[i].u.kid[1]);
887             else if(desc[i].mode==KEYDB_SEARCH_MODE_SHORT_KID)
888               fprintf(spawn->tochild,"0x%08lX\n",
889                       (ulong)desc[i].u.kid[1]);
890             else if(desc[i].mode==KEYDB_SEARCH_MODE_NONE)
891               continue;
892             else
893               BUG();
894
895             log_info(_("requesting key %s from %s server %s\n"),
896                      keystr_from_desc(&desc[i]),
897                      keyserver->scheme,keyserver->host);
898           }
899
900         fprintf(spawn->tochild,"\n");
901
902         break;
903       }
904
905     case SEND:
906       {
907         STRLIST key;
908
909         /* Note the extra \n here to send an empty keylist block */
910         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
911
912         for(key=list;key!=NULL;key=key->next)
913           {
914             armor_filter_context_t afx;
915             IOBUF buffer=iobuf_temp();
916             KBNODE block;
917
918             temp=NULL;
919             add_to_strlist(&temp,key->d);
920
921             memset(&afx,0,sizeof(afx));
922             afx.what=1;
923             iobuf_push_filter(buffer,armor_filter,&afx);
924
925             /* TODO: Remove Comment: lines from keys exported this
926                way? */
927
928             if(export_pubkeys_stream(buffer,temp,&block,
929                                      opt.keyserver_options.export_options)==-1)
930               iobuf_close(buffer);
931             else
932               {
933                 KBNODE node;
934
935                 iobuf_flush_temp(buffer);
936
937                 merge_keys_and_selfsig(block);
938
939                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
940                         (ulong)block->pkt->pkt.public_key->keyid[0],
941                         (ulong)block->pkt->pkt.public_key->keyid[1]);
942
943                 for(node=block;node;node=node->next)
944                   {
945                     switch(node->pkt->pkttype)
946                       {
947                       default:
948                         continue;
949
950                       case PKT_PUBLIC_KEY:
951                       case PKT_PUBLIC_SUBKEY:
952                         {
953                           PKT_public_key *pk=node->pkt->pkt.public_key;
954
955                           keyid_from_pk(pk,NULL);
956
957                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
958                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
959                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
960                                   pk->pubkey_algo,
961                                   nbits_from_pk(pk),
962                                   pk->timestamp,
963                                   pk->expiredate);
964
965                           if(pk->is_revoked)
966                             fprintf(spawn->tochild,"r");
967                           if(pk->has_expired)
968                             fprintf(spawn->tochild,"e");
969
970                           fprintf(spawn->tochild,"\n");
971                         }
972                         break;
973
974                       case PKT_USER_ID:
975                         {
976                           PKT_user_id *uid=node->pkt->pkt.user_id;
977                           int r;
978
979                           if(uid->attrib_data)
980                             continue;
981
982                           fprintf(spawn->tochild,"uid:");
983
984                           /* Quote ':', '%', and any 8-bit
985                              characters */
986                           for(r=0;r<uid->len;r++)
987                             {
988                               if(uid->name[r]==':' || uid->name[r]=='%'
989                                  || uid->name[r]&0x80)
990                                 fprintf(spawn->tochild,"%%%02X",
991                                         (byte)uid->name[r]);
992                               else
993                                 fprintf(spawn->tochild,"%c",uid->name[r]);
994                             }
995
996                           fprintf(spawn->tochild,":%u:%u:",
997                                   uid->created,uid->expiredate);
998
999                           if(uid->is_revoked)
1000                             fprintf(spawn->tochild,"r");
1001                           if(uid->is_expired)
1002                             fprintf(spawn->tochild,"e");
1003
1004                           fprintf(spawn->tochild,"\n");
1005                         }
1006                         break;
1007
1008                         /* This bit is really for the benefit of
1009                            people who store their keys in LDAP
1010                            servers.  It makes it easy to do queries
1011                            for things like "all keys signed by
1012                            Isabella". */
1013                       case PKT_SIGNATURE:
1014                         {
1015                           PKT_signature *sig=node->pkt->pkt.signature;
1016
1017                           if(!IS_UID_SIG(sig))
1018                             continue;
1019
1020                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1021                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1022                                   sig->sig_class,sig->timestamp,
1023                                   sig->expiredate);
1024                         }
1025                         break;
1026                       }
1027                   }
1028
1029                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1030                         (ulong)block->pkt->pkt.public_key->keyid[0],
1031                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1032
1033                 fprintf(spawn->tochild,"KEY %s BEGIN\n",key->d);
1034                 fwrite(iobuf_get_temp_buffer(buffer),
1035                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1036                 fprintf(spawn->tochild,"KEY %s END\n",key->d);
1037
1038                 iobuf_close(buffer);
1039
1040                 log_info(_("sending key %s to %s server %s\n"),
1041                          keystr(block->pkt->pkt.public_key->keyid),
1042                          keyserver->scheme,keyserver->host);
1043
1044                 release_kbnode(block);
1045               }
1046
1047             free_strlist(temp);
1048           }
1049
1050         break;
1051       }
1052
1053     case SEARCH:
1054       {
1055         STRLIST key;
1056
1057         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1058
1059         /* Which keys do we want?  Remember that the gpgkeys_ program
1060            is going to lump these together into a search string. */
1061
1062         for(key=list;key!=NULL;key=key->next)
1063           {
1064             fprintf(spawn->tochild,"%s\n",key->d);
1065             if(key!=list)
1066               {
1067                 searchstr=m_realloc(searchstr,
1068                                     strlen(searchstr)+strlen(key->d)+2);
1069                 strcat(searchstr," ");
1070               }
1071             else
1072               {
1073                 searchstr=m_alloc(strlen(key->d)+1);
1074                 searchstr[0]='\0';
1075               }
1076
1077             strcat(searchstr,key->d);
1078           }
1079
1080         fprintf(spawn->tochild,"\n");
1081
1082         log_info(_("searching for \"%s\" from %s server %s\n"),
1083                  searchstr,keyserver->scheme,keyserver->host);
1084
1085         break;
1086       }
1087
1088     default:
1089       log_fatal(_("no keyserver action!\n"));
1090       break;
1091     }
1092
1093   /* Done sending, so start reading. */
1094   ret=exec_read(spawn);
1095   if(ret)
1096     goto fail;
1097
1098   /* Now handle the response */
1099
1100   for(;;)
1101     {
1102       int plen;
1103       char *ptr;
1104
1105       maxlen=1024;
1106       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1107         {
1108           ret=G10ERR_READ_FILE;
1109           goto fail; /* i.e. EOF */
1110         }
1111
1112       ptr=line;
1113
1114       /* remove trailing whitespace */
1115       plen=strlen(ptr);
1116       while(plen>0 && ascii_isspace(ptr[plen-1]))
1117         plen--;
1118       plen[ptr]='\0';
1119
1120       if(*ptr=='\0')
1121         break;
1122
1123       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1124         {
1125           gotversion=1;
1126
1127           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1128             {
1129               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1130                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1131               goto fail;
1132             }
1133         }
1134       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1135         {
1136           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1137             log_info(_("WARNING: keyserver handler from a different"
1138                        " version of GnuPG (%s)\n"),&ptr[8]);
1139         }
1140       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1141         outofband=1; /* Currently the only OPTION */
1142     }
1143
1144   if(!gotversion)
1145     {
1146       log_error(_("keyserver did not send VERSION\n"));
1147       goto fail;
1148     }
1149
1150   if(!outofband)
1151     switch(action)
1152       {
1153       case GET:
1154         {
1155           void *stats_handle;
1156
1157           stats_handle=import_new_stats_handle();
1158
1159           /* Slurp up all the key data.  In the future, it might be
1160              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1161              It's harmless to ignore them, but ignoring them does make
1162              gpg complain about "no valid OpenPGP data found".  One
1163              way to do this could be to continue parsing this
1164              line-by-line and make a temp iobuf for each key. */
1165
1166           import_keys_stream(spawn->fromchild,stats_handle,
1167                              opt.keyserver_options.import_options);
1168
1169           import_print_stats(stats_handle);
1170           import_release_stats_handle(stats_handle);
1171
1172           break;
1173         }
1174
1175         /* Nothing to do here */
1176       case SEND:
1177         break;
1178
1179       case SEARCH:
1180         keyserver_search_prompt(spawn->fromchild,searchstr);
1181         break;
1182
1183       default:
1184         log_fatal(_("no keyserver action!\n"));
1185         break;
1186       }
1187
1188  fail:
1189   m_free(line);
1190   m_free(searchstr);
1191
1192   *prog=exec_finish(spawn);
1193
1194   return ret;
1195 }
1196
1197 static int 
1198 keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
1199                int count,struct keyserver_spec *keyserver)
1200 {
1201   int rc=0,ret=0;
1202
1203   if(!keyserver)
1204     {
1205       log_error(_("no keyserver known (use option --keyserver)\n"));
1206       return G10ERR_BAD_URI;
1207     }
1208
1209 #ifdef DISABLE_KEYSERVER_HELPERS
1210
1211   log_error(_("external keyserver calls are not supported in this build\n"));
1212   return G10ERR_KEYSERVER;
1213
1214 #else
1215   /* Spawn a handler */
1216
1217   rc=keyserver_spawn(action,list,desc,count,&ret,keyserver);
1218   if(ret)
1219     {
1220       switch(ret)
1221         {
1222         case KEYSERVER_SCHEME_NOT_FOUND:
1223           log_error(_("no handler for keyserver scheme `%s'\n"),
1224                     keyserver->scheme);
1225           break;
1226
1227         case KEYSERVER_NOT_SUPPORTED:
1228           log_error(_("action `%s' not supported with keyserver "
1229                       "scheme `%s'\n"),
1230                     action==GET?"get":action==SEND?"send":
1231                     action==SEARCH?"search":"unknown",
1232                     keyserver->scheme);
1233           break;
1234
1235         case KEYSERVER_VERSION_ERROR:
1236           log_error(_("gpgkeys_%s does not support handler version %d\n"),
1237                     keyserver->scheme,KEYSERVER_PROTO_VERSION);
1238           break;
1239
1240         case KEYSERVER_INTERNAL_ERROR:
1241         default:
1242           log_error(_("keyserver internal error\n"));
1243           break;
1244         }
1245
1246       return G10ERR_KEYSERVER;
1247     }
1248
1249   if(rc)
1250     {
1251       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1252
1253       return rc;
1254     }
1255
1256   return 0;
1257 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1258 }
1259
1260 int 
1261 keyserver_export(STRLIST users)
1262 {
1263   STRLIST sl=NULL;
1264   KEYDB_SEARCH_DESC desc;
1265   int rc=0;
1266
1267   /* Weed out descriptors that we don't support sending */
1268   for(;users;users=users->next)
1269     {
1270       classify_user_id (users->d, &desc);
1271       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1272          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1273          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1274          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1275         {
1276           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1277           continue;
1278         }
1279       else
1280         append_to_strlist(&sl,users->d);
1281     }
1282
1283   if(sl)
1284     {
1285       rc=keyserver_work(SEND,sl,NULL,0,opt.keyserver);
1286       free_strlist(sl);
1287     }
1288
1289   return rc;
1290 }
1291
1292 int 
1293 keyserver_import(STRLIST users)
1294 {
1295   KEYDB_SEARCH_DESC *desc;
1296   int num=100,count=0;
1297   int rc=0;
1298
1299   /* Build a list of key ids */
1300   desc=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1301
1302   for(;users;users=users->next)
1303     {
1304       classify_user_id (users->d, &desc[count]);
1305       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1306          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1307          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1308          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1309         {
1310           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1311           continue;
1312         }
1313
1314       count++;
1315       if(count==num)
1316         {
1317           num+=100;
1318           desc=m_realloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1319         }
1320     }
1321
1322   if(count>0)
1323     rc=keyserver_work(GET,NULL,desc,count,opt.keyserver);
1324
1325   m_free(desc);
1326
1327   return rc;
1328 }
1329
1330 int
1331 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1332                         struct keyserver_spec *keyserver)
1333 {
1334   KEYDB_SEARCH_DESC desc;
1335
1336   memset(&desc,0,sizeof(desc));
1337
1338   if(fprint_len==16)
1339     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1340   else if(fprint_len==20)
1341     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1342   else
1343     return -1;
1344
1345   memcpy(desc.u.fpr,fprint,fprint_len);
1346
1347   return keyserver_work(GET,NULL,&desc,1,keyserver);
1348 }
1349
1350 int 
1351 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1352 {
1353   KEYDB_SEARCH_DESC desc;
1354
1355   memset(&desc,0,sizeof(desc));
1356
1357   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1358   desc.u.kid[0]=keyid[0];
1359   desc.u.kid[1]=keyid[1];
1360
1361   return keyserver_work(GET,NULL,&desc,1,keyserver);
1362 }
1363
1364 /* code mostly stolen from do_export_stream */
1365 static int 
1366 keyidlist(STRLIST users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1367 {
1368   int rc=0,ndesc,num=100;
1369   KBNODE keyblock=NULL,node;
1370   KEYDB_HANDLE kdbhd;
1371   KEYDB_SEARCH_DESC *desc;
1372   STRLIST sl;
1373
1374   *count=0;
1375
1376   *klist=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1377
1378   kdbhd=keydb_new(0);
1379
1380   if(!users)
1381     {
1382       ndesc = 1;
1383       desc = m_alloc_clear ( ndesc * sizeof *desc);
1384       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1385     }
1386   else
1387     {
1388       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
1389         ;
1390       desc = m_alloc ( ndesc * sizeof *desc);
1391         
1392       for (ndesc=0, sl=users; sl; sl = sl->next)
1393         {
1394           if(classify_user_id (sl->d, desc+ndesc))
1395             ndesc++;
1396           else
1397             log_error (_("key \"%s\" not found: %s\n"),
1398                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1399         }
1400     }
1401
1402   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1403     {
1404       if (!users) 
1405         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1406
1407       /* read the keyblock */
1408       rc = keydb_get_keyblock (kdbhd, &keyblock );
1409       if( rc )
1410         {
1411           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1412           goto leave;
1413         }
1414
1415       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1416         {
1417           /* This is to work around a bug in some keyservers (pksd and
1418              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1419              The answer is to refresh both the correct v4 keyid
1420              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1421              This only happens for key refresh using the HKP scheme
1422              and if the refresh-add-fake-v3-keyids keyserver option is
1423              set. */
1424           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1425              node->pkt->pkt.public_key->version>=4)
1426             {
1427               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1428               mpi_get_keyid(node->pkt->pkt.public_key->pkey[0],
1429                             (*klist)[*count].u.kid);
1430               (*count)++;
1431
1432               if(*count==num)
1433                 {
1434                   num+=100;
1435                   *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1436                 }
1437             }
1438
1439           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1440              This is because it's easy to calculate any sort of keyid
1441              from a v4 fingerprint, but not a v3 fingerprint. */
1442
1443           if(node->pkt->pkt.public_key->version<4)
1444             {
1445               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1446               keyid_from_pk(node->pkt->pkt.public_key,
1447                             (*klist)[*count].u.kid);
1448             }
1449           else
1450             {
1451               size_t dummy;
1452
1453               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1454               fingerprint_from_pk(node->pkt->pkt.public_key,
1455                                   (*klist)[*count].u.fpr,&dummy);
1456             }
1457
1458           /* This is a little hackish, using the skipfncvalue as a
1459              void* pointer to the keyserver spec, but we don't need
1460              the skipfnc here, and it saves having an additional field
1461              for this (which would be wasted space most of the
1462              time). */
1463
1464           (*klist)[*count].skipfncvalue=NULL;
1465
1466           /* Are we honoring preferred keyservers? */
1467           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1468             {
1469               PKT_user_id *uid=NULL;
1470               PKT_signature *sig=NULL;
1471
1472               merge_keys_and_selfsig(keyblock);
1473
1474               for(node=node->next;node;node=node->next)
1475                 {
1476                   if(node->pkt->pkttype==PKT_USER_ID
1477                      && node->pkt->pkt.user_id->is_primary)
1478                     uid=node->pkt->pkt.user_id;
1479                   else if(node->pkt->pkttype==PKT_SIGNATURE
1480                           && node->pkt->pkt.signature->
1481                           flags.chosen_selfsig && uid)
1482                     {
1483                       sig=node->pkt->pkt.signature;
1484                       break;
1485                     }
1486                 }
1487
1488               /* Try and parse the keyserver URL.  If it doesn't work,
1489                  then we end up writing NULL which indicates we are
1490                  the same as any other key. */
1491               if(uid && sig)
1492                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1493             }
1494
1495           (*count)++;
1496
1497           if(*count==num)
1498             {
1499               num+=100;
1500               *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1501             }
1502         }
1503     }
1504
1505   if(rc==-1)
1506     rc=0;
1507   
1508  leave:
1509   if(rc)
1510     m_free(*klist);
1511   m_free(desc);
1512   keydb_release(kdbhd);
1513   release_kbnode(keyblock);
1514
1515   return rc;
1516 }
1517
1518 /* Note this is different than the original HKP refresh.  It allows
1519    usernames to refresh only part of the keyring. */
1520
1521 int 
1522 keyserver_refresh(STRLIST users)
1523 {
1524   int rc,count,numdesc,fakev3=0;
1525   KEYDB_SEARCH_DESC *desc;
1526
1527   /* We switch merge_only on during a refresh, as 'refresh' should
1528      never import new keys, even if their keyids match.  Is it worth
1529      preserving the old merge_only value here? */
1530   opt.import_options|=IMPORT_MERGE_ONLY;
1531
1532   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1533      scheme, then enable fake v3 keyid generation. */
1534   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1535      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1536          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1537     fakev3=1;
1538
1539   rc=keyidlist(users,&desc,&numdesc,fakev3);
1540   if(rc)
1541     return rc;
1542
1543   count=numdesc;
1544   if(count>0)
1545     {
1546       int i;
1547
1548       /* Try to handle preferred keyserver keys first */
1549       for(i=0;i<count;i++)
1550         {
1551           if(desc[i].skipfncvalue)
1552             {
1553               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1554
1555               /* We use the keyserver structure we parsed out before.
1556                  Note that a preferred keyserver without a scheme://
1557                  will be interpreted as hkp:// */
1558
1559               rc=keyserver_work(GET,NULL,&desc[i],1,keyserver);
1560               if(rc)
1561                 log_info(_("WARNING: unable to refresh key %s"
1562                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
1563                          keyserver->uri,g10_errstr(rc));
1564               else
1565                 {
1566                   /* We got it, so mark it as NONE so we don't try and
1567                      get it again from the regular keyserver. */
1568
1569                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
1570                   count--;
1571                 }
1572
1573               free_keyserver_spec(keyserver);
1574             }
1575         }
1576     }
1577
1578   if(count>0)
1579     {
1580       if(opt.keyserver)
1581         {
1582           if(count==1)
1583             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
1584           else
1585             log_info(_("refreshing %d keys from %s\n"),
1586                      count,opt.keyserver->uri);
1587         }
1588
1589       rc=keyserver_work(GET,NULL,desc,numdesc,opt.keyserver);
1590     }
1591
1592   m_free(desc);
1593
1594   return rc;
1595 }
1596
1597 int
1598 keyserver_search(STRLIST tokens)
1599 {
1600   if(tokens)
1601     return keyserver_work(SEARCH,tokens,NULL,0,opt.keyserver);
1602   else
1603     return 0;
1604 }