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