Fix a couple of minor bugs.
[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   if (modlist)
781     {
782       for(ml=modlist;*ml;ml++)
783         {
784           free_mod_values(*ml);
785           free(*ml);
786         }
787       free(modlist);
788     }
789
790   free(addlist);
791   free(dn);
792   free(key);
793
794   if(ret!=0 && begin)
795     fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
796
797   return ret;
798 }
799
800 static int
801 send_key_keyserver(int *eof)
802 {
803   int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
804   char *dn=NULL,line[MAX_LINE],*key[2]={NULL,NULL};
805   char keyid[17],state[6];
806   LDAPMod mod, *attrs[2];
807
808   memset(&mod,0,sizeof(mod));
809   mod.mod_op=LDAP_MOD_ADD;
810   mod.mod_type=pgpkeystr;
811   mod.mod_values=key;
812   attrs[0]=&mod;
813   attrs[1]=NULL;
814
815   dn=malloc(strlen("pgpCertid=virtual,")+strlen(basekeyspacedn)+1);
816   if(dn==NULL)
817     {
818       fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
819       ret=KEYSERVER_NO_MEMORY;
820       goto fail;
821     }
822
823   strcpy(dn,"pgpCertid=virtual,");
824   strcat(dn,basekeyspacedn);
825
826   key[0]=malloc(1);
827   if(key[0]==NULL)
828     {
829       fprintf(console,"gpgkeys: unable to allocate memory for key\n");
830       ret=KEYSERVER_NO_MEMORY;
831       goto fail;
832     }
833
834   key[0][0]='\0';
835
836   /* Read and throw away stdin until we see the BEGIN */
837
838   while(fgets(line,MAX_LINE,input)!=NULL)
839     if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
840        && strcmp(state,"BEGIN")==0)
841       {
842         begin=1;
843         break;
844       }
845
846   if(!begin)
847     {
848       /* i.e. eof before the KEY BEGIN was found.  This isn't an
849          error. */
850       *eof=1;
851       ret=KEYSERVER_OK;
852       goto fail;
853     }
854
855   /* Now slurp up everything until we see the END */
856
857   while(fgets(line,MAX_LINE,input)!=NULL)
858     if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
859        && strcmp(state,"END")==0)
860       {
861         end=1;
862         break;
863       }
864     else
865       {
866         keysize+=strlen(line);
867         key[0]=realloc(key[0],keysize);
868         if(key[0]==NULL)
869           {
870             fprintf(console,"gpgkeys: unable to reallocate for key\n");
871             ret=KEYSERVER_NO_MEMORY;
872             goto fail;
873           }
874
875         strcat(key[0],line);
876       }
877
878   if(!end)
879     {
880       fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
881       *eof=1;
882       ret=KEYSERVER_KEY_INCOMPLETE;
883       goto fail;
884     }
885
886   err=ldap_add_s(ldap,dn,attrs);
887   if(err!=LDAP_SUCCESS)
888     {
889       fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
890               keyid,ldap_err2string(err));
891       ret=ldap_err_to_gpg_err(err);
892       goto fail;
893     }
894
895   ret=KEYSERVER_OK;
896
897  fail:
898
899   free(key[0]);
900   free(dn);
901
902   if(ret!=0 && begin)
903     fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
904
905   /* Not a fatal error */
906   if(ret==KEYSERVER_KEY_EXISTS)
907     ret=KEYSERVER_OK;
908
909   return ret;
910 }
911
912 static void
913 build_info(const char *certid,LDAPMessage *each)
914 {
915   char **vals;
916
917   fprintf(output,"INFO %s BEGIN\n",certid);
918
919   fprintf(output,"pub:%s:",certid);
920
921   vals=ldap_get_values(ldap,each,"pgpkeytype");
922   if(vals!=NULL)
923     {
924       if(strcmp(vals[0],"RSA")==0)
925         fprintf(output,"1");
926       else if(strcmp(vals[0],"DSS/DH")==0)
927         fprintf(output,"17");
928       ldap_value_free(vals);
929     }
930
931   fprintf(output,":");
932
933   vals=ldap_get_values(ldap,each,"pgpkeysize");
934   if(vals!=NULL)
935     {
936       if(atoi(vals[0])>0)
937         fprintf(output,"%d",atoi(vals[0]));
938       ldap_value_free(vals);
939     }
940
941   fprintf(output,":");
942
943   vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
944   if(vals!=NULL)
945     {
946       if(strlen(vals[0])==15)
947         fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
948       ldap_value_free(vals);
949     }
950
951   fprintf(output,":");
952
953   vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
954   if(vals!=NULL)
955     {
956       if(strlen(vals[0])==15)
957         fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
958       ldap_value_free(vals);
959     }
960
961   fprintf(output,":");
962
963   vals=ldap_get_values(ldap,each,"pgprevoked");
964   if(vals!=NULL)
965     {
966       if(atoi(vals[0])==1)
967         fprintf(output,"r");
968       ldap_value_free(vals);
969     }
970
971   fprintf(output,"\n");
972
973   vals=ldap_get_values(ldap,each,"pgpuserid");
974   if(vals!=NULL)
975     {
976       int i;
977
978       for(i=0;vals[i];i++)
979         fprintf(output,"uid:%s\n",vals[i]);
980       ldap_value_free(vals);
981     }
982
983   fprintf(output,"INFO %s END\n",certid);
984 }
985
986 /* Note that key-not-found is not a fatal error */
987 static int
988 get_key(char *getkey)
989 {
990   LDAPMessage *res,*each;
991   int ret=KEYSERVER_INTERNAL_ERROR,err,count;
992   struct keylist *dupelist=NULL;
993   char search[62];
994   /* This ordering is significant - specifically, "pgpcertid" needs to
995      be the second item in the list, since everything after it may be
996      discarded if the user isn't in verbose mode. */
997   char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
998                  "pgpdisabled","pgpkeycreatetime","modifytimestamp",
999                  "pgpkeysize","pgpkeytype",NULL};
1000   attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1001                          array initializers. */
1002
1003   /* Build the search string */
1004
1005   /* GPG can send us a v4 fingerprint, a v3 or v4 long key id, or a v3
1006      or v4 short key id */
1007
1008   if(strncmp(getkey,"0x",2)==0)
1009     getkey+=2;
1010
1011   if(strlen(getkey)==32)
1012     {
1013       fprintf(console,
1014               "gpgkeys: LDAP keyservers do not support v3 fingerprints\n");
1015       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1016       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_NOT_SUPPORTED);
1017       return KEYSERVER_NOT_SUPPORTED;
1018     }
1019
1020   if(strlen(getkey)>16)
1021     {
1022       char *offset=&getkey[strlen(getkey)-16];
1023
1024       /* fingerprint.  Take the last 16 characters and treat it like a
1025          long key id */
1026
1027       if(opt->flags.include_subkeys)
1028         sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1029                 offset,offset);
1030       else
1031         sprintf(search,"(pgpcertid=%.16s)",offset);
1032     }
1033   else if(strlen(getkey)>8)
1034     {
1035       /* long key id */
1036
1037       if(opt->flags.include_subkeys)
1038         sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1039                 getkey,getkey);
1040       else
1041         sprintf(search,"(pgpcertid=%.16s)",getkey);
1042     }
1043   else
1044     {
1045       /* short key id */
1046     
1047       sprintf(search,"(pgpkeyid=%.8s)",getkey);
1048     }
1049
1050   if(opt->verbose>2)
1051     fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1052
1053   if(!opt->verbose)
1054     attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1055
1056   err=ldap_search_s(ldap,basekeyspacedn,
1057                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1058   if(err!=0)
1059     {
1060       int errtag=ldap_err_to_gpg_err(err);
1061
1062       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1063       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1064       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1065       return errtag;
1066     }
1067
1068   count=ldap_count_entries(ldap,res);
1069   if(count<1)
1070     {
1071       fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1072       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1073       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1074     }
1075   else
1076     {
1077       /* There may be more than one unique result for a given keyID,
1078          so we should fetch them all (test this by fetching short key
1079          id 0xDEADBEEF). */
1080
1081       each=ldap_first_entry(ldap,res);
1082       while(each!=NULL)
1083         {
1084           char **vals,**certid;
1085
1086           /* Use the long keyid to remove duplicates.  The LDAP server
1087              returns the same keyid more than once if there are
1088              multiple user IDs on the key.  Note that this does NOT
1089              mean that a keyid that exists multiple times on the
1090              keyserver will not be fetched.  It means that each KEY,
1091              no matter how many user IDs share its keyid, will be
1092              fetched only once.  If a keyid that belongs to more than
1093              one key is fetched, the server quite properly responds
1094              with all matching keys. -ds */
1095
1096           certid=ldap_get_values(ldap,each,"pgpcertid");
1097           if(certid!=NULL)
1098             {
1099               if(!key_in_keylist(certid[0],dupelist))
1100                 {
1101                   /* it's not a duplicate, so add it */
1102
1103                   int rc=add_key_to_keylist(certid[0],&dupelist);
1104                   if(rc)
1105                     {
1106                       ret=rc;
1107                       goto fail;
1108                     }
1109
1110                   build_info(certid[0],each);
1111
1112                   fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1113
1114                   vals=ldap_get_values(ldap,each,pgpkeystr);
1115                   if(vals==NULL)
1116                     {
1117                       int errtag=ldap_to_gpg_err(ldap);
1118
1119                       fprintf(console,"gpgkeys: unable to retrieve key %s "
1120                               "from keyserver\n",getkey);
1121                       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1122                     }
1123                   else
1124                     {
1125                       print_nocr(output,vals[0]);
1126                       fprintf(output,"\nKEY 0x%s END\n",getkey);
1127
1128                       ldap_value_free(vals);
1129                     }
1130                 }
1131
1132               ldap_value_free(certid);
1133             }
1134
1135           each=ldap_next_entry(ldap,each);
1136         }
1137     }
1138
1139   ret=KEYSERVER_OK;
1140
1141  fail:
1142   ldap_msgfree(res);
1143   free_keylist(dupelist);
1144
1145   return ret;
1146 }
1147
1148 #define LDAP_ESCAPE_CHARS "*()\\"
1149
1150 /* Append string to buffer in a LDAP-quoted way */
1151 static void
1152 ldap_quote(char *buffer,const char *string)
1153 {
1154   /* Find the end of buffer */
1155   buffer+=strlen(buffer);
1156
1157   for(;*string;string++)
1158     {
1159       if(strchr(LDAP_ESCAPE_CHARS,*string))
1160         {
1161           sprintf(buffer,"\\%02X",*string);
1162           buffer+=3;
1163         }
1164       else
1165         *buffer++=*string;
1166     }
1167
1168   *buffer='\0';
1169 }
1170
1171 /* Note that key-not-found is not a fatal error */
1172 static int
1173 get_name(char *getkey)
1174 {
1175   LDAPMessage *res,*each;
1176   int ret=KEYSERVER_INTERNAL_ERROR,err,count;
1177   /* The maximum size of the search, including the optional stuff and
1178      the trailing \0 */
1179   char search[2+12+(MAX_LINE*3)+2+15+14+1+1+20];
1180   /* This ordering is significant - specifically, "pgpcertid" needs to
1181      be the second item in the list, since everything after it may be
1182      discarded if the user isn't in verbose mode. */
1183   char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
1184                  "pgpdisabled","pgpkeycreatetime","modifytimestamp",
1185                  "pgpkeysize","pgpkeytype",NULL};
1186   attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1187                          array initializers. */
1188
1189   /* Build the search string */
1190
1191   search[0]='\0';
1192
1193   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1194     strcat(search,"(&");
1195
1196   strcat(search,"(pgpUserID=*");
1197   ldap_quote(search,getkey);
1198   strcat(search,"*)");
1199
1200   if(!opt->flags.include_disabled)
1201     strcat(search,"(pgpDisabled=0)");
1202
1203   if(!opt->flags.include_revoked)
1204     strcat(search,"(pgpRevoked=0)");
1205
1206   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1207     strcat(search,")");
1208
1209   if(opt->verbose>2)
1210     fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1211
1212   if(!opt->verbose)
1213     attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1214
1215   err=ldap_search_s(ldap,basekeyspacedn,
1216                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1217   if(err!=0)
1218     {
1219       int errtag=ldap_err_to_gpg_err(err);
1220
1221       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1222       fprintf(output,"NAME %s BEGIN\n",getkey);
1223       fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1224       return errtag;
1225     }
1226
1227   count=ldap_count_entries(ldap,res);
1228   if(count<1)
1229     {
1230       fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1231       fprintf(output,"NAME %s BEGIN\n",getkey);
1232       fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1233     }
1234   else
1235     {
1236       /* There may be more than one result, but we return them all. */
1237
1238       each=ldap_first_entry(ldap,res);
1239       while(each!=NULL)
1240         {
1241           char **vals,**certid;
1242
1243           certid=ldap_get_values(ldap,each,"pgpcertid");
1244           if(certid!=NULL)
1245             {
1246               build_info(certid[0],each);
1247
1248               fprintf(output,"NAME %s BEGIN\n",getkey);
1249
1250               vals=ldap_get_values(ldap,each,pgpkeystr);
1251               if(vals==NULL)
1252                 {
1253                   int errtag=ldap_to_gpg_err(ldap);
1254
1255                   fprintf(console,"gpgkeys: unable to retrieve key %s "
1256                           "from keyserver\n",getkey);
1257                   fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1258                 }
1259               else
1260                 {
1261                   print_nocr(output,vals[0]);
1262                   fprintf(output,"\nNAME %s END\n",getkey);
1263
1264                   ldap_value_free(vals);
1265                 }
1266
1267               ldap_value_free(certid);
1268             }
1269
1270           each=ldap_next_entry(ldap,each);
1271         }
1272     }
1273
1274   ret=KEYSERVER_OK;
1275
1276   ldap_msgfree(res);
1277
1278   return ret;
1279 }
1280
1281 static void
1282 printquoted(FILE *stream,char *string,char delim)
1283 {
1284   while(*string)
1285     {
1286       if(*string==delim || *string=='%')
1287         fprintf(stream,"%%%02x",(unsigned char)*string);
1288       else
1289         fputc(*string,stream);
1290
1291       string++;
1292     }
1293 }
1294
1295 /* Returns 0 on success and -1 on error.  Note that key-not-found is
1296    not an error! */
1297 static int
1298 search_key(const char *searchkey)
1299 {
1300   char **vals,*search;
1301   LDAPMessage *res,*each;
1302   int err,count=0;
1303   struct keylist *dupelist=NULL;
1304   /* The maximum size of the search, including the optional stuff and
1305      the trailing \0 */
1306   char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1307                  "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1308                  "pgpkeysize","pgpkeytype",NULL};
1309   enum ks_search_type search_type;
1310
1311   search=malloc(2+1+9+1+3+strlen(searchkey)+3+1+15+14+1+1+20);
1312   if(!search)
1313     {
1314       fprintf(console,"gpgkeys: out of memory when building search list\n");
1315       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,KEYSERVER_NO_MEMORY);
1316       return KEYSERVER_NO_MEMORY;
1317     }
1318
1319   fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1320
1321   search_type=classify_ks_search(&searchkey);
1322
1323   if(opt->debug)
1324     fprintf(console,"search type is %d, and key is \"%s\"\n",
1325             search_type,searchkey);
1326
1327   /* Build the search string */
1328
1329   search[0]='\0';
1330
1331   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1332     strcat(search,"(&");
1333
1334   strcat(search,"(");
1335
1336   switch(search_type)
1337     {
1338     case KS_SEARCH_KEYID_SHORT:
1339       strcat(search,"pgpKeyID");
1340       break;
1341
1342     case KS_SEARCH_KEYID_LONG:
1343       strcat(search,"pgpCertID");
1344       break;
1345
1346     default:
1347       strcat(search,"pgpUserID");
1348       break;
1349     }
1350
1351   strcat(search,"=");
1352
1353   switch(search_type)
1354     {
1355     case KS_SEARCH_SUBSTR:
1356       strcat(search,"*");
1357       break;
1358
1359     case KS_SEARCH_MAIL:
1360       strcat(search,"*<");
1361       break;
1362
1363     case KS_SEARCH_MAILSUB:
1364       strcat(search,"*<*");
1365       break;
1366
1367     case KS_SEARCH_EXACT:
1368     case KS_SEARCH_KEYID_LONG:
1369     case KS_SEARCH_KEYID_SHORT:
1370       break;
1371     }
1372
1373   strcat(search,searchkey);
1374
1375   switch(search_type)
1376     {
1377     case KS_SEARCH_SUBSTR:
1378       strcat(search,"*");
1379       break;
1380
1381     case KS_SEARCH_MAIL:
1382       strcat(search,">*");
1383       break;
1384
1385     case KS_SEARCH_MAILSUB:
1386       strcat(search,"*>*");
1387       break;
1388
1389     case KS_SEARCH_EXACT:
1390     case KS_SEARCH_KEYID_LONG:
1391     case KS_SEARCH_KEYID_SHORT:
1392       break;
1393     }
1394
1395   strcat(search,")");
1396
1397   if(!opt->flags.include_disabled)
1398     strcat(search,"(pgpDisabled=0)");
1399
1400   if(!opt->flags.include_revoked)
1401     strcat(search,"(pgpRevoked=0)");
1402
1403   if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1404     strcat(search,")");
1405
1406   if(opt->verbose>2)
1407     fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1408
1409   err=ldap_search_s(ldap,basekeyspacedn,
1410                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1411   free(search);
1412   if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1413     {
1414       int errtag=ldap_err_to_gpg_err(err);
1415
1416       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1417       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1418       return errtag;
1419     }
1420
1421   /* The LDAP server doesn't return a real count of unique keys, so we
1422      can't use ldap_count_entries here. */
1423   each=ldap_first_entry(ldap,res);
1424   while(each!=NULL)
1425     {
1426       char **certid=ldap_get_values(ldap,each,"pgpcertid");
1427
1428       if(certid!=NULL)
1429         {
1430           if(!key_in_keylist(certid[0],dupelist))
1431             {
1432               int rc=add_key_to_keylist(certid[0],&dupelist);
1433               if(rc!=0)
1434                 {
1435                   fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1436                   free_keylist(dupelist);
1437                   return rc;
1438                 }
1439
1440               count++;
1441             }
1442         }
1443
1444       each=ldap_next_entry(ldap,each);
1445     }
1446
1447   if(err==LDAP_SIZELIMIT_EXCEEDED)
1448     {
1449       if(count==1)
1450         fprintf(console,"gpgkeys: search results exceeded server limit."
1451                 "  First %d result shown.\n",count);
1452       else
1453         fprintf(console,"gpgkeys: search results exceeded server limit."
1454                 "  First %d results shown.\n",count);
1455     }
1456
1457   free_keylist(dupelist);
1458   dupelist=NULL;
1459
1460   if(count<1)
1461     fprintf(output,"info:1:0\n");
1462   else
1463     {
1464       fprintf(output,"info:1:%d\n",count);
1465
1466       each=ldap_first_entry(ldap,res);
1467       while(each!=NULL)
1468         {
1469           char **certid;
1470
1471           certid=ldap_get_values(ldap,each,"pgpcertid");
1472           if(certid!=NULL)
1473             {
1474               LDAPMessage *uids;
1475
1476               /* Have we seen this certid before? */
1477               if(!key_in_keylist(certid[0],dupelist))
1478                 {
1479                   int rc=add_key_to_keylist(certid[0],&dupelist);
1480                   if(rc)
1481                     {
1482                       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1483                       free_keylist(dupelist);
1484                       ldap_value_free(certid);
1485                       ldap_msgfree(res);
1486                       return rc;
1487                     }
1488
1489                   fprintf(output,"pub:%s:",certid[0]);
1490
1491                   vals=ldap_get_values(ldap,each,"pgpkeytype");
1492                   if(vals!=NULL)
1493                     {
1494                       /* The LDAP server doesn't exactly handle this
1495                          well. */
1496                       if(ascii_strcasecmp(vals[0],"RSA")==0)
1497                         fprintf(output,"1");
1498                       else if(ascii_strcasecmp(vals[0],"DSS/DH")==0)
1499                         fprintf(output,"17");
1500                       ldap_value_free(vals);
1501                     }
1502
1503                   fputc(':',output);
1504
1505                   vals=ldap_get_values(ldap,each,"pgpkeysize");
1506                   if(vals!=NULL)
1507                     {
1508                       /* Not sure why, but some keys are listed with a
1509                          key size of 0.  Treat that like an
1510                          unknown. */
1511                       if(atoi(vals[0])>0)
1512                         fprintf(output,"%d",atoi(vals[0]));
1513                       ldap_value_free(vals);
1514                     }
1515
1516                   fputc(':',output);
1517
1518                   /* YYYYMMDDHHmmssZ */
1519
1520                   vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1521                   if(vals!=NULL && strlen(vals[0])==15)
1522                     {
1523                       fprintf(output,"%u",
1524                               (unsigned int)ldap2epochtime(vals[0]));
1525                       ldap_value_free(vals);
1526                     }
1527
1528                   fputc(':',output);
1529
1530                   vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
1531                   if(vals!=NULL && strlen(vals[0])==15)
1532                     {
1533                       fprintf(output,"%u",
1534                               (unsigned int)ldap2epochtime(vals[0]));
1535                       ldap_value_free(vals);
1536                     }
1537
1538                   fputc(':',output);
1539
1540                   vals=ldap_get_values(ldap,each,"pgprevoked");
1541                   if(vals!=NULL)
1542                     {
1543                       if(atoi(vals[0])==1)
1544                         fprintf(output,"r");
1545                       ldap_value_free(vals);
1546                     }
1547
1548                   vals=ldap_get_values(ldap,each,"pgpdisabled");
1549                   if(vals!=NULL)
1550                     {
1551                       if(atoi(vals[0])==1)
1552                         fprintf(output,"d");
1553                       ldap_value_free(vals);
1554                     }
1555
1556 #if 0
1557                   /* This is not yet specified in the keyserver
1558                      protocol, but may be someday. */
1559                   fputc(':',output);
1560
1561                   vals=ldap_get_values(ldap,each,"modifytimestamp");
1562                   if(vals!=NULL && strlen(vals[0])==15)
1563                     {
1564                       fprintf(output,"%u",
1565                               (unsigned int)ldap2epochtime(vals[0]));
1566                       ldap_value_free(vals);
1567                     }
1568 #endif
1569
1570                   fprintf(output,"\n");
1571
1572                   /* Now print all the uids that have this certid */
1573                   uids=ldap_first_entry(ldap,res);
1574                   while(uids!=NULL)
1575                     {
1576                       vals=ldap_get_values(ldap,uids,"pgpcertid");
1577                       if(vals!=NULL)
1578                         {
1579                           if(ascii_strcasecmp(certid[0],vals[0])==0)
1580                             {
1581                               char **uidvals;
1582
1583                               fprintf(output,"uid:");
1584
1585                               uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1586                               if(uidvals!=NULL)
1587                                 {
1588                                   /* Need to escape any colons */
1589                                   printquoted(output,uidvals[0],':');
1590                                   ldap_value_free(uidvals);
1591                                 }
1592
1593                               fprintf(output,"\n");
1594                             }
1595
1596                           ldap_value_free(vals);
1597                         }
1598
1599                       uids=ldap_next_entry(ldap,uids);
1600                     }
1601                 }
1602
1603               ldap_value_free(certid);
1604             }
1605
1606           each=ldap_next_entry(ldap,each);
1607         }
1608     }
1609
1610   ldap_msgfree(res);
1611   free_keylist(dupelist);
1612
1613   fprintf(output,"SEARCH %s END\n",searchkey);
1614
1615   return KEYSERVER_OK;
1616 }
1617
1618 static void
1619 fail_all(struct keylist *keylist,int err)
1620 {
1621   if(!keylist)
1622     return;
1623
1624   if(opt->action==KS_SEARCH)
1625     {
1626       fprintf(output,"SEARCH ");
1627       while(keylist)
1628         {
1629           fprintf(output,"%s ",keylist->str);
1630           keylist=keylist->next;
1631         }
1632       fprintf(output,"FAILED %d\n",err);
1633     }
1634   else
1635     while(keylist)
1636       {
1637         fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1638         keylist=keylist->next;
1639       }
1640 }
1641
1642 static int
1643 find_basekeyspacedn(void)
1644 {
1645   int err,i;
1646   char *attr[]={"namingContexts",NULL,NULL,NULL};
1647   LDAPMessage *res;
1648   char **context;
1649
1650   /* Look for namingContexts */
1651   err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1652   if(err==LDAP_SUCCESS)
1653     {
1654       context=ldap_get_values(ldap,res,"namingContexts");
1655       if(context)
1656         {
1657           attr[0]="pgpBaseKeySpaceDN";
1658           attr[1]="pgpVersion";
1659           attr[2]="pgpSoftware";
1660
1661           real_ldap=1;
1662
1663           /* We found some, so try each namingContext as the search base
1664              and look for pgpBaseKeySpaceDN.  Because we found this, we
1665              know we're talking to a regular-ish LDAP server and not a
1666              LDAP keyserver. */
1667
1668           for(i=0;context[i] && !basekeyspacedn;i++)
1669             {
1670               char **vals;
1671               LDAPMessage *si_res;
1672               char *object;
1673
1674               object=malloc(17+strlen(context[i])+1);
1675               if(!object)
1676                 return -1;
1677
1678               strcpy(object,"cn=pgpServerInfo,");
1679               strcat(object,context[i]);
1680
1681               err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1682                                 "(objectClass=*)",attr,0,&si_res);
1683               free(object);
1684
1685               if(err==LDAP_NO_SUCH_OBJECT)
1686                 continue;
1687               else if(err!=LDAP_SUCCESS)
1688                 return err;
1689
1690               vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1691               if(vals)
1692                 {
1693                   basekeyspacedn=strdup(vals[0]);
1694                   ldap_value_free(vals);
1695                 }
1696
1697               if(opt->verbose>1)
1698                 {
1699                   vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1700                   if(vals)
1701                     {
1702                       fprintf(console,"Server: \t%s\n",vals[0]);
1703                       ldap_value_free(vals);
1704                     }
1705
1706                   vals=ldap_get_values(ldap,si_res,"pgpVersion");
1707                   if(vals)
1708                     {
1709                       fprintf(console,"Version:\t%s\n",vals[0]);
1710                       ldap_value_free(vals);
1711                     }
1712                 }
1713
1714               ldap_msgfree(si_res);
1715             }
1716
1717           ldap_value_free(context);
1718         }
1719
1720       ldap_msgfree(res);
1721     }
1722   else
1723     {
1724       /* We don't have an answer yet, which means the server might be
1725          a LDAP keyserver. */
1726       char **vals;
1727       LDAPMessage *si_res;
1728
1729       attr[0]="pgpBaseKeySpaceDN";
1730       attr[1]="version";
1731       attr[2]="software";
1732
1733       err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1734                         "(objectClass=*)",attr,0,&si_res);
1735       if(err!=LDAP_SUCCESS)
1736         return err;
1737
1738       /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1739          KEYSPACE,C=US", but it might not be in the future. */
1740
1741       vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1742       if(vals)
1743         {
1744           basekeyspacedn=strdup(vals[0]);
1745           ldap_value_free(vals);
1746         }
1747
1748       if(opt->verbose>1)
1749         {
1750           vals=ldap_get_values(ldap,si_res,"software");
1751           if(vals)
1752             {
1753               fprintf(console,"Server: \t%s\n",vals[0]);
1754               ldap_value_free(vals);
1755             }
1756         }
1757
1758       vals=ldap_get_values(ldap,si_res,"version");
1759       if(vals)
1760         {
1761           if(opt->verbose>1)
1762             fprintf(console,"Version:\t%s\n",vals[0]);
1763
1764           /* If the version is high enough, use the new pgpKeyV2
1765              attribute.  This design if iffy at best, but it matches how
1766              PGP does it.  I figure the NAI folks assumed that there would
1767              never be a LDAP keyserver vendor with a different numbering
1768              scheme. */
1769           if(atoi(vals[0])>1)
1770             pgpkeystr="pgpKeyV2";
1771
1772           ldap_value_free(vals);
1773         }
1774
1775       ldap_msgfree(si_res);
1776     }   
1777
1778   return LDAP_SUCCESS;
1779 }
1780
1781 static void 
1782 show_help (FILE *fp)
1783 {
1784   fprintf (fp,"-h, --help\thelp\n");
1785   fprintf (fp,"-V\t\tmachine readable version\n");
1786   fprintf (fp,"--version\thuman readable version\n");
1787   fprintf (fp,"-o\t\toutput to this file\n");
1788 }
1789
1790 int
1791 main(int argc,char *argv[])
1792 {
1793   int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1794   char line[MAX_LINE],*binddn=NULL,*bindpw=NULL;
1795   int failed=0,use_ssl=0,use_tls=0,bound=0;
1796   struct keylist *keylist=NULL,*keyptr=NULL;
1797
1798   console=stderr;
1799
1800   /* Kludge to implement standard GNU options.  */
1801   if (argc > 1 && !strcmp (argv[1], "--version"))
1802     {
1803       fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1804       return 0;
1805     }
1806   else if (argc > 1 && !strcmp (argv[1], "--help"))
1807     {
1808       show_help (stdout);
1809       return 0;
1810     }
1811
1812   while((arg=getopt(argc,argv,"hVo:"))!=-1)
1813     switch(arg)
1814       {
1815       default:
1816       case 'h':
1817         show_help (console);
1818         return KEYSERVER_OK;
1819
1820       case 'V':
1821         fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1822         return KEYSERVER_OK;
1823
1824       case 'o':
1825         output=fopen(optarg,"w");
1826         if(output==NULL)
1827           {
1828             fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1829                     optarg,strerror(errno));
1830             return KEYSERVER_INTERNAL_ERROR;
1831           }
1832
1833         break;
1834       }
1835
1836   if(argc>optind)
1837     {
1838       input=fopen(argv[optind],"r");
1839       if(input==NULL)
1840         {
1841           fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1842                   argv[optind],strerror(errno));
1843           return KEYSERVER_INTERNAL_ERROR;
1844         }
1845     }
1846
1847   if(input==NULL)
1848     input=stdin;
1849
1850   if(output==NULL)
1851     output=stdout;
1852
1853   opt=init_ks_options();
1854   if(!opt)
1855     return KEYSERVER_NO_MEMORY;
1856
1857   /* Get the command and info block */
1858
1859   while(fgets(line,MAX_LINE,input)!=NULL)
1860     {
1861       char optionstr[MAX_OPTION+1];
1862
1863       if(line[0]=='\n')
1864         break;
1865
1866       err=parse_ks_options(line,opt);
1867       if(err>0)
1868         {
1869           ret=err;
1870           goto fail;
1871         }
1872       else if(err==0)
1873         continue;
1874
1875       if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1876         {
1877           int no=0;
1878           char *start=&optionstr[0];
1879
1880           optionstr[MAX_OPTION]='\0';
1881
1882           if(ascii_strncasecmp(optionstr,"no-",3)==0)
1883             {
1884               no=1;
1885               start=&optionstr[3];
1886             }
1887
1888           if(ascii_strncasecmp(start,"tls",3)==0)
1889             {
1890               if(no)
1891                 use_tls=0;
1892               else if(start[3]=='=')
1893                 {
1894                   if(ascii_strcasecmp(&start[4],"no")==0)
1895                     use_tls=0;
1896                   else if(ascii_strcasecmp(&start[4],"try")==0)
1897                     use_tls=1;
1898                   else if(ascii_strcasecmp(&start[4],"warn")==0)
1899                     use_tls=2;
1900                   else if(ascii_strcasecmp(&start[4],"require")==0)
1901                     use_tls=3;
1902                   else
1903                     use_tls=1;
1904                 }
1905               else if(start[3]=='\0')
1906                 use_tls=1;
1907             }
1908           else if(ascii_strncasecmp(start,"basedn",6)==0)
1909             {
1910               if(no)
1911                 {
1912                   free(basekeyspacedn);
1913                   basekeyspacedn=NULL;
1914                 }
1915               else if(start[6]=='=')
1916                 {
1917                   free(basekeyspacedn);
1918                   basekeyspacedn=strdup(&start[7]);
1919                   if(!basekeyspacedn)
1920                     {
1921                       fprintf(console,"gpgkeys: out of memory while creating "
1922                               "base DN\n");
1923                       ret=KEYSERVER_NO_MEMORY;
1924                       goto fail;
1925                     }
1926
1927                   real_ldap=1;
1928                 }
1929             }
1930           else if(ascii_strncasecmp(start,"binddn",6)==0)
1931             {
1932               if(no)
1933                 {
1934                   free(binddn);
1935                   binddn=NULL;
1936                 }
1937               else if(start[6]=='=')
1938                 {
1939                   free(binddn);
1940                   binddn=strdup(&start[7]);
1941                   if(!binddn)
1942                     {
1943                       fprintf(console,"gpgkeys: out of memory while creating "
1944                               "bind DN\n");
1945                       ret=KEYSERVER_NO_MEMORY;
1946                       goto fail;
1947                     }
1948
1949                   real_ldap=1;
1950                 }
1951             }
1952           else if(ascii_strncasecmp(start,"bindpw",6)==0)
1953             {
1954               if(no)
1955                 {
1956                   free(bindpw);
1957                   bindpw=NULL;
1958                 }
1959               else if(start[6]=='=')
1960                 {
1961                   free(bindpw);
1962                   bindpw=strdup(&start[7]);
1963                   if(!bindpw)
1964                     {
1965                       fprintf(console,"gpgkeys: out of memory while creating "
1966                               "bind password\n");
1967                       ret=KEYSERVER_NO_MEMORY;
1968                       goto fail;
1969                     }
1970
1971                   real_ldap=1;
1972                 }
1973             }
1974
1975           continue;
1976         }
1977     }
1978
1979   if(!opt->scheme)
1980     {
1981       fprintf(console,"gpgkeys: no scheme supplied!\n");
1982       ret=KEYSERVER_SCHEME_NOT_FOUND;
1983       goto fail;
1984     }
1985
1986   if(ascii_strcasecmp(opt->scheme,"ldaps")==0)
1987     {
1988       port=636;
1989       use_ssl=1;
1990     }
1991
1992   if(opt->port)
1993     port=atoi(opt->port);
1994
1995   if(!opt->host)
1996     {
1997       fprintf(console,"gpgkeys: no keyserver host provided\n");
1998       goto fail;
1999     }
2000
2001   if(opt->timeout && register_timeout()==-1)
2002     {
2003       fprintf(console,"gpgkeys: unable to register timeout handler\n");
2004       return KEYSERVER_INTERNAL_ERROR;
2005     }
2006
2007 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
2008
2009   if(opt->ca_cert_file)
2010     {
2011       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
2012       if(err!=LDAP_SUCCESS)
2013         {
2014           fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
2015                   ldap_err2string(err));
2016           ret=KEYSERVER_INTERNAL_ERROR;
2017           goto fail;
2018         }
2019     }
2020 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
2021
2022   /* SSL trumps TLS */
2023   if(use_ssl)
2024     use_tls=0;
2025
2026   /* If it's a GET or a SEARCH, the next thing to come in is the
2027      keyids.  If it's a SEND, then there are no keyids. */
2028
2029   if(opt->action==KS_SEND)
2030     while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
2031   else if(opt->action==KS_GET
2032           || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
2033     {
2034       for(;;)
2035         {
2036           struct keylist *work;
2037
2038           if(fgets(line,MAX_LINE,input)==NULL)
2039             break;
2040           else
2041             {
2042               if(line[0]=='\n' || line[0]=='\0')
2043                 break;
2044
2045               work=malloc(sizeof(struct keylist));
2046               if(work==NULL)
2047                 {
2048                   fprintf(console,"gpgkeys: out of memory while "
2049                           "building key list\n");
2050                   ret=KEYSERVER_NO_MEMORY;
2051                   goto fail;
2052                 }
2053
2054               strcpy(work->str,line);
2055
2056               /* Trim the trailing \n */
2057               work->str[strlen(line)-1]='\0';
2058
2059               work->next=NULL;
2060
2061               /* Always attach at the end to keep the list in proper
2062                  order for searching */
2063               if(keylist==NULL)
2064                 keylist=work;
2065               else
2066                 keyptr->next=work;
2067
2068               keyptr=work;
2069             }
2070         }
2071     }
2072   else
2073     {
2074       fprintf(console,"gpgkeys: no keyserver command specified\n");
2075       goto fail;
2076     }
2077
2078   /* Send the response */
2079
2080   fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
2081   fprintf(output,"PROGRAM %s\n\n",VERSION);
2082
2083   if(opt->verbose>1)
2084     {
2085       fprintf(console,"Host:\t\t%s\n",opt->host);
2086       if(port)
2087         fprintf(console,"Port:\t\t%d\n",port);
2088       fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
2089     }
2090
2091   if(opt->debug)
2092     {
2093 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
2094       err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
2095       if(err!=LDAP_SUCCESS)
2096         fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
2097                 ldap_err2string(err));
2098       else
2099         fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
2100 #else
2101       fprintf(console,"gpgkeys: not built with debugging support\n");
2102 #endif
2103     }
2104
2105   /* We have a timeout set for the setup stuff since it could time out
2106      as well. */
2107   set_timeout(opt->timeout);
2108
2109   /* Note that this tries all A records on a given host (or at least,
2110      OpenLDAP does). */
2111   ldap=ldap_init(opt->host,port);
2112   if(ldap==NULL)
2113     {
2114       fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
2115               strerror(errno));
2116       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2117       goto fail;
2118     }
2119
2120   if(use_ssl)
2121     {
2122 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
2123       int ssl=LDAP_OPT_X_TLS_HARD;
2124
2125       err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
2126       if(err!=LDAP_SUCCESS)
2127         {
2128           fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2129                   ldap_err2string(err));
2130           fail_all(keylist,ldap_err_to_gpg_err(err));
2131           goto fail;
2132         }
2133
2134       if(!opt->flags.check_cert)
2135         ssl=LDAP_OPT_X_TLS_NEVER;
2136
2137       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
2138       if(err!=LDAP_SUCCESS)
2139         {
2140           fprintf(console,
2141                   "gpgkeys: unable to set certificate validation: %s\n",
2142                   ldap_err2string(err));
2143           fail_all(keylist,ldap_err_to_gpg_err(err));
2144           goto fail;
2145         }
2146 #else
2147       fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2148               "not built with LDAPS support");
2149       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2150       goto fail;
2151 #endif
2152     }
2153
2154   if(!basekeyspacedn)
2155     if((err=find_basekeyspacedn()) || !basekeyspacedn)
2156       {
2157         fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
2158                 err?ldap_err2string(err):"not found");
2159         fail_all(keylist,ldap_err_to_gpg_err(err));
2160         goto fail;
2161       }
2162
2163   /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
2164      3=force use. */
2165   if(use_tls)
2166     {
2167       if(!real_ldap)
2168         {
2169           if(use_tls>=2)
2170             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2171                     "not supported by the NAI LDAP keyserver");
2172           if(use_tls==3)
2173             {
2174               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2175               goto fail;
2176             }
2177         }
2178       else
2179         {
2180 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
2181           int ver=LDAP_VERSION3;
2182
2183           err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2184
2185 #ifdef LDAP_OPT_X_TLS
2186           if(err==LDAP_SUCCESS)
2187             {
2188               if(opt->flags.check_cert)
2189                 ver=LDAP_OPT_X_TLS_HARD;
2190               else
2191                 ver=LDAP_OPT_X_TLS_NEVER;
2192
2193               err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
2194             }
2195 #endif
2196
2197           if(err==LDAP_SUCCESS)
2198             err=ldap_start_tls_s(ldap,NULL,NULL);
2199
2200           if(err!=LDAP_SUCCESS)
2201             {
2202               if(use_tls>=2 || opt->verbose>2)
2203                 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2204                         ldap_err2string(err));
2205               /* Are we forcing it? */
2206               if(use_tls==3)
2207                 {
2208                   fail_all(keylist,ldap_err_to_gpg_err(err));
2209                   goto fail;
2210                 }
2211             }
2212           else if(opt->verbose>1)
2213             fprintf(console,"gpgkeys: TLS started successfully.\n");
2214 #else
2215           if(use_tls>=2)
2216             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2217                     "not built with TLS support");
2218           if(use_tls==3)
2219             {
2220               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2221               goto fail;
2222             }
2223 #endif
2224         }
2225     }
2226
2227   /* By default we don't bind as there is usually no need to.  For
2228      cases where the server needs some authentication, the user can
2229      use binddn and bindpw for auth. */
2230
2231   if(binddn)
2232     {
2233 #ifdef HAVE_LDAP_SET_OPTION
2234       int ver=LDAP_VERSION3;
2235
2236       err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2237       if(err!=LDAP_SUCCESS)
2238         {
2239           fprintf(console,"gpgkeys: unable to go to LDAP 3: %s\n",
2240                   ldap_err2string(err));
2241           fail_all(keylist,ldap_err_to_gpg_err(err));
2242           goto fail;
2243         }
2244 #endif
2245
2246       if(opt->verbose>2)
2247         fprintf(console,"gpgkeys: LDAP bind to %s, pw %s\n",binddn,
2248                 bindpw?">not shown<":">none<");
2249       err=ldap_simple_bind_s(ldap,binddn,bindpw);
2250       if(err!=LDAP_SUCCESS)
2251         {
2252           fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
2253                   ldap_err2string(err));
2254           fail_all(keylist,ldap_err_to_gpg_err(err));
2255           goto fail;
2256         }
2257       else
2258         bound=1;
2259     }
2260
2261   if(opt->action==KS_GET)
2262     {
2263       keyptr=keylist;
2264
2265       while(keyptr!=NULL)
2266         {
2267           set_timeout(opt->timeout);
2268
2269           if(get_key(keyptr->str)!=KEYSERVER_OK)
2270             failed++;
2271
2272           keyptr=keyptr->next;
2273         }
2274     }
2275   else if(opt->action==KS_GETNAME)
2276     {
2277       keyptr=keylist;
2278
2279       while(keyptr!=NULL)
2280         {
2281           set_timeout(opt->timeout);
2282
2283           if(get_name(keyptr->str)!=KEYSERVER_OK)
2284             failed++;
2285
2286           keyptr=keyptr->next;
2287         }
2288     }
2289   else if(opt->action==KS_SEND)
2290     {
2291       int eof=0;
2292
2293       do
2294         {
2295           set_timeout(opt->timeout);
2296
2297           if(real_ldap)
2298             {
2299               if(send_key(&eof)!=KEYSERVER_OK)
2300                 failed++;
2301             }
2302           else
2303             {
2304               if(send_key_keyserver(&eof)!=KEYSERVER_OK)
2305                 failed++;
2306             }
2307         }
2308       while(!eof);
2309     }
2310   else if(opt->action==KS_SEARCH)
2311     {
2312       char *searchkey=NULL;
2313       int len=0;
2314
2315       set_timeout(opt->timeout);
2316
2317       /* To search, we stick a * in between each key to search for.
2318          This means that if the user enters words, they'll get
2319          "enters*words".  If the user "enters words", they'll get
2320          "enters words" */
2321
2322       keyptr=keylist;
2323       while(keyptr!=NULL)
2324         {
2325           len+=strlen(keyptr->str)+1;
2326           keyptr=keyptr->next;
2327         }
2328
2329       searchkey=malloc((len*3)+1);
2330       if(searchkey==NULL)
2331         {
2332           ret=KEYSERVER_NO_MEMORY;
2333           fail_all(keylist,KEYSERVER_NO_MEMORY);
2334           goto fail;
2335         }
2336
2337       searchkey[0]='\0';
2338
2339       keyptr=keylist;
2340       while(keyptr!=NULL)
2341         {
2342           ldap_quote(searchkey,keyptr->str);
2343           strcat(searchkey,"*");
2344           keyptr=keyptr->next;
2345         }
2346
2347       /* Nail that last "*" */
2348       if(*searchkey)
2349         searchkey[strlen(searchkey)-1]='\0';
2350
2351       if(search_key(searchkey)!=KEYSERVER_OK)
2352         failed++;
2353
2354       free(searchkey);
2355     }
2356   else
2357     assert (!"invalid action");
2358
2359   if(!failed)
2360     ret=KEYSERVER_OK;
2361
2362  fail:
2363
2364   while(keylist!=NULL)
2365     {
2366       struct keylist *current=keylist;
2367       keylist=keylist->next;
2368       free(current);
2369     }
2370
2371   if(input!=stdin)
2372     fclose(input);
2373
2374   if(output!=stdout)
2375     fclose(output);
2376
2377   free_ks_options(opt);
2378
2379   if(ldap!=NULL && bound)
2380     ldap_unbind_s(ldap);
2381
2382   free(basekeyspacedn);
2383
2384   return ret;
2385 }