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