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