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