* pkclist.c (do_edit_ownertrust): Use the same translated string for
[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             if(keyserver->host)
896               log_info(_("requesting key %s from %s server %s\n"),
897                        keystr_from_desc(&desc[i]),
898                        keyserver->scheme,keyserver->host);
899             else
900               log_info(_("requesting key %s from %s\n"),
901                        keystr_from_desc(&desc[i]),keyserver->uri);
902           }
903
904         fprintf(spawn->tochild,"\n");
905
906         break;
907       }
908
909     case SEND:
910       {
911         STRLIST key;
912
913         /* Note the extra \n here to send an empty keylist block */
914         fprintf(spawn->tochild,"COMMAND SEND\n\n\n");
915
916         for(key=list;key!=NULL;key=key->next)
917           {
918             armor_filter_context_t afx;
919             IOBUF buffer=iobuf_temp();
920             KBNODE block;
921
922             temp=NULL;
923             add_to_strlist(&temp,key->d);
924
925             memset(&afx,0,sizeof(afx));
926             afx.what=1;
927             iobuf_push_filter(buffer,armor_filter,&afx);
928
929             /* TODO: Remove Comment: lines from keys exported this
930                way? */
931
932             if(export_pubkeys_stream(buffer,temp,&block,
933                                      opt.keyserver_options.export_options)==-1)
934               iobuf_close(buffer);
935             else
936               {
937                 KBNODE node;
938
939                 iobuf_flush_temp(buffer);
940
941                 merge_keys_and_selfsig(block);
942
943                 fprintf(spawn->tochild,"INFO %08lX%08lX BEGIN\n",
944                         (ulong)block->pkt->pkt.public_key->keyid[0],
945                         (ulong)block->pkt->pkt.public_key->keyid[1]);
946
947                 for(node=block;node;node=node->next)
948                   {
949                     switch(node->pkt->pkttype)
950                       {
951                       default:
952                         continue;
953
954                       case PKT_PUBLIC_KEY:
955                       case PKT_PUBLIC_SUBKEY:
956                         {
957                           PKT_public_key *pk=node->pkt->pkt.public_key;
958
959                           keyid_from_pk(pk,NULL);
960
961                           fprintf(spawn->tochild,"%sb:%08lX%08lX:%u:%u:%u:%u:",
962                                   node->pkt->pkttype==PKT_PUBLIC_KEY?"pu":"su",
963                                   (ulong)pk->keyid[0],(ulong)pk->keyid[1],
964                                   pk->pubkey_algo,
965                                   nbits_from_pk(pk),
966                                   pk->timestamp,
967                                   pk->expiredate);
968
969                           if(pk->is_revoked)
970                             fprintf(spawn->tochild,"r");
971                           if(pk->has_expired)
972                             fprintf(spawn->tochild,"e");
973
974                           fprintf(spawn->tochild,"\n");
975                         }
976                         break;
977
978                       case PKT_USER_ID:
979                         {
980                           PKT_user_id *uid=node->pkt->pkt.user_id;
981                           int r;
982
983                           if(uid->attrib_data)
984                             continue;
985
986                           fprintf(spawn->tochild,"uid:");
987
988                           /* Quote ':', '%', and any 8-bit
989                              characters */
990                           for(r=0;r<uid->len;r++)
991                             {
992                               if(uid->name[r]==':' || uid->name[r]=='%'
993                                  || uid->name[r]&0x80)
994                                 fprintf(spawn->tochild,"%%%02X",
995                                         (byte)uid->name[r]);
996                               else
997                                 fprintf(spawn->tochild,"%c",uid->name[r]);
998                             }
999
1000                           fprintf(spawn->tochild,":%u:%u:",
1001                                   uid->created,uid->expiredate);
1002
1003                           if(uid->is_revoked)
1004                             fprintf(spawn->tochild,"r");
1005                           if(uid->is_expired)
1006                             fprintf(spawn->tochild,"e");
1007
1008                           fprintf(spawn->tochild,"\n");
1009                         }
1010                         break;
1011
1012                         /* This bit is really for the benefit of
1013                            people who store their keys in LDAP
1014                            servers.  It makes it easy to do queries
1015                            for things like "all keys signed by
1016                            Isabella". */
1017                       case PKT_SIGNATURE:
1018                         {
1019                           PKT_signature *sig=node->pkt->pkt.signature;
1020
1021                           if(!IS_UID_SIG(sig))
1022                             continue;
1023
1024                           fprintf(spawn->tochild,"sig:%08lX%08lX:%X:%u:%u\n",
1025                                   (ulong)sig->keyid[0],(ulong)sig->keyid[1],
1026                                   sig->sig_class,sig->timestamp,
1027                                   sig->expiredate);
1028                         }
1029                         break;
1030                       }
1031                   }
1032
1033                 fprintf(spawn->tochild,"INFO %08lX%08lX END\n",
1034                         (ulong)block->pkt->pkt.public_key->keyid[0],
1035                         (ulong)block->pkt->pkt.public_key->keyid[1]);
1036
1037                 fprintf(spawn->tochild,"KEY %s BEGIN\n",key->d);
1038                 fwrite(iobuf_get_temp_buffer(buffer),
1039                        iobuf_get_temp_length(buffer),1,spawn->tochild);
1040                 fprintf(spawn->tochild,"KEY %s END\n",key->d);
1041
1042                 iobuf_close(buffer);
1043
1044                 if(keyserver->host)
1045                   log_info(_("sending key %s to %s server %s\n"),
1046                            keystr(block->pkt->pkt.public_key->keyid),
1047                            keyserver->scheme,keyserver->host);
1048                 else
1049                   log_info(_("sending key %s to %s\n"),
1050                            keystr(block->pkt->pkt.public_key->keyid),
1051                            keyserver->uri);
1052
1053                 release_kbnode(block);
1054               }
1055
1056             free_strlist(temp);
1057           }
1058
1059         break;
1060       }
1061
1062     case SEARCH:
1063       {
1064         STRLIST key;
1065
1066         fprintf(spawn->tochild,"COMMAND SEARCH\n\n");
1067
1068         /* Which keys do we want?  Remember that the gpgkeys_ program
1069            is going to lump these together into a search string. */
1070
1071         for(key=list;key!=NULL;key=key->next)
1072           {
1073             fprintf(spawn->tochild,"%s\n",key->d);
1074             if(key!=list)
1075               {
1076                 searchstr=m_realloc(searchstr,
1077                                     strlen(searchstr)+strlen(key->d)+2);
1078                 strcat(searchstr," ");
1079               }
1080             else
1081               {
1082                 searchstr=m_alloc(strlen(key->d)+1);
1083                 searchstr[0]='\0';
1084               }
1085
1086             strcat(searchstr,key->d);
1087           }
1088
1089         fprintf(spawn->tochild,"\n");
1090
1091         if(keyserver->host)
1092           log_info(_("searching for \"%s\" from %s server %s\n"),
1093                    searchstr,keyserver->scheme,keyserver->host);
1094         else
1095           log_info(_("searching for \"%s\" from %s\n"),
1096                    searchstr,keyserver->uri);
1097
1098         break;
1099       }
1100
1101     default:
1102       log_fatal(_("no keyserver action!\n"));
1103       break;
1104     }
1105
1106   /* Done sending, so start reading. */
1107   ret=exec_read(spawn);
1108   if(ret)
1109     goto fail;
1110
1111   /* Now handle the response */
1112
1113   for(;;)
1114     {
1115       int plen;
1116       char *ptr;
1117
1118       maxlen=1024;
1119       if(iobuf_read_line(spawn->fromchild,&line,&buflen,&maxlen)==0)
1120         {
1121           ret=G10ERR_READ_FILE;
1122           goto fail; /* i.e. EOF */
1123         }
1124
1125       ptr=line;
1126
1127       /* remove trailing whitespace */
1128       plen=strlen(ptr);
1129       while(plen>0 && ascii_isspace(ptr[plen-1]))
1130         plen--;
1131       plen[ptr]='\0';
1132
1133       if(*ptr=='\0')
1134         break;
1135
1136       if(ascii_strncasecmp(ptr,"VERSION ",8)==0)
1137         {
1138           gotversion=1;
1139
1140           if(atoi(&ptr[8])!=KEYSERVER_PROTO_VERSION)
1141             {
1142               log_error(_("invalid keyserver protocol (us %d!=handler %d)\n"),
1143                         KEYSERVER_PROTO_VERSION,atoi(&ptr[8]));
1144               goto fail;
1145             }
1146         }
1147       else if(ascii_strncasecmp(ptr,"PROGRAM ",8)==0)
1148         {
1149           if(ascii_strncasecmp(&ptr[8],VERSION,strlen(VERSION))!=0)
1150             log_info(_("WARNING: keyserver handler from a different"
1151                        " version of GnuPG (%s)\n"),&ptr[8]);
1152         }
1153       else if(ascii_strncasecmp(ptr,"OPTION OUTOFBAND",16)==0)
1154         outofband=1; /* Currently the only OPTION */
1155     }
1156
1157   if(!gotversion)
1158     {
1159       log_error(_("keyserver did not send VERSION\n"));
1160       goto fail;
1161     }
1162
1163   if(!outofband)
1164     switch(action)
1165       {
1166       case GET:
1167         {
1168           void *stats_handle;
1169
1170           stats_handle=import_new_stats_handle();
1171
1172           /* Slurp up all the key data.  In the future, it might be
1173              nice to look for KEY foo OUTOFBAND and FAILED indicators.
1174              It's harmless to ignore them, but ignoring them does make
1175              gpg complain about "no valid OpenPGP data found".  One
1176              way to do this could be to continue parsing this
1177              line-by-line and make a temp iobuf for each key. */
1178
1179           import_keys_stream(spawn->fromchild,stats_handle,
1180                              opt.keyserver_options.import_options);
1181
1182           import_print_stats(stats_handle);
1183           import_release_stats_handle(stats_handle);
1184
1185           break;
1186         }
1187
1188         /* Nothing to do here */
1189       case SEND:
1190         break;
1191
1192       case SEARCH:
1193         keyserver_search_prompt(spawn->fromchild,searchstr);
1194         break;
1195
1196       default:
1197         log_fatal(_("no keyserver action!\n"));
1198         break;
1199       }
1200
1201  fail:
1202   m_free(line);
1203   m_free(searchstr);
1204
1205   *prog=exec_finish(spawn);
1206
1207   return ret;
1208 }
1209
1210 static int 
1211 keyserver_work(int action,STRLIST list,KEYDB_SEARCH_DESC *desc,
1212                int count,struct keyserver_spec *keyserver)
1213 {
1214   int rc=0,ret=0;
1215
1216   if(!keyserver)
1217     {
1218       log_error(_("no keyserver known (use option --keyserver)\n"));
1219       return G10ERR_BAD_URI;
1220     }
1221
1222 #ifdef DISABLE_KEYSERVER_HELPERS
1223
1224   log_error(_("external keyserver calls are not supported in this build\n"));
1225   return G10ERR_KEYSERVER;
1226
1227 #else
1228   /* Spawn a handler */
1229
1230   rc=keyserver_spawn(action,list,desc,count,&ret,keyserver);
1231   if(ret)
1232     {
1233       switch(ret)
1234         {
1235         case KEYSERVER_SCHEME_NOT_FOUND:
1236           log_error(_("no handler for keyserver scheme `%s'\n"),
1237                     keyserver->scheme);
1238           break;
1239
1240         case KEYSERVER_NOT_SUPPORTED:
1241           log_error(_("action `%s' not supported with keyserver "
1242                       "scheme `%s'\n"),
1243                     action==GET?"get":action==SEND?"send":
1244                     action==SEARCH?"search":"unknown",
1245                     keyserver->scheme);
1246           break;
1247
1248         case KEYSERVER_VERSION_ERROR:
1249           log_error(_("gpgkeys_%s does not support handler version %d\n"),
1250                     keyserver->scheme,KEYSERVER_PROTO_VERSION);
1251           break;
1252
1253         case KEYSERVER_INTERNAL_ERROR:
1254         default:
1255           log_error(_("keyserver internal error\n"));
1256           break;
1257         }
1258
1259       return G10ERR_KEYSERVER;
1260     }
1261
1262   if(rc)
1263     {
1264       log_error(_("keyserver communications error: %s\n"),g10_errstr(rc));
1265
1266       return rc;
1267     }
1268
1269   return 0;
1270 #endif /* ! DISABLE_KEYSERVER_HELPERS*/
1271 }
1272
1273 int 
1274 keyserver_export(STRLIST users)
1275 {
1276   STRLIST sl=NULL;
1277   KEYDB_SEARCH_DESC desc;
1278   int rc=0;
1279
1280   /* Weed out descriptors that we don't support sending */
1281   for(;users;users=users->next)
1282     {
1283       classify_user_id (users->d, &desc);
1284       if(desc.mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1285          desc.mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1286          desc.mode!=KEYDB_SEARCH_MODE_FPR16 &&
1287          desc.mode!=KEYDB_SEARCH_MODE_FPR20)
1288         {
1289           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1290           continue;
1291         }
1292       else
1293         append_to_strlist(&sl,users->d);
1294     }
1295
1296   if(sl)
1297     {
1298       rc=keyserver_work(SEND,sl,NULL,0,opt.keyserver);
1299       free_strlist(sl);
1300     }
1301
1302   return rc;
1303 }
1304
1305 int 
1306 keyserver_import(STRLIST users)
1307 {
1308   KEYDB_SEARCH_DESC *desc;
1309   int num=100,count=0;
1310   int rc=0;
1311
1312   /* Build a list of key ids */
1313   desc=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1314
1315   for(;users;users=users->next)
1316     {
1317       classify_user_id (users->d, &desc[count]);
1318       if(desc[count].mode!=KEYDB_SEARCH_MODE_SHORT_KID &&
1319          desc[count].mode!=KEYDB_SEARCH_MODE_LONG_KID &&
1320          desc[count].mode!=KEYDB_SEARCH_MODE_FPR16 &&
1321          desc[count].mode!=KEYDB_SEARCH_MODE_FPR20)
1322         {
1323           log_error(_("\"%s\" not a key ID: skipping\n"),users->d);
1324           continue;
1325         }
1326
1327       count++;
1328       if(count==num)
1329         {
1330           num+=100;
1331           desc=m_realloc(desc,sizeof(KEYDB_SEARCH_DESC)*num);
1332         }
1333     }
1334
1335   if(count>0)
1336     rc=keyserver_work(GET,NULL,desc,count,opt.keyserver);
1337
1338   m_free(desc);
1339
1340   return rc;
1341 }
1342
1343 int
1344 keyserver_import_fprint(const byte *fprint,size_t fprint_len,
1345                         struct keyserver_spec *keyserver)
1346 {
1347   KEYDB_SEARCH_DESC desc;
1348
1349   memset(&desc,0,sizeof(desc));
1350
1351   if(fprint_len==16)
1352     desc.mode=KEYDB_SEARCH_MODE_FPR16;
1353   else if(fprint_len==20)
1354     desc.mode=KEYDB_SEARCH_MODE_FPR20;
1355   else
1356     return -1;
1357
1358   memcpy(desc.u.fpr,fprint,fprint_len);
1359
1360   return keyserver_work(GET,NULL,&desc,1,keyserver);
1361 }
1362
1363 int 
1364 keyserver_import_keyid(u32 *keyid,struct keyserver_spec *keyserver)
1365 {
1366   KEYDB_SEARCH_DESC desc;
1367
1368   memset(&desc,0,sizeof(desc));
1369
1370   desc.mode=KEYDB_SEARCH_MODE_LONG_KID;
1371   desc.u.kid[0]=keyid[0];
1372   desc.u.kid[1]=keyid[1];
1373
1374   return keyserver_work(GET,NULL,&desc,1,keyserver);
1375 }
1376
1377 /* code mostly stolen from do_export_stream */
1378 static int 
1379 keyidlist(STRLIST users,KEYDB_SEARCH_DESC **klist,int *count,int fakev3)
1380 {
1381   int rc=0,ndesc,num=100;
1382   KBNODE keyblock=NULL,node;
1383   KEYDB_HANDLE kdbhd;
1384   KEYDB_SEARCH_DESC *desc;
1385   STRLIST sl;
1386
1387   *count=0;
1388
1389   *klist=m_alloc(sizeof(KEYDB_SEARCH_DESC)*num);
1390
1391   kdbhd=keydb_new(0);
1392
1393   if(!users)
1394     {
1395       ndesc = 1;
1396       desc = m_alloc_clear ( ndesc * sizeof *desc);
1397       desc[0].mode = KEYDB_SEARCH_MODE_FIRST;
1398     }
1399   else
1400     {
1401       for (ndesc=0, sl=users; sl; sl = sl->next, ndesc++) 
1402         ;
1403       desc = m_alloc ( ndesc * sizeof *desc);
1404         
1405       for (ndesc=0, sl=users; sl; sl = sl->next)
1406         {
1407           if(classify_user_id (sl->d, desc+ndesc))
1408             ndesc++;
1409           else
1410             log_error (_("key \"%s\" not found: %s\n"),
1411                        sl->d, g10_errstr (G10ERR_INV_USER_ID));
1412         }
1413     }
1414
1415   while (!(rc = keydb_search (kdbhd, desc, ndesc)))
1416     {
1417       if (!users) 
1418         desc[0].mode = KEYDB_SEARCH_MODE_NEXT;
1419
1420       /* read the keyblock */
1421       rc = keydb_get_keyblock (kdbhd, &keyblock );
1422       if( rc )
1423         {
1424           log_error (_("error reading keyblock: %s\n"), g10_errstr(rc) );
1425           goto leave;
1426         }
1427
1428       if((node=find_kbnode(keyblock,PKT_PUBLIC_KEY)))
1429         {
1430           /* This is to work around a bug in some keyservers (pksd and
1431              OKS) that calculate v4 RSA keyids as if they were v3 RSA.
1432              The answer is to refresh both the correct v4 keyid
1433              (e.g. 99242560) and the fake v3 keyid (e.g. 68FDDBC7).
1434              This only happens for key refresh using the HKP scheme
1435              and if the refresh-add-fake-v3-keyids keyserver option is
1436              set. */
1437           if(fakev3 && is_RSA(node->pkt->pkt.public_key->pubkey_algo) &&
1438              node->pkt->pkt.public_key->version>=4)
1439             {
1440               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1441               mpi_get_keyid(node->pkt->pkt.public_key->pkey[0],
1442                             (*klist)[*count].u.kid);
1443               (*count)++;
1444
1445               if(*count==num)
1446                 {
1447                   num+=100;
1448                   *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1449                 }
1450             }
1451
1452           /* v4 keys get full fingerprints.  v3 keys get long keyids.
1453              This is because it's easy to calculate any sort of keyid
1454              from a v4 fingerprint, but not a v3 fingerprint. */
1455
1456           if(node->pkt->pkt.public_key->version<4)
1457             {
1458               (*klist)[*count].mode=KEYDB_SEARCH_MODE_LONG_KID;
1459               keyid_from_pk(node->pkt->pkt.public_key,
1460                             (*klist)[*count].u.kid);
1461             }
1462           else
1463             {
1464               size_t dummy;
1465
1466               (*klist)[*count].mode=KEYDB_SEARCH_MODE_FPR20;
1467               fingerprint_from_pk(node->pkt->pkt.public_key,
1468                                   (*klist)[*count].u.fpr,&dummy);
1469             }
1470
1471           /* This is a little hackish, using the skipfncvalue as a
1472              void* pointer to the keyserver spec, but we don't need
1473              the skipfnc here, and it saves having an additional field
1474              for this (which would be wasted space most of the
1475              time). */
1476
1477           (*klist)[*count].skipfncvalue=NULL;
1478
1479           /* Are we honoring preferred keyservers? */
1480           if(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
1481             {
1482               PKT_user_id *uid=NULL;
1483               PKT_signature *sig=NULL;
1484
1485               merge_keys_and_selfsig(keyblock);
1486
1487               for(node=node->next;node;node=node->next)
1488                 {
1489                   if(node->pkt->pkttype==PKT_USER_ID
1490                      && node->pkt->pkt.user_id->is_primary)
1491                     uid=node->pkt->pkt.user_id;
1492                   else if(node->pkt->pkttype==PKT_SIGNATURE
1493                           && node->pkt->pkt.signature->
1494                           flags.chosen_selfsig && uid)
1495                     {
1496                       sig=node->pkt->pkt.signature;
1497                       break;
1498                     }
1499                 }
1500
1501               /* Try and parse the keyserver URL.  If it doesn't work,
1502                  then we end up writing NULL which indicates we are
1503                  the same as any other key. */
1504               if(uid && sig)
1505                 (*klist)[*count].skipfncvalue=parse_preferred_keyserver(sig);
1506             }
1507
1508           (*count)++;
1509
1510           if(*count==num)
1511             {
1512               num+=100;
1513               *klist=m_realloc(*klist,sizeof(KEYDB_SEARCH_DESC)*num);
1514             }
1515         }
1516     }
1517
1518   if(rc==-1)
1519     rc=0;
1520   
1521  leave:
1522   if(rc)
1523     m_free(*klist);
1524   m_free(desc);
1525   keydb_release(kdbhd);
1526   release_kbnode(keyblock);
1527
1528   return rc;
1529 }
1530
1531 /* Note this is different than the original HKP refresh.  It allows
1532    usernames to refresh only part of the keyring. */
1533
1534 int 
1535 keyserver_refresh(STRLIST users)
1536 {
1537   int rc,count,numdesc,fakev3=0;
1538   KEYDB_SEARCH_DESC *desc;
1539
1540   /* We switch merge_only on during a refresh, as 'refresh' should
1541      never import new keys, even if their keyids match.  Is it worth
1542      preserving the old merge_only value here? */
1543   opt.import_options|=IMPORT_MERGE_ONLY;
1544
1545   /* If refresh_add_fake_v3_keyids is on and it's a HKP or MAILTO
1546      scheme, then enable fake v3 keyid generation. */
1547   if((opt.keyserver_options.options&KEYSERVER_ADD_FAKE_V3) && opt.keyserver
1548      && (ascii_strcasecmp(opt.keyserver->scheme,"hkp")==0 ||
1549          ascii_strcasecmp(opt.keyserver->scheme,"mailto")==0))
1550     fakev3=1;
1551
1552   rc=keyidlist(users,&desc,&numdesc,fakev3);
1553   if(rc)
1554     return rc;
1555
1556   count=numdesc;
1557   if(count>0)
1558     {
1559       int i;
1560
1561       /* Try to handle preferred keyserver keys first */
1562       for(i=0;i<count;i++)
1563         {
1564           if(desc[i].skipfncvalue)
1565             {
1566               struct keyserver_spec *keyserver=desc[i].skipfncvalue;
1567
1568               /* We use the keyserver structure we parsed out before.
1569                  Note that a preferred keyserver without a scheme://
1570                  will be interpreted as hkp:// */
1571
1572               rc=keyserver_work(GET,NULL,&desc[i],1,keyserver);
1573               if(rc)
1574                 log_info(_("WARNING: unable to refresh key %s"
1575                            " via %s: %s\n"),keystr_from_desc(&desc[i]),
1576                          keyserver->uri,g10_errstr(rc));
1577               else
1578                 {
1579                   /* We got it, so mark it as NONE so we don't try and
1580                      get it again from the regular keyserver. */
1581
1582                   desc[i].mode=KEYDB_SEARCH_MODE_NONE;
1583                   count--;
1584                 }
1585
1586               free_keyserver_spec(keyserver);
1587             }
1588         }
1589     }
1590
1591   if(count>0)
1592     {
1593       if(opt.keyserver)
1594         {
1595           if(count==1)
1596             log_info(_("refreshing 1 key from %s\n"),opt.keyserver->uri);
1597           else
1598             log_info(_("refreshing %d keys from %s\n"),
1599                      count,opt.keyserver->uri);
1600         }
1601
1602       rc=keyserver_work(GET,NULL,desc,numdesc,opt.keyserver);
1603     }
1604
1605   m_free(desc);
1606
1607   return rc;
1608 }
1609
1610 int
1611 keyserver_search(STRLIST tokens)
1612 {
1613   if(tokens)
1614     return keyserver_work(SEARCH,tokens,NULL,0,opt.keyserver);
1615   else
1616     return 0;
1617 }