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