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