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