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