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