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