f96555eddb0fd8a610dd7386b83b6d55ca7cdcf8
[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 static void
957 print_nocr(FILE *stream,const char *str)
958 {
959   while(*str)
960     {
961       if(*str!='\r')
962         fputc(*str,stream);
963       str++;
964     }
965 }
966
967 /* Note that key-not-found is not a fatal error */
968 static int
969 get_key(char *getkey)
970 {
971   LDAPMessage *res,*each;
972   int ret=KEYSERVER_INTERNAL_ERROR,err,count;
973   struct keylist *dupelist=NULL;
974   char search[62];
975   /* This ordering is significant - specifically, "pgpcertid" needs to
976      be the second item in the list, since everything after it may be
977      discarded if the user isn't in verbose mode. */
978   char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
979                  "pgpdisabled","pgpkeycreatetime","modifytimestamp",
980                  "pgpkeysize","pgpkeytype",NULL};
981   attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
982                          array initializers. */
983
984   /* Build the search string */
985
986   /* GPG can send us a v4 fingerprint, a v3 or v4 long key id, or a v3
987      or v4 short key id */
988
989   if(strncmp(getkey,"0x",2)==0)
990     getkey+=2;
991
992   if(strlen(getkey)==32)
993     {
994       fprintf(console,
995               "gpgkeys: LDAP keyservers do not support v3 fingerprints\n");
996       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
997       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_NOT_SUPPORTED);
998       return KEYSERVER_NOT_SUPPORTED;
999     }
1000
1001   if(strlen(getkey)>16)
1002     {
1003       char *offset=&getkey[strlen(getkey)-16];
1004
1005       /* fingerprint.  Take the last 16 characters and treat it like a
1006          long key id */
1007
1008       if(opt->flags.include_subkeys)
1009         sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1010                 offset,offset);
1011       else
1012         sprintf(search,"(pgpcertid=%.16s)",offset);
1013     }
1014   else if(strlen(getkey)>8)
1015     {
1016       /* long key id */
1017
1018       if(opt->flags.include_subkeys)
1019         sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1020                 getkey,getkey);
1021       else
1022         sprintf(search,"(pgpcertid=%.16s)",getkey);
1023     }
1024   else
1025     {
1026       /* short key id */
1027     
1028       sprintf(search,"(pgpkeyid=%.8s)",getkey);
1029     }
1030
1031   if(opt->verbose>2)
1032     fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1033
1034   if(!opt->verbose)
1035     attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1036
1037   err=ldap_search_s(ldap,basekeyspacedn,
1038                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1039   if(err!=0)
1040     {
1041       int errtag=ldap_err_to_gpg_err(err);
1042
1043       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1044       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1045       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1046       return errtag;
1047     }
1048
1049   count=ldap_count_entries(ldap,res);
1050   if(count<1)
1051     {
1052       fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1053       fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1054       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1055     }
1056   else
1057     {
1058       /* There may be more than one unique result for a given keyID,
1059          so we should fetch them all (test this by fetching short key
1060          id 0xDEADBEEF). */
1061
1062       each=ldap_first_entry(ldap,res);
1063       while(each!=NULL)
1064         {
1065           char **vals,**certid;
1066
1067           /* Use the long keyid to remove duplicates.  The LDAP server
1068              returns the same keyid more than once if there are
1069              multiple user IDs on the key.  Note that this does NOT
1070              mean that a keyid that exists multiple times on the
1071              keyserver will not be fetched.  It means that each KEY,
1072              no matter how many user IDs share its keyid, will be
1073              fetched only once.  If a keyid that belongs to more than
1074              one key is fetched, the server quite properly responds
1075              with all matching keys. -ds */
1076
1077           certid=ldap_get_values(ldap,each,"pgpcertid");
1078           if(certid!=NULL)
1079             {
1080               if(!key_in_keylist(certid[0],dupelist))
1081                 {
1082                   /* it's not a duplicate, so add it */
1083
1084                   int rc=add_key_to_keylist(certid[0],&dupelist);
1085                   if(rc)
1086                     {
1087                       ret=rc;
1088                       goto fail;
1089                     }
1090
1091                   build_info(certid[0],each);
1092
1093                   fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1094
1095                   vals=ldap_get_values(ldap,each,pgpkeystr);
1096                   if(vals==NULL)
1097                     {
1098                       int errtag=ldap_to_gpg_err(ldap);
1099
1100                       fprintf(console,"gpgkeys: unable to retrieve key %s "
1101                               "from keyserver\n",getkey);
1102                       fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1103                     }
1104                   else
1105                     {
1106                       print_nocr(output,vals[0]);
1107                       fprintf(output,"\nKEY 0x%s END\n",getkey);
1108
1109                       ldap_value_free(vals);
1110                     }
1111                 }
1112
1113               ldap_value_free(certid);
1114             }
1115
1116           each=ldap_next_entry(ldap,each);
1117         }
1118     }
1119
1120   ret=KEYSERVER_OK;
1121
1122  fail:
1123   ldap_msgfree(res);
1124   free_keylist(dupelist);
1125
1126   return ret;
1127 }
1128
1129 static void
1130 printquoted(FILE *stream,char *string,char delim)
1131 {
1132   while(*string)
1133     {
1134       if(*string==delim || *string=='%')
1135         fprintf(stream,"%%%02x",*string);
1136       else
1137         fputc(*string,stream);
1138
1139       string++;
1140     }
1141 }
1142
1143 /* Returns 0 on success and -1 on error.  Note that key-not-found is
1144    not an error! */
1145 static int
1146 search_key(char *searchkey)
1147 {
1148   char **vals;
1149   LDAPMessage *res,*each;
1150   int err,count=0;
1151   struct keylist *dupelist=NULL;
1152   /* The maximum size of the search, including the optional stuff and
1153      the trailing \0 */
1154   char search[2+12+MAX_LINE+2+15+14+1+1];
1155   char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1156                  "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1157                  "pgpkeysize","pgpkeytype",NULL};
1158
1159   fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1160
1161   /* Build the search string */
1162
1163   sprintf(search,"%s(pgpuserid=*%s*)%s%s%s",
1164           (!(opt->flags.include_disabled&&opt->flags.include_revoked))?"(&":"",
1165           searchkey,
1166           opt->flags.include_disabled?"":"(pgpdisabled=0)",
1167           opt->flags.include_revoked?"":"(pgprevoked=0)",
1168           !(opt->flags.include_disabled&&opt->flags.include_revoked)?")":"");
1169
1170   if(opt->verbose>2)
1171     fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1172
1173   err=ldap_search_s(ldap,basekeyspacedn,
1174                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1175   if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1176     {
1177       int errtag=ldap_err_to_gpg_err(err);
1178
1179       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1180       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1181       return errtag;
1182     }
1183
1184   /* The LDAP server doesn't return a real count of unique keys, so we
1185      can't use ldap_count_entries here. */
1186   each=ldap_first_entry(ldap,res);
1187   while(each!=NULL)
1188     {
1189       char **certid=ldap_get_values(ldap,each,"pgpcertid");
1190
1191       if(certid!=NULL)
1192         {
1193           if(!key_in_keylist(certid[0],dupelist))
1194             {
1195               int rc=add_key_to_keylist(certid[0],&dupelist);
1196               if(rc!=0)
1197                 {
1198                   fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1199                   free_keylist(dupelist);
1200                   return rc;
1201                 }
1202
1203               count++;
1204             }
1205         }
1206
1207       each=ldap_next_entry(ldap,each);
1208     }
1209
1210   if(err==LDAP_SIZELIMIT_EXCEEDED)
1211     fprintf(console,"gpgkeys: search results exceeded server limit.  First %d results shown.\n",count);
1212
1213   free_keylist(dupelist);
1214   dupelist=NULL;
1215
1216   if(count<1)
1217     fprintf(output,"info:1:0\n");
1218   else
1219     {
1220       fprintf(output,"info:1:%d\n",count);
1221
1222       each=ldap_first_entry(ldap,res);
1223       while(each!=NULL)
1224         {
1225           char **certid;
1226
1227           certid=ldap_get_values(ldap,each,"pgpcertid");
1228           if(certid!=NULL)
1229             {
1230               LDAPMessage *uids;
1231
1232               /* Have we seen this certid before? */
1233               if(!key_in_keylist(certid[0],dupelist))
1234                 {
1235                   int rc=add_key_to_keylist(certid[0],&dupelist);
1236                   if(rc)
1237                     {
1238                       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1239                       free_keylist(dupelist);
1240                       ldap_value_free(certid);
1241                       ldap_msgfree(res);
1242                       return rc;
1243                     }
1244
1245                   fprintf(output,"pub:%s:",certid[0]);
1246
1247                   vals=ldap_get_values(ldap,each,"pgpkeytype");
1248                   if(vals!=NULL)
1249                     {
1250                       /* The LDAP server doesn't exactly handle this
1251                          well. */
1252                       if(strcasecmp(vals[0],"RSA")==0)
1253                         fprintf(output,"1");
1254                       else if(strcasecmp(vals[0],"DSS/DH")==0)
1255                         fprintf(output,"17");
1256                       ldap_value_free(vals);
1257                     }
1258
1259                   fputc(':',output);
1260
1261                   vals=ldap_get_values(ldap,each,"pgpkeysize");
1262                   if(vals!=NULL)
1263                     {
1264                       /* Not sure why, but some keys are listed with a
1265                          key size of 0.  Treat that like an
1266                          unknown. */
1267                       if(atoi(vals[0])>0)
1268                         fprintf(output,"%d",atoi(vals[0]));
1269                       ldap_value_free(vals);
1270                     }
1271
1272                   fputc(':',output);
1273
1274                   /* YYYYMMDDHHmmssZ */
1275
1276                   vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1277                   if(vals!=NULL && strlen(vals[0])==15)
1278                     {
1279                       fprintf(output,"%u",
1280                               (unsigned int)ldap2epochtime(vals[0]));
1281                       ldap_value_free(vals);
1282                     }
1283
1284                   fputc(':',output);
1285
1286                   vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
1287                   if(vals!=NULL && strlen(vals[0])==15)
1288                     {
1289                       fprintf(output,"%u",
1290                               (unsigned int)ldap2epochtime(vals[0]));
1291                       ldap_value_free(vals);
1292                     }
1293
1294                   fputc(':',output);
1295
1296                   vals=ldap_get_values(ldap,each,"pgprevoked");
1297                   if(vals!=NULL)
1298                     {
1299                       if(atoi(vals[0])==1)
1300                         fprintf(output,"r");
1301                       ldap_value_free(vals);
1302                     }
1303
1304                   vals=ldap_get_values(ldap,each,"pgpdisabled");
1305                   if(vals!=NULL)
1306                     {
1307                       if(atoi(vals[0])==1)
1308                         fprintf(output,"d");
1309                       ldap_value_free(vals);
1310                     }
1311
1312 #if 0
1313                   /* This is not yet specified in the keyserver
1314                      protocol, but may be someday. */
1315                   fputc(':',output);
1316
1317                   vals=ldap_get_values(ldap,each,"modifytimestamp");
1318                   if(vals!=NULL && strlen(vals[0])==15)
1319                     {
1320                       fprintf(output,"%u",
1321                               (unsigned int)ldap2epochtime(vals[0]));
1322                       ldap_value_free(vals);
1323                     }
1324 #endif
1325
1326                   fprintf(output,"\n");
1327
1328                   /* Now print all the uids that have this certid */
1329                   uids=ldap_first_entry(ldap,res);
1330                   while(uids!=NULL)
1331                     {
1332                       vals=ldap_get_values(ldap,uids,"pgpcertid");
1333                       if(vals!=NULL)
1334                         {
1335                           if(strcasecmp(certid[0],vals[0])==0)
1336                             {
1337                               char **uidvals;
1338
1339                               fprintf(output,"uid:");
1340
1341                               uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1342                               if(uidvals!=NULL)
1343                                 {
1344                                   /* Need to escape any colons */
1345                                   printquoted(output,uidvals[0],':');
1346                                   ldap_value_free(uidvals);
1347                                 }
1348
1349                               fprintf(output,"\n");
1350                             }
1351
1352                           ldap_value_free(vals);
1353                         }
1354
1355                       uids=ldap_next_entry(ldap,uids);
1356                     }
1357                 }
1358
1359               ldap_value_free(certid);
1360             }
1361
1362           each=ldap_next_entry(ldap,each);
1363         }
1364     }
1365
1366   ldap_msgfree(res);
1367   free_keylist(dupelist);
1368
1369   fprintf(output,"SEARCH %s END\n",searchkey);
1370
1371   return KEYSERVER_OK;
1372 }
1373
1374 static void
1375 fail_all(struct keylist *keylist,int err)
1376 {
1377   if(!keylist)
1378     return;
1379
1380   if(opt->action==KS_SEARCH)
1381     {
1382       fprintf(output,"SEARCH ");
1383       while(keylist)
1384         {
1385           fprintf(output,"%s ",keylist->str);
1386           keylist=keylist->next;
1387         }
1388       fprintf(output,"FAILED %d\n",err);
1389     }
1390   else
1391     while(keylist)
1392       {
1393         fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1394         keylist=keylist->next;
1395       }
1396 }
1397
1398 static int
1399 find_basekeyspacedn(void)
1400 {
1401   int err,i;
1402   char *attr[]={"namingContexts",NULL,NULL,NULL};
1403   LDAPMessage *res;
1404   char **context;
1405
1406   /* Look for namingContexts */
1407   err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1408   if(err==LDAP_SUCCESS)
1409     {
1410       context=ldap_get_values(ldap,res,"namingContexts");
1411       if(context)
1412         {
1413           attr[0]="pgpBaseKeySpaceDN";
1414           attr[1]="pgpVersion";
1415           attr[2]="pgpSoftware";
1416
1417           real_ldap=1;
1418
1419           /* We found some, so try each namingContext as the search base
1420              and look for pgpBaseKeySpaceDN.  Because we found this, we
1421              know we're talking to a regular-ish LDAP server and not a
1422              LDAP keyserver. */
1423
1424           for(i=0;context[i] && !basekeyspacedn;i++)
1425             {
1426               char **vals;
1427               LDAPMessage *si_res;
1428               char *object;
1429
1430               object=malloc(17+strlen(context[i])+1);
1431               if(!object)
1432                 return -1;
1433
1434               strcpy(object,"cn=pgpServerInfo,");
1435               strcat(object,context[i]);
1436
1437               err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1438                                 "(objectClass=*)",attr,0,&si_res);
1439               free(object);
1440
1441               if(err==LDAP_NO_SUCH_OBJECT)
1442                 continue;
1443               else if(err!=LDAP_SUCCESS)
1444                 return err;
1445
1446               vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1447               if(vals)
1448                 {
1449                   basekeyspacedn=strdup(vals[0]);
1450                   ldap_value_free(vals);
1451                 }
1452
1453               if(opt->verbose>1)
1454                 {
1455                   vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1456                   if(vals)
1457                     {
1458                       fprintf(console,"Server: \t%s\n",vals[0]);
1459                       ldap_value_free(vals);
1460                     }
1461
1462                   vals=ldap_get_values(ldap,si_res,"pgpVersion");
1463                   if(vals)
1464                     {
1465                       fprintf(console,"Version:\t%s\n",vals[0]);
1466                       ldap_value_free(vals);
1467                     }
1468                 }
1469
1470               ldap_msgfree(si_res);
1471             }
1472
1473           ldap_value_free(context);
1474         }
1475
1476       ldap_msgfree(res);
1477     }
1478   else
1479     {
1480       /* We don't have an answer yet, which means the server might be
1481          a LDAP keyserver. */
1482       char **vals;
1483       LDAPMessage *si_res;
1484
1485       attr[0]="pgpBaseKeySpaceDN";
1486       attr[1]="version";
1487       attr[2]="software";
1488
1489       err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1490                         "(objectClass=*)",attr,0,&si_res);
1491       if(err!=LDAP_SUCCESS)
1492         return err;
1493
1494       /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1495          KEYSPACE,C=US", but it might not be in the future. */
1496
1497       vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1498       if(vals)
1499         {
1500           basekeyspacedn=strdup(vals[0]);
1501           ldap_value_free(vals);
1502         }
1503
1504       if(opt->verbose>1)
1505         {
1506           vals=ldap_get_values(ldap,si_res,"software");
1507           if(vals)
1508             {
1509               fprintf(console,"Server: \t%s\n",vals[0]);
1510               ldap_value_free(vals);
1511             }
1512         }
1513
1514       vals=ldap_get_values(ldap,si_res,"version");
1515       if(vals)
1516         {
1517           if(opt->verbose>1)
1518             fprintf(console,"Version:\t%s\n",vals[0]);
1519
1520           /* If the version is high enough, use the new pgpKeyV2
1521              attribute.  This design if iffy at best, but it matches how
1522              PGP does it.  I figure the NAI folks assumed that there would
1523              never be a LDAP keyserver vendor with a different numbering
1524              scheme. */
1525           if(atoi(vals[0])>1)
1526             pgpkeystr="pgpKeyV2";
1527
1528           ldap_value_free(vals);
1529         }
1530
1531       ldap_msgfree(si_res);
1532     }   
1533
1534   return LDAP_SUCCESS;
1535 }
1536
1537 static void 
1538 show_help (FILE *fp)
1539 {
1540   fprintf (fp,"-h\thelp\n");
1541   fprintf (fp,"-V\tversion\n");
1542   fprintf (fp,"-o\toutput to this file\n");
1543 }
1544
1545 int
1546 main(int argc,char *argv[])
1547 {
1548   int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1549   char line[MAX_LINE];
1550   int failed=0,use_ssl=0,use_tls=0,bound=0;
1551   struct keylist *keylist=NULL,*keyptr=NULL;
1552
1553   console=stderr;
1554
1555   /* Kludge to implement standard GNU options.  */
1556   if (argc > 1 && !strcmp (argv[1], "--version"))
1557     {
1558       fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1559       return 0;
1560     }
1561   else if (argc > 1 && !strcmp (argv[1], "--help"))
1562     {
1563       show_help (stdout);
1564       return 0;
1565     }
1566
1567   while((arg=getopt(argc,argv,"hVo:"))!=-1)
1568     switch(arg)
1569       {
1570       default:
1571       case 'h':
1572         show_help (console);
1573         return KEYSERVER_OK;
1574
1575       case 'V':
1576         fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1577         return KEYSERVER_OK;
1578
1579       case 'o':
1580         output=fopen(optarg,"w");
1581         if(output==NULL)
1582           {
1583             fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1584                     optarg,strerror(errno));
1585             return KEYSERVER_INTERNAL_ERROR;
1586           }
1587
1588         break;
1589       }
1590
1591   if(argc>optind)
1592     {
1593       input=fopen(argv[optind],"r");
1594       if(input==NULL)
1595         {
1596           fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1597                   argv[optind],strerror(errno));
1598           return KEYSERVER_INTERNAL_ERROR;
1599         }
1600     }
1601
1602   if(input==NULL)
1603     input=stdin;
1604
1605   if(output==NULL)
1606     output=stdout;
1607
1608   opt=init_ks_options();
1609   if(!opt)
1610     return KEYSERVER_NO_MEMORY;
1611
1612   /* Get the command and info block */
1613
1614   while(fgets(line,MAX_LINE,input)!=NULL)
1615     {
1616       char optionstr[MAX_OPTION+1];
1617
1618       if(line[0]=='\n')
1619         break;
1620
1621       err=parse_ks_options(line,opt);
1622       if(err>0)
1623         {
1624           ret=err;
1625           goto fail;
1626         }
1627       else if(err==0)
1628         continue;
1629
1630       if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1631         {
1632           int no=0;
1633           char *start=&optionstr[0];
1634
1635           optionstr[MAX_OPTION]='\0';
1636
1637           if(strncasecmp(optionstr,"no-",3)==0)
1638             {
1639               no=1;
1640               start=&optionstr[3];
1641             }
1642
1643           if(strncasecmp(start,"tls",3)==0)
1644             {
1645               if(no)
1646                 use_tls=0;
1647               else if(start[3]=='=')
1648                 {
1649                   if(strcasecmp(&start[4],"no")==0)
1650                     use_tls=0;
1651                   else if(strcasecmp(&start[4],"try")==0)
1652                     use_tls=1;
1653                   else if(strcasecmp(&start[4],"warn")==0)
1654                     use_tls=2;
1655                   else if(strcasecmp(&start[4],"require")==0)
1656                     use_tls=3;
1657                   else
1658                     use_tls=1;
1659                 }
1660               else if(start[3]=='\0')
1661                 use_tls=1;
1662             }
1663           else if(strncasecmp(start,"basedn",6)==0)
1664             {
1665               if(no)
1666                 {
1667                   free(basekeyspacedn);
1668                   basekeyspacedn=NULL;
1669                 }
1670               else if(start[6]=='=')
1671                 {
1672                   free(basekeyspacedn);
1673                   basekeyspacedn=strdup(&start[7]);
1674                   if(!basekeyspacedn)
1675                     {
1676                       fprintf(console,"gpgkeys: out of memory while creating "
1677                               "base DN\n");
1678                       ret=KEYSERVER_NO_MEMORY;
1679                       goto fail;
1680                     }
1681
1682                   real_ldap=1;
1683                 }
1684             }
1685
1686           continue;
1687         }
1688     }
1689
1690   if(!opt->scheme)
1691     {
1692       fprintf(console,"gpgkeys: no scheme supplied!\n");
1693       ret=KEYSERVER_SCHEME_NOT_FOUND;
1694       goto fail;
1695     }
1696
1697   if(strcasecmp(opt->scheme,"ldaps")==0)
1698     {
1699       port=636;
1700       use_ssl=1;
1701     }
1702
1703   if(opt->port)
1704     port=atoi(opt->port);
1705
1706   if(!opt->host)
1707     {
1708       fprintf(console,"gpgkeys: no keyserver host provided\n");
1709       goto fail;
1710     }
1711
1712   if(opt->timeout && register_timeout()==-1)
1713     {
1714       fprintf(console,"gpgkeys: unable to register timeout handler\n");
1715       return KEYSERVER_INTERNAL_ERROR;
1716     }
1717
1718 #if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS_CACERTFILE)
1719   if(opt->ca_cert_file)
1720     {
1721       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
1722       if(err!=LDAP_SUCCESS)
1723         {
1724           fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
1725                   ldap_err2string(err));
1726           ret=KEYSERVER_INTERNAL_ERROR;
1727           goto fail;
1728         }
1729     }
1730 #endif /* HAVE_LDAP_SET_OPTION && LDAP_OPT_X_TLS_CACERTFILE */
1731
1732   /* SSL trumps TLS */
1733   if(use_ssl)
1734     use_tls=0;
1735
1736   /* If it's a GET or a SEARCH, the next thing to come in is the
1737      keyids.  If it's a SEND, then there are no keyids. */
1738
1739   if(opt->action==KS_SEND)
1740     while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
1741   else if(opt->action==KS_GET || opt->action==KS_SEARCH)
1742     {
1743       for(;;)
1744         {
1745           struct keylist *work;
1746
1747           if(fgets(line,MAX_LINE,input)==NULL)
1748             break;
1749           else
1750             {
1751               if(line[0]=='\n' || line[0]=='\0')
1752                 break;
1753
1754               work=malloc(sizeof(struct keylist));
1755               if(work==NULL)
1756                 {
1757                   fprintf(console,"gpgkeys: out of memory while "
1758                           "building key list\n");
1759                   ret=KEYSERVER_NO_MEMORY;
1760                   goto fail;
1761                 }
1762
1763               strcpy(work->str,line);
1764
1765               /* Trim the trailing \n */
1766               work->str[strlen(line)-1]='\0';
1767
1768               work->next=NULL;
1769
1770               /* Always attach at the end to keep the list in proper
1771                  order for searching */
1772               if(keylist==NULL)
1773                 keylist=work;
1774               else
1775                 keyptr->next=work;
1776
1777               keyptr=work;
1778             }
1779         }
1780     }
1781   else
1782     {
1783       fprintf(console,"gpgkeys: no keyserver command specified\n");
1784       goto fail;
1785     }
1786
1787   /* Send the response */
1788
1789   fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1790   fprintf(output,"PROGRAM %s\n\n",VERSION);
1791
1792   if(opt->verbose>1)
1793     {
1794       fprintf(console,"Host:\t\t%s\n",opt->host);
1795       if(port)
1796         fprintf(console,"Port:\t\t%d\n",port);
1797       fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
1798     }
1799
1800   if(opt->debug)
1801     {
1802 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
1803       err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
1804       if(err!=LDAP_SUCCESS)
1805         fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
1806                 ldap_err2string(err));
1807       else
1808         fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
1809 #else
1810       fprintf(console,"gpgkeys: not built with debugging support\n");
1811 #endif
1812     }
1813
1814   /* We have a timeout set for the setup stuff since it could time out
1815      as well. */
1816   set_timeout(opt->timeout);
1817
1818   /* Note that this tries all A records on a given host (or at least,
1819      OpenLDAP does). */
1820   ldap=ldap_init(opt->host,port);
1821   if(ldap==NULL)
1822     {
1823       fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
1824               strerror(errno));
1825       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
1826       goto fail;
1827     }
1828
1829   if(use_ssl)
1830     {
1831 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
1832       int ssl=LDAP_OPT_X_TLS_HARD;
1833
1834       err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
1835       if(err!=LDAP_SUCCESS)
1836         {
1837           fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
1838                   ldap_err2string(err));
1839           fail_all(keylist,ldap_err_to_gpg_err(err));
1840           goto fail;
1841         }
1842
1843       if(!opt->flags.check_cert)
1844         ssl=LDAP_OPT_X_TLS_NEVER;
1845
1846       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
1847       if(err!=LDAP_SUCCESS)
1848         {
1849           fprintf(console,
1850                   "gpgkeys: unable to set certificate validation: %s\n",
1851                   ldap_err2string(err));
1852           fail_all(keylist,ldap_err_to_gpg_err(err));
1853           goto fail;
1854         }
1855 #else
1856       fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
1857               "not built with LDAPS support");
1858       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
1859       goto fail;
1860 #endif
1861     }
1862
1863   if(!basekeyspacedn)
1864     if((err=find_basekeyspacedn()) || !basekeyspacedn)
1865       {
1866         fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
1867                 err?ldap_err2string(err):"not found");
1868         fail_all(keylist,ldap_err_to_gpg_err(err));
1869         goto fail;
1870       }
1871
1872   /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
1873      3=force use. */
1874   if(use_tls)
1875     {
1876       if(!real_ldap)
1877         {
1878           if(use_tls>=2)
1879             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
1880                     "not supported by the NAI LDAP keyserver");
1881           if(use_tls==3)
1882             {
1883               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
1884               goto fail;
1885             }
1886         }
1887       else
1888         {
1889 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
1890           int ver=LDAP_VERSION3;
1891
1892           err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
1893           if(err==LDAP_SUCCESS)
1894             {
1895               if(opt->flags.check_cert)
1896                 ver=LDAP_OPT_X_TLS_HARD;
1897               else
1898                 ver=LDAP_OPT_X_TLS_NEVER;
1899
1900               err=ldap_set_option(ldap,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
1901               if(err==LDAP_SUCCESS)
1902                 err=ldap_start_tls_s(ldap,NULL,NULL);
1903             }
1904
1905           if(err!=LDAP_SUCCESS)
1906             {
1907               if(use_tls>=2 || opt->verbose>2)
1908                 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
1909                         ldap_err2string(err));
1910               /* Are we forcing it? */
1911               if(use_tls==3)
1912                 {
1913                   fail_all(keylist,ldap_err_to_gpg_err(err));
1914                   goto fail;
1915                 }
1916             }
1917           else if(err==LDAP_SUCCESS && opt->verbose>1)
1918             fprintf(console,"gpgkeys: TLS started successfully.\n");
1919 #else
1920           if(use_tls>=2)
1921             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
1922                     "not built with TLS support");
1923           if(use_tls==3)
1924             {
1925               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
1926               goto fail;
1927             }
1928 #endif
1929         }
1930     }
1931
1932 #if 0
1933   /* The LDAP keyserver doesn't require this, but it might be useful
1934      if someone stores keys on a V2 LDAP server somewhere.  (V3
1935      doesn't require a bind).  Leave this out for now since it is not
1936      clear if anyone's server we're likely to use really cares, plus
1937      there are some servers that don't allow it. */
1938
1939   err=ldap_simple_bind_s(ldap,NULL,NULL);
1940   if(err!=0)
1941     {
1942       fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
1943               ldap_err2string(err));
1944       fail_all(keylist,ldap_err_to_gpg_err(err));
1945       goto fail;
1946     }
1947   else
1948     bound=1;
1949 #endif
1950
1951   if(opt->action==KS_GET)
1952     {
1953       keyptr=keylist;
1954
1955       while(keyptr!=NULL)
1956         {
1957           set_timeout(opt->timeout);
1958
1959           if(get_key(keyptr->str)!=KEYSERVER_OK)
1960             failed++;
1961
1962           keyptr=keyptr->next;
1963         }
1964     }
1965   else if(opt->action==KS_SEND)
1966     {
1967       int eof=0;
1968
1969       do
1970         {
1971           set_timeout(opt->timeout);
1972
1973           if(real_ldap)
1974             {
1975               if(send_key(&eof)!=KEYSERVER_OK)
1976                 failed++;
1977             }
1978           else
1979             {
1980               if(send_key_keyserver(&eof)!=KEYSERVER_OK)
1981                 failed++;
1982             }
1983         }
1984       while(!eof);
1985     }
1986   else if(opt->action==KS_SEARCH)
1987     {
1988       char *searchkey=NULL;
1989       int len=0;
1990
1991       set_timeout(opt->timeout);
1992
1993       /* To search, we stick a * in between each key to search for.
1994          This means that if the user enters words, they'll get
1995          "enters*words".  If the user "enters words", they'll get
1996          "enters words" */
1997
1998       keyptr=keylist;
1999       while(keyptr!=NULL)
2000         {
2001           len+=strlen(keyptr->str)+1;
2002           keyptr=keyptr->next;
2003         }
2004
2005       searchkey=malloc(len+1);
2006       if(searchkey==NULL)
2007         {
2008           ret=KEYSERVER_NO_MEMORY;
2009           fail_all(keylist,KEYSERVER_NO_MEMORY);
2010           goto fail;
2011         }
2012
2013       searchkey[0]='\0';
2014
2015       keyptr=keylist;
2016       while(keyptr!=NULL)
2017         {
2018           strcat(searchkey,keyptr->str);
2019           strcat(searchkey,"*");
2020           keyptr=keyptr->next;
2021         }
2022
2023       /* Nail that last "*" */
2024       if(*searchkey)
2025         searchkey[strlen(searchkey)-1]='\0';
2026
2027       if(search_key(searchkey)!=KEYSERVER_OK)
2028         failed++;
2029
2030       free(searchkey);
2031     }
2032   else
2033     BUG();
2034
2035   if(!failed)
2036     ret=KEYSERVER_OK;
2037
2038  fail:
2039
2040   while(keylist!=NULL)
2041     {
2042       struct keylist *current=keylist;
2043       keylist=keylist->next;
2044       free(current);
2045     }
2046
2047   if(input!=stdin)
2048     fclose(input);
2049
2050   if(output!=stdout)
2051     fclose(output);
2052
2053   free_ks_options(opt);
2054
2055   if(ldap!=NULL && bound)
2056     ldap_unbind_s(ldap);
2057
2058   free(basekeyspacedn);
2059
2060   return ret;
2061 }