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