* keyserver.c (parse_keyserver_uri): If there is a path present, set the
[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 #define LDAP_ESCAPE_CHARS "*()\\"
1120
1121 static int
1122 ldap_quote(char *buffer,const char *string)
1123 {
1124   int count=0;
1125
1126   for(;*string;string++)
1127     {
1128       if(strchr(LDAP_ESCAPE_CHARS,*string))
1129         {
1130           if(buffer)
1131             {
1132               sprintf(buffer,"\\%02X",*string);
1133               buffer+=3;
1134             }
1135
1136           count+=3;
1137         }
1138       else
1139         {
1140           if(buffer)
1141             *buffer++=*string;
1142
1143           count++;
1144         }
1145     }
1146
1147   if(buffer)
1148     *buffer='\0';
1149
1150   return count;
1151 }
1152
1153 /* Note that key-not-found is not a fatal error */
1154 static int
1155 get_name(char *getkey)
1156 {
1157   LDAPMessage *res,*each;
1158   int ret=KEYSERVER_INTERNAL_ERROR,err,count;
1159   char *expanded_search;
1160   /* The maximum size of the search, including the optional stuff and
1161      the trailing \0 */
1162   char search[2+11+3+MAX_LINE+2+15+14+1+1+20];
1163   /* This ordering is significant - specifically, "pgpcertid" needs to
1164      be the second item in the list, since everything after it may be
1165      discarded if the user isn't in verbose mode. */
1166   char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
1167                  "pgpdisabled","pgpkeycreatetime","modifytimestamp",
1168                  "pgpkeysize","pgpkeytype",NULL};
1169   attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1170                          array initializers. */
1171
1172   expanded_search=malloc(ldap_quote(NULL,getkey)+1);
1173   if(!expanded_search)
1174     {
1175       fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_NO_MEMORY);
1176       fprintf(console,"Out of memory when quoting LDAP search string\n");
1177       return KEYSERVER_NO_MEMORY;
1178     }
1179
1180   ldap_quote(expanded_search,getkey);
1181
1182   /* Build the search string */
1183
1184   sprintf(search,"%s(pgpuserid=*%s*)%s%s%s",
1185           (!(opt->flags.include_disabled&&opt->flags.include_revoked))?"(&":"",
1186           expanded_search,
1187           opt->flags.include_disabled?"":"(pgpdisabled=0)",
1188           opt->flags.include_revoked?"":"(pgprevoked=0)",
1189           !(opt->flags.include_disabled&&opt->flags.include_revoked)?")":"");
1190
1191   free(expanded_search);
1192
1193   if(opt->verbose>2)
1194     fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1195
1196   if(!opt->verbose)
1197     attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1198
1199   err=ldap_search_s(ldap,basekeyspacedn,
1200                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1201   if(err!=0)
1202     {
1203       int errtag=ldap_err_to_gpg_err(err);
1204
1205       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1206       fprintf(output,"NAME %s BEGIN\n",getkey);
1207       fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1208       return errtag;
1209     }
1210
1211   count=ldap_count_entries(ldap,res);
1212   if(count<1)
1213     {
1214       fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1215       fprintf(output,"NAME %s BEGIN\n",getkey);
1216       fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1217     }
1218   else
1219     {
1220       /* There may be more than one result, but we return them all. */
1221
1222       each=ldap_first_entry(ldap,res);
1223       while(each!=NULL)
1224         {
1225           char **vals,**certid;
1226
1227           certid=ldap_get_values(ldap,each,"pgpcertid");
1228           if(certid!=NULL)
1229             {
1230               build_info(certid[0],each);
1231
1232               fprintf(output,"NAME %s BEGIN\n",getkey);
1233
1234               vals=ldap_get_values(ldap,each,pgpkeystr);
1235               if(vals==NULL)
1236                 {
1237                   int errtag=ldap_to_gpg_err(ldap);
1238
1239                   fprintf(console,"gpgkeys: unable to retrieve key %s "
1240                           "from keyserver\n",getkey);
1241                   fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1242                 }
1243               else
1244                 {
1245                   print_nocr(output,vals[0]);
1246                   fprintf(output,"\nNAME %s END\n",getkey);
1247
1248                   ldap_value_free(vals);
1249                 }
1250
1251               ldap_value_free(certid);
1252             }
1253
1254           each=ldap_next_entry(ldap,each);
1255         }
1256     }
1257
1258   ret=KEYSERVER_OK;
1259
1260   ldap_msgfree(res);
1261
1262   return ret;
1263 }
1264
1265 static void
1266 printquoted(FILE *stream,char *string,char delim)
1267 {
1268   while(*string)
1269     {
1270       if(*string==delim || *string=='%')
1271         fprintf(stream,"%%%02x",*string);
1272       else
1273         fputc(*string,stream);
1274
1275       string++;
1276     }
1277 }
1278
1279 /* Returns 0 on success and -1 on error.  Note that key-not-found is
1280    not an error! */
1281 static int
1282 search_key(const char *searchkey)
1283 {
1284   char **vals;
1285   LDAPMessage *res,*each;
1286   int err,count=0;
1287   struct keylist *dupelist=NULL;
1288   char *expanded_search;
1289   /* The maximum size of the search, including the optional stuff and
1290      the trailing \0 */
1291   char search[2+11+3+MAX_LINE+2+15+14+1+1+20];
1292   char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1293                  "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1294                  "pgpkeysize","pgpkeytype",NULL};
1295   enum ks_search_type search_type;
1296
1297   fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1298
1299   search_type=classify_ks_search(&searchkey);
1300
1301   if(opt->debug)
1302     fprintf(console,"search type is %d, and key is \"%s\"\n",
1303             search_type,searchkey);
1304
1305   expanded_search=malloc(ldap_quote(NULL,searchkey)+1);
1306   if(!expanded_search)
1307     {
1308       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,KEYSERVER_NO_MEMORY);
1309       fprintf(console,"Out of memory when quoting LDAP search string\n");
1310       return KEYSERVER_NO_MEMORY;
1311     }
1312
1313   ldap_quote(expanded_search,searchkey);
1314
1315   /* Build the search string */
1316
1317   sprintf(search,"%s(pgpuserid=%s%s%s)%s%s%s",
1318           (!(opt->flags.include_disabled&&opt->flags.include_revoked))?"(&":"",
1319           (search_type==KS_SEARCH_EXACT)?"":
1320           (search_type==KS_SEARCH_MAILSUB)?"*<*":"*",
1321           expanded_search,
1322           (search_type==KS_SEARCH_EXACT
1323            || search_type==KS_SEARCH_MAIL)?"":
1324           (search_type==KS_SEARCH_MAILSUB)?"*>":"*",
1325           opt->flags.include_disabled?"":"(pgpdisabled=0)",
1326           opt->flags.include_revoked?"":"(pgprevoked=0)",
1327           !(opt->flags.include_disabled&&opt->flags.include_revoked)?")":"");
1328
1329   free(expanded_search);
1330
1331   if(opt->verbose>2)
1332     fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1333
1334   err=ldap_search_s(ldap,basekeyspacedn,
1335                     LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1336   if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1337     {
1338       int errtag=ldap_err_to_gpg_err(err);
1339
1340       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1341       fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1342       return errtag;
1343     }
1344
1345   /* The LDAP server doesn't return a real count of unique keys, so we
1346      can't use ldap_count_entries here. */
1347   each=ldap_first_entry(ldap,res);
1348   while(each!=NULL)
1349     {
1350       char **certid=ldap_get_values(ldap,each,"pgpcertid");
1351
1352       if(certid!=NULL)
1353         {
1354           if(!key_in_keylist(certid[0],dupelist))
1355             {
1356               int rc=add_key_to_keylist(certid[0],&dupelist);
1357               if(rc!=0)
1358                 {
1359                   fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1360                   free_keylist(dupelist);
1361                   return rc;
1362                 }
1363
1364               count++;
1365             }
1366         }
1367
1368       each=ldap_next_entry(ldap,each);
1369     }
1370
1371   if(err==LDAP_SIZELIMIT_EXCEEDED)
1372     {
1373       if(count==1)
1374         fprintf(console,"gpgkeys: search results exceeded server limit."
1375                 "  First %d result shown.\n",count);
1376       else
1377         fprintf(console,"gpgkeys: search results exceeded server limit."
1378                 "  First %d results shown.\n",count);
1379     }
1380
1381   free_keylist(dupelist);
1382   dupelist=NULL;
1383
1384   if(count<1)
1385     fprintf(output,"info:1:0\n");
1386   else
1387     {
1388       fprintf(output,"info:1:%d\n",count);
1389
1390       each=ldap_first_entry(ldap,res);
1391       while(each!=NULL)
1392         {
1393           char **certid;
1394
1395           certid=ldap_get_values(ldap,each,"pgpcertid");
1396           if(certid!=NULL)
1397             {
1398               LDAPMessage *uids;
1399
1400               /* Have we seen this certid before? */
1401               if(!key_in_keylist(certid[0],dupelist))
1402                 {
1403                   int rc=add_key_to_keylist(certid[0],&dupelist);
1404                   if(rc)
1405                     {
1406                       fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1407                       free_keylist(dupelist);
1408                       ldap_value_free(certid);
1409                       ldap_msgfree(res);
1410                       return rc;
1411                     }
1412
1413                   fprintf(output,"pub:%s:",certid[0]);
1414
1415                   vals=ldap_get_values(ldap,each,"pgpkeytype");
1416                   if(vals!=NULL)
1417                     {
1418                       /* The LDAP server doesn't exactly handle this
1419                          well. */
1420                       if(strcasecmp(vals[0],"RSA")==0)
1421                         fprintf(output,"1");
1422                       else if(strcasecmp(vals[0],"DSS/DH")==0)
1423                         fprintf(output,"17");
1424                       ldap_value_free(vals);
1425                     }
1426
1427                   fputc(':',output);
1428
1429                   vals=ldap_get_values(ldap,each,"pgpkeysize");
1430                   if(vals!=NULL)
1431                     {
1432                       /* Not sure why, but some keys are listed with a
1433                          key size of 0.  Treat that like an
1434                          unknown. */
1435                       if(atoi(vals[0])>0)
1436                         fprintf(output,"%d",atoi(vals[0]));
1437                       ldap_value_free(vals);
1438                     }
1439
1440                   fputc(':',output);
1441
1442                   /* YYYYMMDDHHmmssZ */
1443
1444                   vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1445                   if(vals!=NULL && strlen(vals[0])==15)
1446                     {
1447                       fprintf(output,"%u",
1448                               (unsigned int)ldap2epochtime(vals[0]));
1449                       ldap_value_free(vals);
1450                     }
1451
1452                   fputc(':',output);
1453
1454                   vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
1455                   if(vals!=NULL && strlen(vals[0])==15)
1456                     {
1457                       fprintf(output,"%u",
1458                               (unsigned int)ldap2epochtime(vals[0]));
1459                       ldap_value_free(vals);
1460                     }
1461
1462                   fputc(':',output);
1463
1464                   vals=ldap_get_values(ldap,each,"pgprevoked");
1465                   if(vals!=NULL)
1466                     {
1467                       if(atoi(vals[0])==1)
1468                         fprintf(output,"r");
1469                       ldap_value_free(vals);
1470                     }
1471
1472                   vals=ldap_get_values(ldap,each,"pgpdisabled");
1473                   if(vals!=NULL)
1474                     {
1475                       if(atoi(vals[0])==1)
1476                         fprintf(output,"d");
1477                       ldap_value_free(vals);
1478                     }
1479
1480 #if 0
1481                   /* This is not yet specified in the keyserver
1482                      protocol, but may be someday. */
1483                   fputc(':',output);
1484
1485                   vals=ldap_get_values(ldap,each,"modifytimestamp");
1486                   if(vals!=NULL && strlen(vals[0])==15)
1487                     {
1488                       fprintf(output,"%u",
1489                               (unsigned int)ldap2epochtime(vals[0]));
1490                       ldap_value_free(vals);
1491                     }
1492 #endif
1493
1494                   fprintf(output,"\n");
1495
1496                   /* Now print all the uids that have this certid */
1497                   uids=ldap_first_entry(ldap,res);
1498                   while(uids!=NULL)
1499                     {
1500                       vals=ldap_get_values(ldap,uids,"pgpcertid");
1501                       if(vals!=NULL)
1502                         {
1503                           if(strcasecmp(certid[0],vals[0])==0)
1504                             {
1505                               char **uidvals;
1506
1507                               fprintf(output,"uid:");
1508
1509                               uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1510                               if(uidvals!=NULL)
1511                                 {
1512                                   /* Need to escape any colons */
1513                                   printquoted(output,uidvals[0],':');
1514                                   ldap_value_free(uidvals);
1515                                 }
1516
1517                               fprintf(output,"\n");
1518                             }
1519
1520                           ldap_value_free(vals);
1521                         }
1522
1523                       uids=ldap_next_entry(ldap,uids);
1524                     }
1525                 }
1526
1527               ldap_value_free(certid);
1528             }
1529
1530           each=ldap_next_entry(ldap,each);
1531         }
1532     }
1533
1534   ldap_msgfree(res);
1535   free_keylist(dupelist);
1536
1537   fprintf(output,"SEARCH %s END\n",searchkey);
1538
1539   return KEYSERVER_OK;
1540 }
1541
1542 static void
1543 fail_all(struct keylist *keylist,int err)
1544 {
1545   if(!keylist)
1546     return;
1547
1548   if(opt->action==KS_SEARCH)
1549     {
1550       fprintf(output,"SEARCH ");
1551       while(keylist)
1552         {
1553           fprintf(output,"%s ",keylist->str);
1554           keylist=keylist->next;
1555         }
1556       fprintf(output,"FAILED %d\n",err);
1557     }
1558   else
1559     while(keylist)
1560       {
1561         fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1562         keylist=keylist->next;
1563       }
1564 }
1565
1566 static int
1567 find_basekeyspacedn(void)
1568 {
1569   int err,i;
1570   char *attr[]={"namingContexts",NULL,NULL,NULL};
1571   LDAPMessage *res;
1572   char **context;
1573
1574   /* Look for namingContexts */
1575   err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1576   if(err==LDAP_SUCCESS)
1577     {
1578       context=ldap_get_values(ldap,res,"namingContexts");
1579       if(context)
1580         {
1581           attr[0]="pgpBaseKeySpaceDN";
1582           attr[1]="pgpVersion";
1583           attr[2]="pgpSoftware";
1584
1585           real_ldap=1;
1586
1587           /* We found some, so try each namingContext as the search base
1588              and look for pgpBaseKeySpaceDN.  Because we found this, we
1589              know we're talking to a regular-ish LDAP server and not a
1590              LDAP keyserver. */
1591
1592           for(i=0;context[i] && !basekeyspacedn;i++)
1593             {
1594               char **vals;
1595               LDAPMessage *si_res;
1596               char *object;
1597
1598               object=malloc(17+strlen(context[i])+1);
1599               if(!object)
1600                 return -1;
1601
1602               strcpy(object,"cn=pgpServerInfo,");
1603               strcat(object,context[i]);
1604
1605               err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1606                                 "(objectClass=*)",attr,0,&si_res);
1607               free(object);
1608
1609               if(err==LDAP_NO_SUCH_OBJECT)
1610                 continue;
1611               else if(err!=LDAP_SUCCESS)
1612                 return err;
1613
1614               vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1615               if(vals)
1616                 {
1617                   basekeyspacedn=strdup(vals[0]);
1618                   ldap_value_free(vals);
1619                 }
1620
1621               if(opt->verbose>1)
1622                 {
1623                   vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1624                   if(vals)
1625                     {
1626                       fprintf(console,"Server: \t%s\n",vals[0]);
1627                       ldap_value_free(vals);
1628                     }
1629
1630                   vals=ldap_get_values(ldap,si_res,"pgpVersion");
1631                   if(vals)
1632                     {
1633                       fprintf(console,"Version:\t%s\n",vals[0]);
1634                       ldap_value_free(vals);
1635                     }
1636                 }
1637
1638               ldap_msgfree(si_res);
1639             }
1640
1641           ldap_value_free(context);
1642         }
1643
1644       ldap_msgfree(res);
1645     }
1646   else
1647     {
1648       /* We don't have an answer yet, which means the server might be
1649          a LDAP keyserver. */
1650       char **vals;
1651       LDAPMessage *si_res;
1652
1653       attr[0]="pgpBaseKeySpaceDN";
1654       attr[1]="version";
1655       attr[2]="software";
1656
1657       err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1658                         "(objectClass=*)",attr,0,&si_res);
1659       if(err!=LDAP_SUCCESS)
1660         return err;
1661
1662       /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1663          KEYSPACE,C=US", but it might not be in the future. */
1664
1665       vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1666       if(vals)
1667         {
1668           basekeyspacedn=strdup(vals[0]);
1669           ldap_value_free(vals);
1670         }
1671
1672       if(opt->verbose>1)
1673         {
1674           vals=ldap_get_values(ldap,si_res,"software");
1675           if(vals)
1676             {
1677               fprintf(console,"Server: \t%s\n",vals[0]);
1678               ldap_value_free(vals);
1679             }
1680         }
1681
1682       vals=ldap_get_values(ldap,si_res,"version");
1683       if(vals)
1684         {
1685           if(opt->verbose>1)
1686             fprintf(console,"Version:\t%s\n",vals[0]);
1687
1688           /* If the version is high enough, use the new pgpKeyV2
1689              attribute.  This design if iffy at best, but it matches how
1690              PGP does it.  I figure the NAI folks assumed that there would
1691              never be a LDAP keyserver vendor with a different numbering
1692              scheme. */
1693           if(atoi(vals[0])>1)
1694             pgpkeystr="pgpKeyV2";
1695
1696           ldap_value_free(vals);
1697         }
1698
1699       ldap_msgfree(si_res);
1700     }   
1701
1702   return LDAP_SUCCESS;
1703 }
1704
1705 static void 
1706 show_help (FILE *fp)
1707 {
1708   fprintf (fp,"-h\thelp\n");
1709   fprintf (fp,"-V\tversion\n");
1710   fprintf (fp,"-o\toutput to this file\n");
1711 }
1712
1713 int
1714 main(int argc,char *argv[])
1715 {
1716   int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1717   char line[MAX_LINE];
1718   int failed=0,use_ssl=0,use_tls=0,bound=0;
1719   struct keylist *keylist=NULL,*keyptr=NULL;
1720
1721   console=stderr;
1722
1723   /* Kludge to implement standard GNU options.  */
1724   if (argc > 1 && !strcmp (argv[1], "--version"))
1725     {
1726       fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1727       return 0;
1728     }
1729   else if (argc > 1 && !strcmp (argv[1], "--help"))
1730     {
1731       show_help (stdout);
1732       return 0;
1733     }
1734
1735   while((arg=getopt(argc,argv,"hVo:"))!=-1)
1736     switch(arg)
1737       {
1738       default:
1739       case 'h':
1740         show_help (console);
1741         return KEYSERVER_OK;
1742
1743       case 'V':
1744         fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1745         return KEYSERVER_OK;
1746
1747       case 'o':
1748         output=fopen(optarg,"w");
1749         if(output==NULL)
1750           {
1751             fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1752                     optarg,strerror(errno));
1753             return KEYSERVER_INTERNAL_ERROR;
1754           }
1755
1756         break;
1757       }
1758
1759   if(argc>optind)
1760     {
1761       input=fopen(argv[optind],"r");
1762       if(input==NULL)
1763         {
1764           fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1765                   argv[optind],strerror(errno));
1766           return KEYSERVER_INTERNAL_ERROR;
1767         }
1768     }
1769
1770   if(input==NULL)
1771     input=stdin;
1772
1773   if(output==NULL)
1774     output=stdout;
1775
1776   opt=init_ks_options();
1777   if(!opt)
1778     return KEYSERVER_NO_MEMORY;
1779
1780   /* Get the command and info block */
1781
1782   while(fgets(line,MAX_LINE,input)!=NULL)
1783     {
1784       char optionstr[MAX_OPTION+1];
1785
1786       if(line[0]=='\n')
1787         break;
1788
1789       err=parse_ks_options(line,opt);
1790       if(err>0)
1791         {
1792           ret=err;
1793           goto fail;
1794         }
1795       else if(err==0)
1796         continue;
1797
1798       if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1799         {
1800           int no=0;
1801           char *start=&optionstr[0];
1802
1803           optionstr[MAX_OPTION]='\0';
1804
1805           if(strncasecmp(optionstr,"no-",3)==0)
1806             {
1807               no=1;
1808               start=&optionstr[3];
1809             }
1810
1811           if(strncasecmp(start,"tls",3)==0)
1812             {
1813               if(no)
1814                 use_tls=0;
1815               else if(start[3]=='=')
1816                 {
1817                   if(strcasecmp(&start[4],"no")==0)
1818                     use_tls=0;
1819                   else if(strcasecmp(&start[4],"try")==0)
1820                     use_tls=1;
1821                   else if(strcasecmp(&start[4],"warn")==0)
1822                     use_tls=2;
1823                   else if(strcasecmp(&start[4],"require")==0)
1824                     use_tls=3;
1825                   else
1826                     use_tls=1;
1827                 }
1828               else if(start[3]=='\0')
1829                 use_tls=1;
1830             }
1831           else if(strncasecmp(start,"basedn",6)==0)
1832             {
1833               if(no)
1834                 {
1835                   free(basekeyspacedn);
1836                   basekeyspacedn=NULL;
1837                 }
1838               else if(start[6]=='=')
1839                 {
1840                   free(basekeyspacedn);
1841                   basekeyspacedn=strdup(&start[7]);
1842                   if(!basekeyspacedn)
1843                     {
1844                       fprintf(console,"gpgkeys: out of memory while creating "
1845                               "base DN\n");
1846                       ret=KEYSERVER_NO_MEMORY;
1847                       goto fail;
1848                     }
1849
1850                   real_ldap=1;
1851                 }
1852             }
1853
1854           continue;
1855         }
1856     }
1857
1858   if(!opt->scheme)
1859     {
1860       fprintf(console,"gpgkeys: no scheme supplied!\n");
1861       ret=KEYSERVER_SCHEME_NOT_FOUND;
1862       goto fail;
1863     }
1864
1865   if(strcasecmp(opt->scheme,"ldaps")==0)
1866     {
1867       port=636;
1868       use_ssl=1;
1869     }
1870
1871   if(opt->port)
1872     port=atoi(opt->port);
1873
1874   if(!opt->host)
1875     {
1876       fprintf(console,"gpgkeys: no keyserver host provided\n");
1877       goto fail;
1878     }
1879
1880   if(opt->timeout && register_timeout()==-1)
1881     {
1882       fprintf(console,"gpgkeys: unable to register timeout handler\n");
1883       return KEYSERVER_INTERNAL_ERROR;
1884     }
1885
1886 #if defined(HAVE_LDAP_SET_OPTION) && defined(LDAP_OPT_X_TLS_CACERTFILE)
1887   if(opt->ca_cert_file)
1888     {
1889       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
1890       if(err!=LDAP_SUCCESS)
1891         {
1892           fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
1893                   ldap_err2string(err));
1894           ret=KEYSERVER_INTERNAL_ERROR;
1895           goto fail;
1896         }
1897     }
1898 #endif /* HAVE_LDAP_SET_OPTION && LDAP_OPT_X_TLS_CACERTFILE */
1899
1900   /* SSL trumps TLS */
1901   if(use_ssl)
1902     use_tls=0;
1903
1904   /* If it's a GET or a SEARCH, the next thing to come in is the
1905      keyids.  If it's a SEND, then there are no keyids. */
1906
1907   if(opt->action==KS_SEND)
1908     while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
1909   else if(opt->action==KS_GET
1910           || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
1911     {
1912       for(;;)
1913         {
1914           struct keylist *work;
1915
1916           if(fgets(line,MAX_LINE,input)==NULL)
1917             break;
1918           else
1919             {
1920               if(line[0]=='\n' || line[0]=='\0')
1921                 break;
1922
1923               work=malloc(sizeof(struct keylist));
1924               if(work==NULL)
1925                 {
1926                   fprintf(console,"gpgkeys: out of memory while "
1927                           "building key list\n");
1928                   ret=KEYSERVER_NO_MEMORY;
1929                   goto fail;
1930                 }
1931
1932               strcpy(work->str,line);
1933
1934               /* Trim the trailing \n */
1935               work->str[strlen(line)-1]='\0';
1936
1937               work->next=NULL;
1938
1939               /* Always attach at the end to keep the list in proper
1940                  order for searching */
1941               if(keylist==NULL)
1942                 keylist=work;
1943               else
1944                 keyptr->next=work;
1945
1946               keyptr=work;
1947             }
1948         }
1949     }
1950   else
1951     {
1952       fprintf(console,"gpgkeys: no keyserver command specified\n");
1953       goto fail;
1954     }
1955
1956   /* Send the response */
1957
1958   fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1959   fprintf(output,"PROGRAM %s\n\n",VERSION);
1960
1961   if(opt->verbose>1)
1962     {
1963       fprintf(console,"Host:\t\t%s\n",opt->host);
1964       if(port)
1965         fprintf(console,"Port:\t\t%d\n",port);
1966       fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
1967     }
1968
1969   if(opt->debug)
1970     {
1971 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
1972       err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
1973       if(err!=LDAP_SUCCESS)
1974         fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
1975                 ldap_err2string(err));
1976       else
1977         fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
1978 #else
1979       fprintf(console,"gpgkeys: not built with debugging support\n");
1980 #endif
1981     }
1982
1983   /* We have a timeout set for the setup stuff since it could time out
1984      as well. */
1985   set_timeout(opt->timeout);
1986
1987   /* Note that this tries all A records on a given host (or at least,
1988      OpenLDAP does). */
1989   ldap=ldap_init(opt->host,port);
1990   if(ldap==NULL)
1991     {
1992       fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
1993               strerror(errno));
1994       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
1995       goto fail;
1996     }
1997
1998   if(use_ssl)
1999     {
2000 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
2001       int ssl=LDAP_OPT_X_TLS_HARD;
2002
2003       err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
2004       if(err!=LDAP_SUCCESS)
2005         {
2006           fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2007                   ldap_err2string(err));
2008           fail_all(keylist,ldap_err_to_gpg_err(err));
2009           goto fail;
2010         }
2011
2012       if(!opt->flags.check_cert)
2013         ssl=LDAP_OPT_X_TLS_NEVER;
2014
2015       err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
2016       if(err!=LDAP_SUCCESS)
2017         {
2018           fprintf(console,
2019                   "gpgkeys: unable to set certificate validation: %s\n",
2020                   ldap_err2string(err));
2021           fail_all(keylist,ldap_err_to_gpg_err(err));
2022           goto fail;
2023         }
2024 #else
2025       fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2026               "not built with LDAPS support");
2027       fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2028       goto fail;
2029 #endif
2030     }
2031
2032   if(!basekeyspacedn)
2033     if((err=find_basekeyspacedn()) || !basekeyspacedn)
2034       {
2035         fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
2036                 err?ldap_err2string(err):"not found");
2037         fail_all(keylist,ldap_err_to_gpg_err(err));
2038         goto fail;
2039       }
2040
2041   /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
2042      3=force use. */
2043   if(use_tls)
2044     {
2045       if(!real_ldap)
2046         {
2047           if(use_tls>=2)
2048             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2049                     "not supported by the NAI LDAP keyserver");
2050           if(use_tls==3)
2051             {
2052               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2053               goto fail;
2054             }
2055         }
2056       else
2057         {
2058 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
2059           int ver=LDAP_VERSION3;
2060
2061           err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2062           if(err==LDAP_SUCCESS)
2063             {
2064               if(opt->flags.check_cert)
2065                 ver=LDAP_OPT_X_TLS_HARD;
2066               else
2067                 ver=LDAP_OPT_X_TLS_NEVER;
2068
2069               err=ldap_set_option(ldap,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
2070               if(err==LDAP_SUCCESS)
2071                 err=ldap_start_tls_s(ldap,NULL,NULL);
2072             }
2073
2074           if(err!=LDAP_SUCCESS)
2075             {
2076               if(use_tls>=2 || opt->verbose>2)
2077                 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2078                         ldap_err2string(err));
2079               /* Are we forcing it? */
2080               if(use_tls==3)
2081                 {
2082                   fail_all(keylist,ldap_err_to_gpg_err(err));
2083                   goto fail;
2084                 }
2085             }
2086           else if(err==LDAP_SUCCESS && opt->verbose>1)
2087             fprintf(console,"gpgkeys: TLS started successfully.\n");
2088 #else
2089           if(use_tls>=2)
2090             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2091                     "not built with TLS support");
2092           if(use_tls==3)
2093             {
2094               fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2095               goto fail;
2096             }
2097 #endif
2098         }
2099     }
2100
2101 #if 0
2102   /* The LDAP keyserver doesn't require this, but it might be useful
2103      if someone stores keys on a V2 LDAP server somewhere.  (V3
2104      doesn't require a bind).  Leave this out for now since it is not
2105      clear if anyone's server we're likely to use really cares, plus
2106      there are some servers that don't allow it. */
2107
2108   err=ldap_simple_bind_s(ldap,NULL,NULL);
2109   if(err!=0)
2110     {
2111       fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
2112               ldap_err2string(err));
2113       fail_all(keylist,ldap_err_to_gpg_err(err));
2114       goto fail;
2115     }
2116   else
2117     bound=1;
2118 #endif
2119
2120   if(opt->action==KS_GET)
2121     {
2122       keyptr=keylist;
2123
2124       while(keyptr!=NULL)
2125         {
2126           set_timeout(opt->timeout);
2127
2128           if(get_key(keyptr->str)!=KEYSERVER_OK)
2129             failed++;
2130
2131           keyptr=keyptr->next;
2132         }
2133     }
2134   else if(opt->action==KS_GETNAME)
2135     {
2136       keyptr=keylist;
2137
2138       while(keyptr!=NULL)
2139         {
2140           set_timeout(opt->timeout);
2141
2142           if(get_name(keyptr->str)!=KEYSERVER_OK)
2143             failed++;
2144
2145           keyptr=keyptr->next;
2146         }
2147     }
2148   else if(opt->action==KS_SEND)
2149     {
2150       int eof=0;
2151
2152       do
2153         {
2154           set_timeout(opt->timeout);
2155
2156           if(real_ldap)
2157             {
2158               if(send_key(&eof)!=KEYSERVER_OK)
2159                 failed++;
2160             }
2161           else
2162             {
2163               if(send_key_keyserver(&eof)!=KEYSERVER_OK)
2164                 failed++;
2165             }
2166         }
2167       while(!eof);
2168     }
2169   else if(opt->action==KS_SEARCH)
2170     {
2171       char *searchkey=NULL;
2172       int len=0;
2173
2174       set_timeout(opt->timeout);
2175
2176       /* To search, we stick a * in between each key to search for.
2177          This means that if the user enters words, they'll get
2178          "enters*words".  If the user "enters words", they'll get
2179          "enters words" */
2180
2181       keyptr=keylist;
2182       while(keyptr!=NULL)
2183         {
2184           len+=strlen(keyptr->str)+1;
2185           keyptr=keyptr->next;
2186         }
2187
2188       searchkey=malloc(len+1);
2189       if(searchkey==NULL)
2190         {
2191           ret=KEYSERVER_NO_MEMORY;
2192           fail_all(keylist,KEYSERVER_NO_MEMORY);
2193           goto fail;
2194         }
2195
2196       searchkey[0]='\0';
2197
2198       keyptr=keylist;
2199       while(keyptr!=NULL)
2200         {
2201           strcat(searchkey,keyptr->str);
2202           strcat(searchkey,"*");
2203           keyptr=keyptr->next;
2204         }
2205
2206       /* Nail that last "*" */
2207       if(*searchkey)
2208         searchkey[strlen(searchkey)-1]='\0';
2209
2210       if(search_key(searchkey)!=KEYSERVER_OK)
2211         failed++;
2212
2213       free(searchkey);
2214     }
2215   else
2216     BUG();
2217
2218   if(!failed)
2219     ret=KEYSERVER_OK;
2220
2221  fail:
2222
2223   while(keylist!=NULL)
2224     {
2225       struct keylist *current=keylist;
2226       keylist=keylist->next;
2227       free(current);
2228     }
2229
2230   if(input!=stdin)
2231     fclose(input);
2232
2233   if(output!=stdout)
2234     fclose(output);
2235
2236   free_ks_options(opt);
2237
2238   if(ldap!=NULL && bound)
2239     ldap_unbind_s(ldap);
2240
2241   free(basekeyspacedn);
2242
2243   return ret;
2244 }