Decryption and signi via agent is now implemented.
[gnupg.git] / keyserver / gpgkeys_ldap.c
1 /* gpgkeys_ldap.c - talk to a LDAP keyserver
2  * Copyright (C) 2001, 2002, 2004, 2005, 2006
3  *               2007  Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * In addition, as a special exception, the Free Software Foundation
21  * gives permission to link the code of the keyserver helper tools:
22  * gpgkeys_ldap, gpgkeys_curl and gpgkeys_hkp with the OpenSSL
23  * project's "OpenSSL" library (or with modified versions of it that
24  * use the same license as the "OpenSSL" library), and distribute the
25  * linked executables.  You must obey the GNU General Public License
26  * in all respects for all of the code used other than "OpenSSL".  If
27  * you modify this file, you may extend this exception to your version
28  * of the file, but you are not obligated to do so.  If you do not
29  * wish to do so, delete this exception statement from your version.
30  */
31
32 #include <config.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <time.h>
36 #include <unistd.h>
37 #ifdef HAVE_GETOPT_H
38 #include <getopt.h>
39 #endif
40 #include <stdlib.h>
41 #include <errno.h>
42 #include <assert.h>
43
44 #ifdef _WIN32
45 #include <winsock2.h>
46 #include <winldap.h>
47 #else
48 #ifdef NEED_LBER_H
49 #include <lber.h>
50 #endif
51 /* For OpenLDAP, to enable the API that we're using. */
52 #define LDAP_DEPRECATED 1
53 #include <ldap.h>
54 #endif
55
56 #include "util.h"
57 #include "keyserver.h"
58 #include "ksutil.h"
59
60 #ifdef __riscos__
61 #include "util.h"
62 #endif
63
64 extern char *optarg;
65 extern int optind;
66
67 static int real_ldap=0;
68 static char *basekeyspacedn=NULL;
69 static char *pgpkeystr="pgpKey";
70 static FILE *input=NULL,*output=NULL,*console=NULL;
71 static LDAP *ldap=NULL;
72 static struct ks_options *opt;
73
74 #ifndef HAVE_TIMEGM
75 time_t timegm(struct tm *tm);
76 #endif
77
78 static int
79 ldap_err_to_gpg_err(int err)
80 {
81   int ret;
82
83   switch(err)
84     {
85     case LDAP_ALREADY_EXISTS:
86       ret=KEYSERVER_KEY_EXISTS;
87       break;
88
89     case LDAP_SERVER_DOWN:
90       ret=KEYSERVER_UNREACHABLE;
91       break;
92
93     default:
94       ret=KEYSERVER_GENERAL_ERROR;
95       break;
96     }
97
98   return ret;
99 }
100
101 static int
102 ldap_to_gpg_err(LDAP *ld)
103 {
104 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
105
106   int err;
107
108   if(ldap_get_option(ld,LDAP_OPT_ERROR_NUMBER,&err)==0)
109     return ldap_err_to_gpg_err(err);
110   else
111     return KEYSERVER_GENERAL_ERROR;
112
113 #elif defined(HAVE_LDAP_LD_ERRNO)
114
115   return ldap_err_to_gpg_err(ld->ld_errno);
116
117 #else
118
119   /* We should never get here since the LDAP library should always
120      have either ldap_get_option or ld_errno, but just in case... */
121   return KEYSERVER_GENERAL_ERROR;
122
123 #endif
124 }
125
126 static int
127 key_in_keylist(const char *key,struct keylist *list)
128 {
129   struct keylist *keyptr=list;
130
131   while(keyptr!=NULL)
132     {
133       if(strcasecmp(key,keyptr->str)==0)
134         return 1;
135
136       keyptr=keyptr->next;
137     }
138
139   return 0;
140 }
141
142 static int
143 add_key_to_keylist(const char *key,struct keylist **list)
144 {
145   struct keylist *keyptr=malloc(sizeof(struct keylist));
146
147   if(keyptr==NULL)
148     {
149       fprintf(console,"gpgkeys: out of memory when deduping "
150               "key list\n");
151       return KEYSERVER_NO_MEMORY;
152     }
153
154   strncpy(keyptr->str,key,MAX_LINE);
155   keyptr->str[MAX_LINE-1]='\0';
156   keyptr->next=*list;
157   *list=keyptr;
158
159   return 0;
160 }
161
162 static void
163 free_keylist(struct keylist *list)
164 {
165   while(list!=NULL)
166     {
167       struct keylist *keyptr=list;
168
169       list=keyptr->next;
170       free(keyptr);
171     }
172 }
173
174 static time_t
175 ldap2epochtime(const char *timestr)
176 {
177   struct tm pgptime;
178   time_t answer;
179
180   memset(&pgptime,0,sizeof(pgptime));
181
182   /* YYYYMMDDHHmmssZ */
183
184   sscanf(timestr,"%4d%2d%2d%2d%2d%2d",
185          &pgptime.tm_year,
186          &pgptime.tm_mon,
187          &pgptime.tm_mday,
188          &pgptime.tm_hour,
189          &pgptime.tm_min,
190          &pgptime.tm_sec);
191
192   pgptime.tm_year-=1900;
193   pgptime.tm_isdst=-1;
194   pgptime.tm_mon--;
195
196   /* mktime() takes the timezone into account, so we use timegm() */
197
198   answer=timegm(&pgptime);
199
200   return answer;
201 }
202
203 /* Caller must free */
204 static char *
205 epoch2ldaptime(time_t stamp)
206 {
207   struct tm *ldaptime;
208   char buf[16];
209
210   ldaptime=gmtime(&stamp);
211
212   ldaptime->tm_year+=1900;
213   ldaptime->tm_mon++;
214
215   /* YYYYMMDDHHmmssZ */
216
217   sprintf(buf,"%04d%02d%02d%02d%02d%02dZ",
218           ldaptime->tm_year,
219           ldaptime->tm_mon,
220           ldaptime->tm_mday,
221           ldaptime->tm_hour,
222           ldaptime->tm_min,
223           ldaptime->tm_sec);
224
225   return strdup(buf);
226 }
227
228 /* Append two onto the end of one.  Two is not freed, but its pointers
229    are now part of one.  Make sure you don't free them both! */
230 static int
231 join_two_modlists(LDAPMod ***one,LDAPMod **two)
232 {
233   int i,one_count=0,two_count=0;
234   LDAPMod **grow;
235
236   for(grow=*one;*grow;grow++)
237     one_count++;
238
239   for(grow=two;*grow;grow++)
240     two_count++;
241
242   grow=realloc(*one,sizeof(LDAPMod *)*(one_count+two_count+1));
243   if(!grow)
244     return 0;
245
246   for(i=0;i<two_count;i++)
247     grow[one_count+i]=two[i];
248
249   grow[one_count+i]=NULL;
250
251   *one=grow;
252
253   return 1;
254 }
255
256 /* Passing a NULL for value effectively deletes that attribute.  This
257    doesn't mean "delete" in the sense of removing something from the
258    modlist, but "delete" in the LDAP sense of adding a modlist item
259    that specifies LDAP_MOD_REPLACE and a null attribute for the given
260    attribute.  LDAP_MOD_DELETE doesn't work here as we don't know if
261    the attribute in question exists or not. */
262
263 static int
264 make_one_attr(LDAPMod ***modlist,char *attr,const char *value)
265 {
266   LDAPMod **m;
267   int nummods=0;
268
269   /* Search modlist for the attribute we're playing with. */
270   for(m=*modlist;*m;m++)
271     {
272       if(strcasecmp((*m)->mod_type,attr)==0)
273         {
274           char **ptr=(*m)->mod_values;
275           int numvalues=0;
276
277           /* We have this attribute already, so when the REPLACE
278              happens, the server attributes will be replaced
279              anyway. */
280           if(!value)
281             return 1;
282
283           if(ptr)
284             for(ptr=(*m)->mod_values;*ptr;ptr++)
285               {
286                 /* Duplicate value */
287                 if(strcmp(*ptr,value)==0)
288                   return 1;
289                 numvalues++;
290               }
291
292           ptr=realloc((*m)->mod_values,sizeof(char *)*(numvalues+2));
293           if(!ptr)
294             return 0;
295
296           (*m)->mod_values=ptr;
297           ptr[numvalues]=strdup(value);
298           if(!ptr[numvalues])
299             return 0;
300
301           ptr[numvalues+1]=NULL;
302           break;
303         }
304
305       nummods++;
306     }
307
308   /* We didn't find the attr, so make one and add it to the end */
309   if(!*m)
310     {
311       LDAPMod **grow;
312
313       grow=realloc(*modlist,sizeof(LDAPMod *)*(nummods+2));
314       if(!grow)
315         return 0;
316
317       *modlist=grow;
318       grow[nummods]=malloc(sizeof(LDAPMod));
319       if(!grow[nummods])
320         return 0;
321       grow[nummods]->mod_op=LDAP_MOD_REPLACE;
322       grow[nummods]->mod_type=attr;
323       if(value)
324         {
325           grow[nummods]->mod_values=malloc(sizeof(char *)*2);
326           if(!grow[nummods]->mod_values)
327             {
328               grow[nummods]=NULL;
329               return 0;
330             }
331
332           /* Is this the right thing?  Can a UTF8-encoded user ID have
333              embedded nulls? */
334           grow[nummods]->mod_values[0]=strdup(value);
335           if(!grow[nummods]->mod_values[0])
336             {
337               free(grow[nummods]->mod_values);
338               grow[nummods]=NULL;
339               return 0;
340             }
341
342           grow[nummods]->mod_values[1]=NULL;
343         }
344       else
345         grow[nummods]->mod_values=NULL;
346
347       grow[nummods+1]=NULL;
348     }
349
350   return 1;
351 }
352
353 static void
354 build_attrs(LDAPMod ***modlist,char *line)
355 {
356   char *record;
357   int i;
358
359   /* Remove trailing whitespace */
360   for(i=strlen(line);i>0;i--)
361     if(ascii_isspace(line[i-1]))
362       line[i-1]='\0';
363     else
364       break;
365
366   if((record=strsep(&line,":"))==NULL)
367     return;
368
369   if(ks_strcasecmp("pub",record)==0)
370     {
371       char *tok;
372       int disabled=0,revoked=0;
373
374       /* The long keyid */
375       if((tok=strsep(&line,":"))==NULL)
376         return;
377
378       if(strlen(tok)==16)
379         {
380           make_one_attr(modlist,"pgpCertID",tok);
381           make_one_attr(modlist,"pgpKeyID",&tok[8]);
382         }
383       else
384         return;
385
386       /* The primary pubkey algo */
387       if((tok=strsep(&line,":"))==NULL)
388         return;
389
390       switch(atoi(tok))
391         {
392         case 1:
393           make_one_attr(modlist,"pgpKeyType","RSA");
394           break;
395
396         case 17:
397           make_one_attr(modlist,"pgpKeyType","DSS/DH");
398           break;
399         }
400
401       /* Size of primary key */
402       if((tok=strsep(&line,":"))==NULL)
403         return;
404
405       if(atoi(tok)>0)
406         {
407           char padded[6];
408           int val=atoi(tok);
409
410           /* We zero pad this on the left to make PGP happy. */
411
412           if(val<99999 && val>0)
413             {
414               sprintf(padded,"%05u",atoi(tok));
415               make_one_attr(modlist,"pgpKeySize",padded);
416             }
417         }
418
419       /* pk timestamp */
420       if((tok=strsep(&line,":"))==NULL)
421         return;
422
423       if(atoi(tok)>0)
424         {
425           char *stamp=epoch2ldaptime(atoi(tok));
426           if(stamp)
427             {
428               make_one_attr(modlist,"pgpKeyCreateTime",stamp);
429               free(stamp);
430             }
431         }
432
433       /* pk expire */
434       if((tok=strsep(&line,":"))==NULL)
435         return;
436
437       if(atoi(tok)>0)
438         {
439           char *stamp=epoch2ldaptime(atoi(tok));
440           if(stamp)
441             {
442               make_one_attr(modlist,"pgpKeyExpireTime",stamp);
443               free(stamp);
444             }
445         }
446
447       /* flags */
448       if((tok=strsep(&line,":"))==NULL)
449         return;
450
451       while(*tok)
452         switch(*tok++)
453           {
454           case 'r':
455           case 'R':
456             revoked=1;
457             break;
458             
459           case 'd':
460           case 'D':
461             disabled=1;
462             break;
463           }
464
465       /*
466         Note that we always create the pgpDisabled and pgpRevoked
467         attributes, regardless of whether the key is disabled/revoked
468         or not.  This is because a very common search is like
469         "(&(pgpUserID=*isabella*)(pgpDisabled=0))"
470       */
471
472       make_one_attr(modlist,"pgpDisabled",disabled?"1":"0");
473       make_one_attr(modlist,"pgpRevoked",revoked?"1":"0");
474     }
475   else if(ks_strcasecmp("sub",record)==0)
476     {
477       char *tok;
478
479       /* The long keyid */
480       if((tok=strsep(&line,":"))==NULL)
481         return;
482
483       if(strlen(tok)==16)
484         make_one_attr(modlist,"pgpSubKeyID",tok);
485       else
486         return;
487
488       /* The subkey algo */
489       if((tok=strsep(&line,":"))==NULL)
490         return;
491
492       /* Size of subkey */
493       if((tok=strsep(&line,":"))==NULL)
494         return;
495
496       if(atoi(tok)>0)
497         {
498           char padded[6];
499           int val=atoi(tok);
500
501           /* We zero pad this on the left to make PGP happy. */
502
503           if(val<99999 && val>0)
504             {
505               sprintf(padded,"%05u",atoi(tok));
506               make_one_attr(modlist,"pgpKeySize",padded);
507             }
508         }
509
510       /* Ignore the rest of the items for subkeys since the LDAP
511          schema doesn't store them. */
512     }
513   else if(ks_strcasecmp("uid",record)==0)
514     {
515       char *userid,*tok;
516
517       /* The user ID string */
518       if((tok=strsep(&line,":"))==NULL)
519         return;
520
521       if(strlen(tok)==0)
522         return;
523
524       userid=tok;
525
526       /* By definition, de-%-encoding is always smaller than the
527          original string so we can decode in place. */
528
529       i=0;
530
531       while(*tok)
532         if(tok[0]=='%' && tok[1] && tok[2])
533           {
534             int c;
535
536             userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c;
537             i++;
538             tok+=3;
539           }
540         else
541           userid[i++]=*tok++;
542
543       userid[i]='\0';
544
545       /* We don't care about the other info provided in the uid: line
546          since the LDAP schema doesn't need it. */
547
548       make_one_attr(modlist,"pgpUserID",userid);
549     }
550   else if(ks_strcasecmp("sig",record)==0)
551     {
552       char *tok;
553
554       if((tok=strsep(&line,":"))==NULL)
555         return;
556
557       if(strlen(tok)==16)
558         make_one_attr(modlist,"pgpSignerID",tok);
559     }
560 }
561
562 static void
563 free_mod_values(LDAPMod *mod)
564 {
565   char **ptr;
566
567   if(!mod->mod_values)
568     return;
569
570   for(ptr=mod->mod_values;*ptr;ptr++)
571     free(*ptr);
572
573   free(mod->mod_values);
574 }
575
576 static int
577 send_key(int *r_eof)
578 {
579   int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
580   char *dn=NULL,line[MAX_LINE],*key=NULL;
581   char keyid[17],state[6];
582   LDAPMod **modlist,**addlist,**ml;
583
584   modlist=malloc(sizeof(LDAPMod *));
585   if(!modlist)
586     {
587       fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
588       ret=KEYSERVER_NO_MEMORY;
589       goto fail;
590     }
591
592   *modlist=NULL;
593
594   addlist=malloc(sizeof(LDAPMod *));
595   if(!addlist)
596     {
597       fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
598       ret=KEYSERVER_NO_MEMORY;
599       goto fail;
600     }
601
602   *addlist=NULL;
603
604   /* Start by nulling out all attributes.  We try and do a modify
605      operation first, so this ensures that we don't leave old
606      attributes lying around. */
607   make_one_attr(&modlist,"pgpDisabled",NULL);
608   make_one_attr(&modlist,"pgpKeyID",NULL);
609   make_one_attr(&modlist,"pgpKeyType",NULL);
610   make_one_attr(&modlist,"pgpUserID",NULL);
611   make_one_attr(&modlist,"pgpKeyCreateTime",NULL);
612   make_one_attr(&modlist,"pgpSignerID",NULL);
613   make_one_attr(&modlist,"pgpRevoked",NULL);
614   make_one_attr(&modlist,"pgpSubKeyID",NULL);
615   make_one_attr(&modlist,"pgpKeySize",NULL);
616   make_one_attr(&modlist,"pgpKeyExpireTime",NULL);
617   make_one_attr(&modlist,"pgpCertID",NULL);
618
619   /* Assemble the INFO stuff into LDAP attributes */
620
621   while(fgets(line,MAX_LINE,input)!=NULL)
622     if(sscanf(line,"INFO%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
623        && strcmp(state,"BEGIN")==0)
624       {
625         begin=1;
626         break;
627       }
628
629   if(!begin)
630     {
631       /* i.e. eof before the INFO BEGIN was found.  This isn't an
632          error. */
633       *r_eof=1;
634       ret=KEYSERVER_OK;
635       goto fail;
636     }
637
638   if(strlen(keyid)!=16)
639     {
640       *r_eof=1;
641       ret=KEYSERVER_KEY_INCOMPLETE;
642       goto fail;
643     }
644
645   dn=malloc(strlen("pgpCertID=")+16+1+strlen(basekeyspacedn)+1);
646   if(dn==NULL)
647     {
648       fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
649       ret=KEYSERVER_NO_MEMORY;
650       goto fail;
651     }
652
653   sprintf(dn,"pgpCertID=%s,%s",keyid,basekeyspacedn);
654
655   key=malloc(1);
656   if(!key)
657     {
658       fprintf(console,"gpgkeys: unable to allocate memory for key\n");
659       ret=KEYSERVER_NO_MEMORY;
660       goto fail;
661     }
662
663   key[0]='\0';
664
665   /* Now parse each line until we see the END */
666
667   while(fgets(line,MAX_LINE,input)!=NULL)
668     if(sscanf(line,"INFO%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
669        && strcmp(state,"END")==0)
670       {
671         end=1;
672         break;
673       }
674     else
675       build_attrs(&addlist,line);
676
677   if(!end)
678     {
679       fprintf(console,"gpgkeys: no INFO %s END found\n",keyid);
680       *r_eof=1;
681       ret=KEYSERVER_KEY_INCOMPLETE;
682       goto fail;
683     }
684
685   begin=end=0;
686
687   /* Read and throw away stdin until we see the BEGIN */
688
689   while(fgets(line,MAX_LINE,input)!=NULL)
690     if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
691        && strcmp(state,"BEGIN")==0)
692       {
693         begin=1;
694         break;
695       }
696
697   if(!begin)
698     {
699       /* i.e. eof before the KEY BEGIN was found.  This isn't an
700          error. */
701       *r_eof=1;
702       ret=KEYSERVER_OK;
703       goto fail;
704     }
705
706   /* Now slurp up everything until we see the END */
707
708   while(fgets(line,MAX_LINE,input)!=NULL)
709     if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
710        && strcmp(state,"END")==0)
711       {
712         end=1;
713         break;
714       }
715     else
716       {
717         char *tempkey;
718         keysize+=strlen(line);
719         tempkey=realloc(key,keysize);
720         if(tempkey==NULL)
721           {
722             fprintf(console,"gpgkeys: unable to reallocate for key\n");
723             ret=KEYSERVER_NO_MEMORY;
724             goto fail;
725           }
726         else
727           key=tempkey;
728
729         strcat(key,line);
730       }
731
732   if(!end)
733     {
734       fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
735       *r_eof=1;
736       ret=KEYSERVER_KEY_INCOMPLETE;
737       goto fail;
738     }
739
740   make_one_attr(&addlist,"objectClass","pgpKeyInfo");
741   make_one_attr(&addlist,"pgpKey",key);
742
743   /* Now append addlist onto modlist */
744   if(!join_two_modlists(&modlist,addlist))
745     {
746       fprintf(console,"gpgkeys: unable to merge LDAP modification lists\n");
747       ret=KEYSERVER_NO_MEMORY;
748       goto fail;
749     }
750
751   /* Going on the assumption that modify operations are more frequent
752      than adds, we try a modify first.  If it's not there, we just
753      turn around and send an add command for the same key.  Otherwise,
754      the modify brings the server copy into compliance with our copy.
755      Note that unlike the LDAP keyserver (and really, any other
756      keyserver) this does NOT merge signatures, but replaces the whole
757      key.  This should make some people very happy. */
758
759   err=ldap_modify_s(ldap,dn,modlist);
760   if(err==LDAP_NO_SUCH_OBJECT)
761     err=ldap_add_s(ldap,dn,addlist);
762
763   if(err!=LDAP_SUCCESS)
764     {
765       fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
766               keyid,ldap_err2string(err));
767       ret=ldap_err_to_gpg_err(err);
768       goto fail;
769     }
770
771   ret=KEYSERVER_OK;
772
773  fail:
774   if (modlist)
775     {
776       /* Unwind and free the whole modlist structure */
777       for(ml=modlist;*ml;ml++)
778         {
779           free_mod_values(*ml);
780           free(*ml);
781         }
782       free(modlist);
783     }
784   free(addlist);
785   free(dn);
786   free(key);
787
788   if(ret!=0 && begin)
789     fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
790
791   return ret;
792 }
793
794 static int
795 send_key_keyserver(int *r_eof)
796 {
797   int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
798   char *dn=NULL,line[MAX_LINE],*key[2]={NULL,NULL};
799   char keyid[17],state[6];
800   LDAPMod mod, *attrs[2];
801
802   memset(&mod,0,sizeof(mod));
803   mod.mod_op=LDAP_MOD_ADD;
804   mod.mod_type=pgpkeystr;
805   mod.mod_values=key;
806   attrs[0]=&mod;
807   attrs[1]=NULL;
808
809   dn=malloc(strlen("pgpCertid=virtual,")+strlen(basekeyspacedn)+1);
810   if(dn==NULL)
811     {
812       fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
813       ret=KEYSERVER_NO_MEMORY;
814       goto fail;
815     }
816
817   strcpy(dn,"pgpCertid=virtual,");
818   strcat(dn,basekeyspacedn);
819
820   key[0]=malloc(1);
821   if(key[0]==NULL)
822     {
823       fprintf(console,"gpgkeys: unable to allocate memory for key\n");
824       ret=KEYSERVER_NO_MEMORY;
825       goto fail;
826     }
827
828   key[0][0]='\0';
829
830   /* Read and throw away stdin until we see the BEGIN */
831
832   while(fgets(line,MAX_LINE,input)!=NULL)
833     if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
834        && strcmp(state,"BEGIN")==0)
835       {
836         begin=1;
837         break;
838       }
839
840   if(!begin)
841     {
842       /* i.e. eof before the KEY BEGIN was found.  This isn't an
843          error. */
844       *r_eof=1;
845       ret=KEYSERVER_OK;
846       goto fail;
847     }
848
849   /* Now slurp up everything until we see the END */
850
851   while(fgets(line,MAX_LINE,input)!=NULL)
852     if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
853        && strcmp(state,"END")==0)
854       {
855         end=1;
856         break;
857       }
858     else
859       {
860         keysize+=strlen(line);
861         key[0]=realloc(key[0],keysize);
862         if(key[0]==NULL)
863           {
864             fprintf(console,"gpgkeys: unable to reallocate for key\n");
865             ret=KEYSERVER_NO_MEMORY;
866             goto fail;
867           }
868
869         strcat(key[0],line);
870       }
871
872   if(!end)
873     {
874       fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
875       *r_eof=1;
876       ret=KEYSERVER_KEY_INCOMPLETE;
877       goto fail;
878     }
879
880   err=ldap_add_s(ldap,dn,attrs);
881   if(err!=LDAP_SUCCESS)
882     {
883       fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
884               keyid,ldap_err2string(err));
885       ret=ldap_err_to_gpg_err(err);
886       goto fail;
887     }
888
889   ret=KEYSERVER_OK;
890
891  fail:
892
893   free(key[0]);
894   free(dn);
895
896   if(ret!=0 && begin)
897     fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
898
899   /* Not a fatal error */
900   if(ret==KEYSERVER_KEY_EXISTS)
901     ret=KEYSERVER_OK;
902
903   return ret;
904 }
905
906 static void
907 build_info(const char *certid,LDAPMessage *each)
908 {
909   char **vals;
910
911   fprintf(output,"INFO %s BEGIN\n",certid);
912
913   fprintf(output,"pub:%s:",certid);
914
915   vals=ldap_get_values(ldap,each,"pgpkeytype");
916   if(vals!=NULL)
917     {
918       if(strcmp(vals[0],"RSA")==0)
919         fprintf(output,"1");
920       else if(strcmp(vals[0],"DSS/DH")==0)
921         fprintf(output,"17");
922       ldap_value_free(vals);
923     }
924
925   fprintf(output,":");
926
927   vals=ldap_get_values(ldap,each,"pgpkeysize");
928   if(vals!=NULL)
929     {
930       if(atoi(vals[0])>0)
931         fprintf(output,"%d",atoi(vals[0]));
932       ldap_value_free(vals);
933     }
934
935   fprintf(output,":");
936
937   vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
938   if(vals!=NULL)
939     {
940       if(strlen(vals[0])==15)
941         fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
942       ldap_value_free(vals);
943     }
944
945   fprintf(output,":");
946
947   vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
948   if(vals!=NULL)
949     {
950       if(strlen(vals[0])==15)
951         fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
952       ldap_value_free(vals);
953     }
954
955   fprintf(output,":");
956
957   vals=ldap_get_values(ldap,each,"pgprevoked");
958   if(vals!=NULL)
959     {
960       if(atoi(vals[0])==1)
961         fprintf(output,"r");
962       ldap_value_free(vals);
963     }
964
965   fprintf(output,"\n");
966
967   vals=ldap_get_values(ldap,each,"pgpuserid");
968   if(vals!=NULL)
969     {
970       int i;
971
972       for(i=0;vals[i];i++)
973         fprintf(output,"uid:%s\n",vals[i]);
974       ldap_value_free(vals);
975     }
976
977   fprintf(output,"INFO %s END\n",certid);
978 }
979
980 /* Note that key-not-found is not a fatal error */
981 static int
982 get_key(char *getkey)
983 {
984   LDAPMessage *res,*each;
985   int ret=KEYSERVER_INTERNAL_ERROR,err,count;
986   struct keylist *dupelist=NULL;
987   char search[62];
988   /* This ordering is significant - specifically, "pgpcertid" needs to
989      be the second item in the list, since everything after it may be
990      discarded if the user isn't in verbose mode. */
991   char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
992                  "pgpdisabled","pgpkeycreatetime","modifytimestamp",
993                  "pgpkeysize","pgpkeytype",NULL};
994   attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
995                          array initializers. */
996
997   /* Build the search string */
998
999   /* GPG can send us a v4 fingerprint, a v3 or v4 long key id, or a v3
1000      or v4 short key id */
1001
1002   if(strncmp(getkey,"0x",2)==0)
1003     getkey+=2;
1004
1005   if(strlen(getkey)==32)
1006     {
1007       fprintf(console,
1008               "gpgkeys: LDAP keyservers do not support v3 fingerprints\n");
1009       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1010       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_NOT_SUPPORTED);
1011       return KEYSERVER_NOT_SUPPORTED;
1012     }
1013
1014   if(strlen(getkey)>16)
1015     {
1016       char *offset=&getkey[strlen(getkey)-16];
1017
1018       /* fingerprint.  Take the last 16 characters and treat it like a
1019          long key id */
1020
1021       if(opt->flags.include_subkeys)
1022         sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1023                 offset,offset);
1024       else
1025         sprintf(search,"(pgpcertid=%.16s)",offset);
1026     }
1027   else if(strlen(getkey)>8)
1028     {
1029       /* long key id */
1030
1031       if(opt->flags.include_subkeys)
1032         sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1033                 getkey,getkey);
1034       else
1035         sprintf(search,"(pgpcertid=%.16s)",getkey);
1036     }
1037   else
1038     {
1039       /* short key id */
1040     
1041       sprintf(search,"(pgpkeyid=%.8s)",getkey);
1042     }
1043
1044   if(opt->verbose>2)
1045     fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1046
1047   if(!opt->verbose)
1048     attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1049
1050   err=ldap_search_s(ldap,basekeyspacedn,
1051                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1052   if(err!=0)
1053     {
1054       int errtag=ldap_err_to_gpg_err(err);
1055
1056       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1057       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1058       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1059       return errtag;
1060     }
1061
1062   count=ldap_count_entries(ldap,res);
1063   if(count<1)
1064     {
1065       fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1066       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1067       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1068     }
1069   else
1070     {
1071       /* There may be more than one unique result for a given keyID,
1072          so we should fetch them all (test this by fetching short key
1073          id 0xDEADBEEF). */
1074
1075       each=ldap_first_entry(ldap,res);
1076       while(each!=NULL)
1077         {
1078           char **vals,**certid;
1079
1080           /* Use the long keyid to remove duplicates.  The LDAP server
1081              returns the same keyid more than once if there are
1082              multiple user IDs on the key.  Note that this does NOT
1083              mean that a keyid that exists multiple times on the
1084              keyserver will not be fetched.  It means that each KEY,
1085              no matter how many user IDs share its keyid, will be
1086              fetched only once.  If a keyid that belongs to more than
1087              one key is fetched, the server quite properly responds
1088              with all matching keys. -ds */
1089
1090           certid=ldap_get_values(ldap,each,"pgpcertid");
1091           if(certid!=NULL)
1092             {
1093               if(!key_in_keylist(certid[0],dupelist))
1094                 {
1095                   /* it's not a duplicate, so add it */
1096
1097                   int rc=add_key_to_keylist(certid[0],&dupelist);
1098                   if(rc)
1099                     {
1100                       ret=rc;
1101                       goto fail;
1102                     }
1103
1104                   build_info(certid[0],each);
1105
1106                   fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1107
1108                   vals=ldap_get_values(ldap,each,pgpkeystr);
1109                   if(vals==NULL)
1110                     {
1111                       int errtag=ldap_to_gpg_err(ldap);
1112
1113                       fprintf(console,"gpgkeys: unable to retrieve key %s "
1114                               "from keyserver\n",getkey);
1115                       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1116                     }
1117                   else
1118                     {
1119                       print_nocr(output,vals[0]);
1120                       fprintf(output,"\nKEY 0x%s END\n",getkey);
1121
1122                       ldap_value_free(vals);
1123                     }
1124                 }
1125
1126               ldap_value_free(certid);
1127             }
1128
1129           each=ldap_next_entry(ldap,each);
1130         }
1131     }
1132
1133   ret=KEYSERVER_OK;
1134
1135  fail:
1136   ldap_msgfree(res);
1137   free_keylist(dupelist);
1138
1139   return ret;
1140 }
1141
1142 #define LDAP_ESCAPE_CHARS "*()\\"
1143
1144 /* Append string to buffer in a LDAP-quoted way */
1145 static void
1146 ldap_quote(char *buffer,const char *string)
1147 {
1148   /* Find the end of buffer */
1149   buffer+=strlen(buffer);
1150
1151   for(;*string;string++)
1152     {
1153       if(strchr(LDAP_ESCAPE_CHARS,*string))
1154         {
1155           sprintf(buffer,"\\%02X",*string);
1156           buffer+=3;
1157         }
1158       else
1159         *buffer++=*string;
1160     }
1161
1162   *buffer='\0';
1163 }
1164
1165 /* Note that key-not-found is not a fatal error */
1166 static int
1167 get_name(char *getkey)
1168 {
1169   LDAPMessage *res,*each;
1170   int ret=KEYSERVER_INTERNAL_ERROR,err,count;
1171   /* The maximum size of the search, including the optional stuff and
1172      the trailing \0 */
1173   char search[2+12+(MAX_LINE*3)+2+15+14+1+1+20];
1174   /* This ordering is significant - specifically, "pgpcertid" needs to
1175      be the second item in the list, since everything after it may be
1176      discarded if the user isn't in verbose mode. */
1177   char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
1178                  "pgpdisabled","pgpkeycreatetime","modifytimestamp",
1179                  "pgpkeysize","pgpkeytype",NULL};
1180   attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1181                          array initializers. */
1182
1183   /* Build the search string */
1184
1185   search[0]='\0';
1186
1187   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1188     strcat(search,"(&");
1189
1190   strcat(search,"(pgpUserID=*");
1191   ldap_quote(search,getkey);
1192   strcat(search,"*)");
1193
1194   if(!opt->flags.include_disabled)
1195     strcat(search,"(pgpDisabled=0)");
1196
1197   if(!opt->flags.include_revoked)
1198     strcat(search,"(pgpRevoked=0)");
1199
1200   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1201     strcat(search,")");
1202
1203   if(opt->verbose>2)
1204     fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1205
1206   if(!opt->verbose)
1207     attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1208
1209   err=ldap_search_s(ldap,basekeyspacedn,
1210                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1211   if(err!=0)
1212     {
1213       int errtag=ldap_err_to_gpg_err(err);
1214
1215       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1216       fprintf(output,"NAME %s BEGIN\n",getkey);
1217       fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1218       return errtag;
1219     }
1220
1221   count=ldap_count_entries(ldap,res);
1222   if(count<1)
1223     {
1224       fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1225       fprintf(output,"NAME %s BEGIN\n",getkey);
1226       fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1227     }
1228   else
1229     {
1230       /* There may be more than one result, but we return them all. */
1231
1232       each=ldap_first_entry(ldap,res);
1233       while(each!=NULL)
1234         {
1235           char **vals,**certid;
1236
1237           certid=ldap_get_values(ldap,each,"pgpcertid");
1238           if(certid!=NULL)
1239             {
1240               build_info(certid[0],each);
1241
1242               fprintf(output,"NAME %s BEGIN\n",getkey);
1243
1244               vals=ldap_get_values(ldap,each,pgpkeystr);
1245               if(vals==NULL)
1246                 {
1247                   int errtag=ldap_to_gpg_err(ldap);
1248
1249                   fprintf(console,"gpgkeys: unable to retrieve key %s "
1250                           "from keyserver\n",getkey);
1251                   fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1252                 }
1253               else
1254                 {
1255                   print_nocr(output,vals[0]);
1256                   fprintf(output,"\nNAME %s END\n",getkey);
1257
1258                   ldap_value_free(vals);
1259                 }
1260
1261               ldap_value_free(certid);
1262             }
1263
1264           each=ldap_next_entry(ldap,each);
1265         }
1266     }
1267
1268   ret=KEYSERVER_OK;
1269
1270   ldap_msgfree(res);
1271
1272   return ret;
1273 }
1274
1275 static void
1276 printquoted(FILE *stream,char *string,char delim)
1277 {
1278   while(*string)
1279     {
1280       if(*string==delim || *string=='%')
1281         fprintf(stream,"%%%02x",*string);
1282       else
1283         fputc(*string,stream);
1284
1285       string++;
1286     }
1287 }
1288
1289 /* Returns 0 on success and -1 on error.  Note that key-not-found is
1290    not an error! */
1291 static int
1292 search_key(const char *searchkey)
1293 {
1294   char **vals,*search;
1295   LDAPMessage *res,*each;
1296   int err,count=0;
1297   struct keylist *dupelist=NULL;
1298   /* The maximum size of the search, including the optional stuff and
1299      the trailing \0 */
1300   char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1301                  "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1302                  "pgpkeysize","pgpkeytype",NULL};
1303   enum ks_search_type search_type;
1304
1305   search=malloc(2+1+9+1+3+strlen(searchkey)+3+1+15+14+1+1+20);
1306   if(!search)
1307     {
1308       fprintf(console,"gpgkeys: out of memory when building search list\n");
1309       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,KEYSERVER_NO_MEMORY);
1310       return KEYSERVER_NO_MEMORY;
1311     }
1312
1313   fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1314
1315   search_type=classify_ks_search(&searchkey);
1316
1317   if(opt->debug)
1318     fprintf(console,"search type is %d, and key is \"%s\"\n",
1319             search_type,searchkey);
1320
1321   /* Build the search string */
1322
1323   search[0]='\0';
1324
1325   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1326     strcat(search,"(&");
1327
1328   strcat(search,"(");
1329
1330   switch(search_type)
1331     {
1332     case KS_SEARCH_KEYID_SHORT:
1333       strcat(search,"pgpKeyID");
1334       break;
1335
1336     case KS_SEARCH_KEYID_LONG:
1337       strcat(search,"pgpCertID");
1338       break;
1339
1340     default:
1341       strcat(search,"pgpUserID");
1342       break;
1343     }
1344
1345   strcat(search,"=");
1346
1347   switch(search_type)
1348     {
1349     case KS_SEARCH_SUBSTR:
1350       strcat(search,"*");
1351       break;
1352
1353     case KS_SEARCH_MAIL:
1354       strcat(search,"*<");
1355       break;
1356
1357     case KS_SEARCH_MAILSUB:
1358       strcat(search,"*<*");
1359       break;
1360
1361     case KS_SEARCH_EXACT:
1362     case KS_SEARCH_KEYID_LONG:
1363     case KS_SEARCH_KEYID_SHORT:
1364       break;
1365     }
1366
1367   strcat(search,searchkey);
1368
1369   switch(search_type)
1370     {
1371     case KS_SEARCH_SUBSTR:
1372       strcat(search,"*");
1373       break;
1374
1375     case KS_SEARCH_MAIL:
1376       strcat(search,">*");
1377       break;
1378
1379     case KS_SEARCH_MAILSUB:
1380       strcat(search,"*>*");
1381       break;
1382
1383     case KS_SEARCH_EXACT:
1384     case KS_SEARCH_KEYID_LONG:
1385     case KS_SEARCH_KEYID_SHORT:
1386       break;
1387     }
1388
1389   strcat(search,")");
1390
1391   if(!opt->flags.include_disabled)
1392     strcat(search,"(pgpDisabled=0)");
1393
1394   if(!opt->flags.include_revoked)
1395     strcat(search,"(pgpRevoked=0)");
1396
1397   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1398     strcat(search,")");
1399
1400   if(opt->verbose>2)
1401     fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1402
1403   err=ldap_search_s(ldap,basekeyspacedn,
1404                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1405   free(search);
1406   if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1407     {
1408       int errtag=ldap_err_to_gpg_err(err);
1409
1410       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1411       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1412       return errtag;
1413     }
1414
1415   /* The LDAP server doesn't return a real count of unique keys, so we
1416      can't use ldap_count_entries here. */
1417   each=ldap_first_entry(ldap,res);
1418   while(each!=NULL)
1419     {
1420       char **certid=ldap_get_values(ldap,each,"pgpcertid");
1421
1422       if(certid!=NULL)
1423         {
1424           if(!key_in_keylist(certid[0],dupelist))
1425             {
1426               int rc=add_key_to_keylist(certid[0],&dupelist);
1427               if(rc!=0)
1428                 {
1429                   fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1430                   free_keylist(dupelist);
1431                   return rc;
1432                 }
1433
1434               count++;
1435             }
1436         }
1437
1438       each=ldap_next_entry(ldap,each);
1439     }
1440
1441   if(err==LDAP_SIZELIMIT_EXCEEDED)
1442     {
1443       if(count==1)
1444         fprintf(console,"gpgkeys: search results exceeded server limit."
1445                 "  First %d result shown.\n",count);
1446       else
1447         fprintf(console,"gpgkeys: search results exceeded server limit."
1448                 "  First %d results shown.\n",count);
1449     }
1450
1451   free_keylist(dupelist);
1452   dupelist=NULL;
1453
1454   if(count<1)
1455     fprintf(output,"info:1:0\n");
1456   else
1457     {
1458       fprintf(output,"info:1:%d\n",count);
1459
1460       each=ldap_first_entry(ldap,res);
1461       while(each!=NULL)
1462         {
1463           char **certid;
1464
1465           certid=ldap_get_values(ldap,each,"pgpcertid");
1466           if(certid!=NULL)
1467             {
1468               LDAPMessage *uids;
1469
1470               /* Have we seen this certid before? */
1471               if(!key_in_keylist(certid[0],dupelist))
1472                 {
1473                   int rc=add_key_to_keylist(certid[0],&dupelist);
1474                   if(rc)
1475                     {
1476                       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1477                       free_keylist(dupelist);
1478                       ldap_value_free(certid);
1479                       ldap_msgfree(res);
1480                       return rc;
1481                     }
1482
1483                   fprintf(output,"pub:%s:",certid[0]);
1484
1485                   vals=ldap_get_values(ldap,each,"pgpkeytype");
1486                   if(vals!=NULL)
1487                     {
1488                       /* The LDAP server doesn't exactly handle this
1489                          well. */
1490                       if(strcasecmp(vals[0],"RSA")==0)
1491                         fprintf(output,"1");
1492                       else if(strcasecmp(vals[0],"DSS/DH")==0)
1493                         fprintf(output,"17");
1494                       ldap_value_free(vals);
1495                     }
1496
1497                   fputc(':',output);
1498
1499                   vals=ldap_get_values(ldap,each,"pgpkeysize");
1500                   if(vals!=NULL)
1501                     {
1502                       /* Not sure why, but some keys are listed with a
1503                          key size of 0.  Treat that like an
1504                          unknown. */
1505                       if(atoi(vals[0])>0)
1506                         fprintf(output,"%d",atoi(vals[0]));
1507                       ldap_value_free(vals);
1508                     }
1509
1510                   fputc(':',output);
1511
1512                   /* YYYYMMDDHHmmssZ */
1513
1514                   vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1515                   if(vals!=NULL && strlen(vals[0])==15)
1516                     {
1517                       fprintf(output,"%u",
1518                               (unsigned int)ldap2epochtime(vals[0]));
1519                       ldap_value_free(vals);
1520                     }
1521
1522                   fputc(':',output);
1523
1524                   vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
1525                   if(vals!=NULL && strlen(vals[0])==15)
1526                     {
1527                       fprintf(output,"%u",
1528                               (unsigned int)ldap2epochtime(vals[0]));
1529                       ldap_value_free(vals);
1530                     }
1531
1532                   fputc(':',output);
1533
1534                   vals=ldap_get_values(ldap,each,"pgprevoked");
1535                   if(vals!=NULL)
1536                     {
1537                       if(atoi(vals[0])==1)
1538                         fprintf(output,"r");
1539                       ldap_value_free(vals);
1540                     }
1541
1542                   vals=ldap_get_values(ldap,each,"pgpdisabled");
1543                   if(vals!=NULL)
1544                     {
1545                       if(atoi(vals[0])==1)
1546                         fprintf(output,"d");
1547                       ldap_value_free(vals);
1548                     }
1549
1550 #if 0
1551                   /* This is not yet specified in the keyserver
1552                      protocol, but may be someday. */
1553                   fputc(':',output);
1554
1555                   vals=ldap_get_values(ldap,each,"modifytimestamp");
1556                   if(vals!=NULL && strlen(vals[0])==15)
1557                     {
1558                       fprintf(output,"%u",
1559                               (unsigned int)ldap2epochtime(vals[0]));
1560                       ldap_value_free(vals);
1561                     }
1562 #endif
1563
1564                   fprintf(output,"\n");
1565
1566                   /* Now print all the uids that have this certid */
1567                   uids=ldap_first_entry(ldap,res);
1568                   while(uids!=NULL)
1569                     {
1570                       vals=ldap_get_values(ldap,uids,"pgpcertid");
1571                       if(vals!=NULL)
1572                         {
1573                           if(strcasecmp(certid[0],vals[0])==0)
1574                             {
1575                               char **uidvals;
1576
1577                               fprintf(output,"uid:");
1578
1579                               uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1580                               if(uidvals!=NULL)
1581                                 {
1582                                   /* Need to escape any colons */
1583                                   printquoted(output,uidvals[0],':');
1584                                   ldap_value_free(uidvals);
1585                                 }
1586
1587                               fprintf(output,"\n");
1588                             }
1589
1590                           ldap_value_free(vals);
1591                         }
1592
1593                       uids=ldap_next_entry(ldap,uids);
1594                     }
1595                 }
1596
1597               ldap_value_free(certid);
1598             }
1599
1600           each=ldap_next_entry(ldap,each);
1601         }
1602     }
1603
1604   ldap_msgfree(res);
1605   free_keylist(dupelist);
1606
1607   fprintf(output,"SEARCH %s END\n",searchkey);
1608
1609   return KEYSERVER_OK;
1610 }
1611
1612 static void
1613 fail_all(struct keylist *keylist,int err)
1614 {
1615   if(!keylist)
1616     return;
1617
1618   if(opt->action==KS_SEARCH)
1619     {
1620       fprintf(output,"SEARCH ");
1621       while(keylist)
1622         {
1623           fprintf(output,"%s ",keylist->str);
1624           keylist=keylist->next;
1625         }
1626       fprintf(output,"FAILED %d\n",err);
1627     }
1628   else
1629     while(keylist)
1630       {
1631         fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1632         keylist=keylist->next;
1633       }
1634 }
1635
1636 static int
1637 find_basekeyspacedn(void)
1638 {
1639   int err,i;
1640   char *attr[]={"namingContexts",NULL,NULL,NULL};
1641   LDAPMessage *res;
1642   char **context;
1643
1644   /* Look for namingContexts */
1645   err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1646   if(err==LDAP_SUCCESS)
1647     {
1648       context=ldap_get_values(ldap,res,"namingContexts");
1649       if(context)
1650         {
1651           attr[0]="pgpBaseKeySpaceDN";
1652           attr[1]="pgpVersion";
1653           attr[2]="pgpSoftware";
1654
1655           real_ldap=1;
1656
1657           /* We found some, so try each namingContext as the search base
1658              and look for pgpBaseKeySpaceDN.  Because we found this, we
1659              know we're talking to a regular-ish LDAP server and not a
1660              LDAP keyserver. */
1661
1662           for(i=0;context[i] && !basekeyspacedn;i++)
1663             {
1664               char **vals;
1665               LDAPMessage *si_res;
1666               char *object;
1667
1668               object=malloc(17+strlen(context[i])+1);
1669               if(!object)
1670                 return -1;
1671
1672               strcpy(object,"cn=pgpServerInfo,");
1673               strcat(object,context[i]);
1674
1675               err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1676                                 "(objectClass=*)",attr,0,&si_res);
1677               free(object);
1678
1679               if(err==LDAP_NO_SUCH_OBJECT)
1680                 continue;
1681               else if(err!=LDAP_SUCCESS)
1682                 return err;
1683
1684               vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1685               if(vals)
1686                 {
1687                   basekeyspacedn=strdup(vals[0]);
1688                   ldap_value_free(vals);
1689                 }
1690
1691               if(opt->verbose>1)
1692                 {
1693                   vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1694                   if(vals)
1695                     {
1696                       fprintf(console,"Server: \t%s\n",vals[0]);
1697                       ldap_value_free(vals);
1698                     }
1699
1700                   vals=ldap_get_values(ldap,si_res,"pgpVersion");
1701                   if(vals)
1702                     {
1703                       fprintf(console,"Version:\t%s\n",vals[0]);
1704                       ldap_value_free(vals);
1705                     }
1706                 }
1707
1708               ldap_msgfree(si_res);
1709             }
1710
1711           ldap_value_free(context);
1712         }
1713
1714       ldap_msgfree(res);
1715     }
1716   else
1717     {
1718       /* We don't have an answer yet, which means the server might be
1719          a LDAP keyserver. */
1720       char **vals;
1721       LDAPMessage *si_res;
1722
1723       attr[0]="pgpBaseKeySpaceDN";
1724       attr[1]="version";
1725       attr[2]="software";
1726
1727       err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1728                         "(objectClass=*)",attr,0,&si_res);
1729       if(err!=LDAP_SUCCESS)
1730         return err;
1731
1732       /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1733          KEYSPACE,C=US", but it might not be in the future. */
1734
1735       vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1736       if(vals)
1737         {
1738           basekeyspacedn=strdup(vals[0]);
1739           ldap_value_free(vals);
1740         }
1741
1742       if(opt->verbose>1)
1743         {
1744           vals=ldap_get_values(ldap,si_res,"software");
1745           if(vals)
1746             {
1747               fprintf(console,"Server: \t%s\n",vals[0]);
1748               ldap_value_free(vals);
1749             }
1750         }
1751
1752       vals=ldap_get_values(ldap,si_res,"version");
1753       if(vals)
1754         {
1755           if(opt->verbose>1)
1756             fprintf(console,"Version:\t%s\n",vals[0]);
1757
1758           /* If the version is high enough, use the new pgpKeyV2
1759              attribute.  This design if iffy at best, but it matches how
1760              PGP does it.  I figure the NAI folks assumed that there would
1761              never be a LDAP keyserver vendor with a different numbering
1762              scheme. */
1763           if(atoi(vals[0])>1)
1764             pgpkeystr="pgpKeyV2";
1765
1766           ldap_value_free(vals);
1767         }
1768
1769       ldap_msgfree(si_res);
1770     }   
1771
1772   return LDAP_SUCCESS;
1773 }
1774
1775 static void 
1776 show_help (FILE *fp)
1777 {
1778   fprintf (fp,"-h, --help\thelp\n");
1779   fprintf (fp,"-V\t\tmachine readable version\n");
1780   fprintf (fp,"--version\thuman readable version\n");
1781   fprintf (fp,"-o\t\toutput to this file\n");
1782 }
1783
1784 int
1785 main(int argc,char *argv[])
1786 {
1787   int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1788   char line[MAX_LINE],*binddn=NULL,*bindpw=NULL;
1789   int failed=0,use_ssl=0,use_tls=0,bound=0;
1790   struct keylist *keylist=NULL,*keyptr=NULL;
1791
1792   console=stderr;
1793
1794   /* Kludge to implement standard GNU options.  */
1795   if (argc > 1 && !strcmp (argv[1], "--version"))
1796     {
1797       fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1798       return 0;
1799     }
1800   else if (argc > 1 && !strcmp (argv[1], "--help"))
1801     {
1802       show_help (stdout);
1803       return 0;
1804     }
1805
1806   while((arg=getopt(argc,argv,"hVo:"))!=-1)
1807     switch(arg)
1808       {
1809       default:
1810       case 'h':
1811         show_help (console);
1812         return KEYSERVER_OK;
1813
1814       case 'V':
1815         fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1816         return KEYSERVER_OK;
1817
1818       case 'o':
1819         output=fopen(optarg,"w");
1820         if(output==NULL)
1821           {
1822             fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1823                     optarg,strerror(errno));
1824             return KEYSERVER_INTERNAL_ERROR;
1825           }
1826
1827         break;
1828       }
1829
1830   if(argc>optind)
1831     {
1832       input=fopen(argv[optind],"r");
1833       if(input==NULL)
1834         {
1835           fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1836                   argv[optind],strerror(errno));
1837           return KEYSERVER_INTERNAL_ERROR;
1838         }
1839     }
1840
1841   if(input==NULL)
1842     input=stdin;
1843
1844   if(output==NULL)
1845     output=stdout;
1846
1847   opt=init_ks_options();
1848   if(!opt)
1849     return KEYSERVER_NO_MEMORY;
1850
1851   /* Get the command and info block */
1852
1853   while(fgets(line,MAX_LINE,input)!=NULL)
1854     {
1855       char optionstr[MAX_OPTION+1];
1856
1857       if(line[0]=='\n')
1858         break;
1859
1860       err=parse_ks_options(line,opt);
1861       if(err>0)
1862         {
1863           ret=err;
1864           goto fail;
1865         }
1866       else if(err==0)
1867         continue;
1868
1869       if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1870         {
1871           int no=0;
1872           char *start=&optionstr[0];
1873
1874           optionstr[MAX_OPTION]='\0';
1875
1876           if(strncasecmp(optionstr,"no-",3)==0)
1877             {
1878               no=1;
1879               start=&optionstr[3];
1880             }
1881
1882           if(strncasecmp(start,"tls",3)==0)
1883             {
1884               if(no)
1885                 use_tls=0;
1886               else if(start[3]=='=')
1887                 {
1888                   if(strcasecmp(&start[4],"no")==0)
1889                     use_tls=0;
1890                   else if(strcasecmp(&start[4],"try")==0)
1891                     use_tls=1;
1892                   else if(strcasecmp(&start[4],"warn")==0)
1893                     use_tls=2;
1894                   else if(strcasecmp(&start[4],"require")==0)
1895                     use_tls=3;
1896                   else
1897                     use_tls=1;
1898                 }
1899               else if(start[3]=='\0')
1900                 use_tls=1;
1901             }
1902           else if(strncasecmp(start,"basedn",6)==0)
1903             {
1904               if(no)
1905                 {
1906                   free(basekeyspacedn);
1907                   basekeyspacedn=NULL;
1908                 }
1909               else if(start[6]=='=')
1910                 {
1911                   free(basekeyspacedn);
1912                   basekeyspacedn=strdup(&start[7]);
1913                   if(!basekeyspacedn)
1914                     {
1915                       fprintf(console,"gpgkeys: out of memory while creating "
1916                               "base DN\n");
1917                       ret=KEYSERVER_NO_MEMORY;
1918                       goto fail;
1919                     }
1920
1921                   real_ldap=1;
1922                 }
1923             }
1924           else if(strncasecmp(start,"binddn",6)==0)
1925             {
1926               if(no)
1927                 {
1928                   free(binddn);
1929                   binddn=NULL;
1930                 }
1931               else if(start[6]=='=')
1932                 {
1933                   free(binddn);
1934                   binddn=strdup(&start[7]);
1935                   if(!binddn)
1936                     {
1937                       fprintf(console,"gpgkeys: out of memory while creating "
1938                               "bind DN\n");
1939                       ret=KEYSERVER_NO_MEMORY;
1940                       goto fail;
1941                     }
1942
1943                   real_ldap=1;
1944                 }
1945             }
1946           else if(strncasecmp(start,"bindpw",6)==0)
1947             {
1948               if(no)
1949                 {
1950                   free(bindpw);
1951                   bindpw=NULL;
1952                 }
1953               else if(start[6]=='=')
1954                 {
1955                   free(bindpw);
1956                   bindpw=strdup(&start[7]);
1957                   if(!bindpw)
1958                     {
1959                       fprintf(console,"gpgkeys: out of memory while creating "
1960                               "bind password\n");
1961                       ret=KEYSERVER_NO_MEMORY;
1962                       goto fail;
1963                     }
1964
1965                   real_ldap=1;
1966                 }
1967             }
1968
1969           continue;
1970         }
1971     }
1972
1973   if(!opt->scheme)
1974     {
1975       fprintf(console,"gpgkeys: no scheme supplied!\n");
1976       ret=KEYSERVER_SCHEME_NOT_FOUND;
1977       goto fail;
1978     }
1979
1980   if(strcasecmp(opt->scheme,"ldaps")==0)
1981     {
1982       port=636;
1983       use_ssl=1;
1984     }
1985
1986   if(opt->port)
1987     port=atoi(opt->port);
1988
1989   if(!opt->host)
1990     {
1991       fprintf(console,"gpgkeys: no keyserver host provided\n");
1992       goto fail;
1993     }
1994
1995   if(opt->timeout && register_timeout()==-1)
1996     {
1997       fprintf(console,"gpgkeys: unable to register timeout handler\n");
1998       return KEYSERVER_INTERNAL_ERROR;
1999     }
2000
2001 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
2002
2003   if(opt->ca_cert_file)
2004     {
2005       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
2006       if(err!=LDAP_SUCCESS)
2007         {
2008           fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
2009                   ldap_err2string(err));
2010           ret=KEYSERVER_INTERNAL_ERROR;
2011           goto fail;
2012         }
2013     }
2014 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
2015
2016   /* SSL trumps TLS */
2017   if(use_ssl)
2018     use_tls=0;
2019
2020   /* If it's a GET or a SEARCH, the next thing to come in is the
2021      keyids.  If it's a SEND, then there are no keyids. */
2022
2023   if(opt->action==KS_SEND)
2024     while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
2025   else if(opt->action==KS_GET
2026           || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
2027     {
2028       for(;;)
2029         {
2030           struct keylist *work;
2031
2032           if(fgets(line,MAX_LINE,input)==NULL)
2033             break;
2034           else
2035             {
2036               if(line[0]=='\n' || line[0]=='\0')
2037                 break;
2038
2039               work=malloc(sizeof(struct keylist));
2040               if(work==NULL)
2041                 {
2042                   fprintf(console,"gpgkeys: out of memory while "
2043                           "building key list\n");
2044                   ret=KEYSERVER_NO_MEMORY;
2045                   goto fail;
2046                 }
2047
2048               strcpy(work->str,line);
2049
2050               /* Trim the trailing \n */
2051               work->str[strlen(line)-1]='\0';
2052
2053               work->next=NULL;
2054
2055               /* Always attach at the end to keep the list in proper
2056                  order for searching */
2057               if(keylist==NULL)
2058                 keylist=work;
2059               else
2060                 keyptr->next=work;
2061
2062               keyptr=work;
2063             }
2064         }
2065     }
2066   else
2067     {
2068       fprintf(console,"gpgkeys: no keyserver command specified\n");
2069       goto fail;
2070     }
2071
2072   /* Send the response */
2073
2074   fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
2075   fprintf(output,"PROGRAM %s\n\n",VERSION);
2076
2077   if(opt->verbose>1)
2078     {
2079       fprintf(console,"Host:\t\t%s\n",opt->host);
2080       if(port)
2081         fprintf(console,"Port:\t\t%d\n",port);
2082       fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
2083     }
2084
2085   if(opt->debug)
2086     {
2087 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
2088       err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
2089       if(err!=LDAP_SUCCESS)
2090         fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
2091                 ldap_err2string(err));
2092       else
2093         fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
2094 #else
2095       fprintf(console,"gpgkeys: not built with debugging support\n");
2096 #endif
2097     }
2098
2099   /* We have a timeout set for the setup stuff since it could time out
2100      as well. */
2101   set_timeout(opt->timeout);
2102
2103   /* Note that this tries all A records on a given host (or at least,
2104      OpenLDAP does). */
2105   ldap=ldap_init(opt->host,port);
2106   if(ldap==NULL)
2107     {
2108       fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
2109               strerror(errno));
2110       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2111       goto fail;
2112     }
2113
2114   if(use_ssl)
2115     {
2116 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
2117       int ssl=LDAP_OPT_X_TLS_HARD;
2118
2119       err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
2120       if(err!=LDAP_SUCCESS)
2121         {
2122           fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2123                   ldap_err2string(err));
2124           fail_all(keylist,ldap_err_to_gpg_err(err));
2125           goto fail;
2126         }
2127
2128       if(!opt->flags.check_cert)
2129         ssl=LDAP_OPT_X_TLS_NEVER;
2130
2131       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
2132       if(err!=LDAP_SUCCESS)
2133         {
2134           fprintf(console,
2135                   "gpgkeys: unable to set certificate validation: %s\n",
2136                   ldap_err2string(err));
2137           fail_all(keylist,ldap_err_to_gpg_err(err));
2138           goto fail;
2139         }
2140 #else
2141       fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2142               "not built with LDAPS support");
2143       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2144       goto fail;
2145 #endif
2146     }
2147
2148   if(!basekeyspacedn)
2149     if((err=find_basekeyspacedn()) || !basekeyspacedn)
2150       {
2151         fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
2152                 err?ldap_err2string(err):"not found");
2153         fail_all(keylist,ldap_err_to_gpg_err(err));
2154         goto fail;
2155       }
2156
2157   /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
2158      3=force use. */
2159   if(use_tls)
2160     {
2161       if(!real_ldap)
2162         {
2163           if(use_tls>=2)
2164             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2165                     "not supported by the NAI LDAP keyserver");
2166           if(use_tls==3)
2167             {
2168               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2169               goto fail;
2170             }
2171         }
2172       else
2173         {
2174 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
2175           int ver=LDAP_VERSION3;
2176
2177           err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2178
2179 #ifdef LDAP_OPT_X_TLS
2180           if(err==LDAP_SUCCESS)
2181             {
2182               if(opt->flags.check_cert)
2183                 ver=LDAP_OPT_X_TLS_HARD;
2184               else
2185                 ver=LDAP_OPT_X_TLS_NEVER;
2186
2187               err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
2188             }
2189 #endif
2190
2191           if(err==LDAP_SUCCESS)
2192             err=ldap_start_tls_s(ldap,NULL,NULL);
2193
2194           if(err!=LDAP_SUCCESS)
2195             {
2196               if(use_tls>=2 || opt->verbose>2)
2197                 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2198                         ldap_err2string(err));
2199               /* Are we forcing it? */
2200               if(use_tls==3)
2201                 {
2202                   fail_all(keylist,ldap_err_to_gpg_err(err));
2203                   goto fail;
2204                 }
2205             }
2206           else if(opt->verbose>1)
2207             fprintf(console,"gpgkeys: TLS started successfully.\n");
2208 #else
2209           if(use_tls>=2)
2210             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2211                     "not built with TLS support");
2212           if(use_tls==3)
2213             {
2214               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2215               goto fail;
2216             }
2217 #endif
2218         }
2219     }
2220
2221   /* By default we don't bind as there is usually no need to.  For
2222      cases where the server needs some authentication, the user can
2223      use binddn and bindpw for auth. */
2224
2225   if(binddn)
2226     {
2227 #ifdef HAVE_LDAP_SET_OPTION
2228       int ver=LDAP_VERSION3;
2229
2230       err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2231       if(err!=LDAP_SUCCESS)
2232         {
2233           fprintf(console,"gpgkeys: unable to go to LDAP 3: %s\n",
2234                   ldap_err2string(err));
2235           fail_all(keylist,ldap_err_to_gpg_err(err));
2236           goto fail;
2237         }
2238 #endif
2239
2240       if(opt->verbose>2)
2241         fprintf(console,"gpgkeys: LDAP bind to %s, pw %s\n",binddn,
2242                 bindpw?">not shown<":">none<");
2243       err=ldap_simple_bind_s(ldap,binddn,bindpw);
2244       if(err!=LDAP_SUCCESS)
2245         {
2246           fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
2247                   ldap_err2string(err));
2248           fail_all(keylist,ldap_err_to_gpg_err(err));
2249           goto fail;
2250         }
2251       else
2252         bound=1;
2253     }
2254
2255   if(opt->action==KS_GET)
2256     {
2257       keyptr=keylist;
2258
2259       while(keyptr!=NULL)
2260         {
2261           set_timeout(opt->timeout);
2262
2263           if(get_key(keyptr->str)!=KEYSERVER_OK)
2264             failed++;
2265
2266           keyptr=keyptr->next;
2267         }
2268     }
2269   else if(opt->action==KS_GETNAME)
2270     {
2271       keyptr=keylist;
2272
2273       while(keyptr!=NULL)
2274         {
2275           set_timeout(opt->timeout);
2276
2277           if(get_name(keyptr->str)!=KEYSERVER_OK)
2278             failed++;
2279
2280           keyptr=keyptr->next;
2281         }
2282     }
2283   else if(opt->action==KS_SEND)
2284     {
2285       int eof_seen = 0;
2286
2287       do
2288         {
2289           set_timeout(opt->timeout);
2290
2291           if(real_ldap)
2292             {
2293               if (send_key(&eof_seen) != KEYSERVER_OK)
2294                 failed++;
2295             }
2296           else
2297             {
2298               if (send_key_keyserver(&eof_seen) != KEYSERVER_OK)
2299                 failed++;
2300             }
2301         }
2302       while (!eof_seen);
2303     }
2304   else if(opt->action==KS_SEARCH)
2305     {
2306       char *searchkey=NULL;
2307       int len=0;
2308
2309       set_timeout(opt->timeout);
2310
2311       /* To search, we stick a * in between each key to search for.
2312          This means that if the user enters words, they'll get
2313          "enters*words".  If the user "enters words", they'll get
2314          "enters words" */
2315
2316       keyptr=keylist;
2317       while(keyptr!=NULL)
2318         {
2319           len+=strlen(keyptr->str)+1;
2320           keyptr=keyptr->next;
2321         }
2322
2323       searchkey=malloc((len*3)+1);
2324       if(searchkey==NULL)
2325         {
2326           ret=KEYSERVER_NO_MEMORY;
2327           fail_all(keylist,KEYSERVER_NO_MEMORY);
2328           goto fail;
2329         }
2330
2331       searchkey[0]='\0';
2332
2333       keyptr=keylist;
2334       while(keyptr!=NULL)
2335         {
2336           ldap_quote(searchkey,keyptr->str);
2337           strcat(searchkey,"*");
2338           keyptr=keyptr->next;
2339         }
2340
2341       /* Nail that last "*" */
2342       if(*searchkey)
2343         searchkey[strlen(searchkey)-1]='\0';
2344
2345       if(search_key(searchkey)!=KEYSERVER_OK)
2346         failed++;
2347
2348       free(searchkey);
2349     }
2350   else
2351     assert (!"bad action");
2352
2353   if(!failed)
2354     ret=KEYSERVER_OK;
2355
2356  fail:
2357
2358   while(keylist!=NULL)
2359     {
2360       struct keylist *current=keylist;
2361       keylist=keylist->next;
2362       free(current);
2363     }
2364
2365   if(input!=stdin)
2366     fclose(input);
2367
2368   if(output!=stdout)
2369     fclose(output);
2370
2371   free_ks_options(opt);
2372
2373   if(ldap!=NULL && bound)
2374     ldap_unbind_s(ldap);
2375
2376   free(basekeyspacedn);
2377
2378   return ret;
2379 }