* gpgkeys_ldap.c (main), gpgkeys_hkp.c (main), gpgkeys_http.c (main),
[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 int
1536 main(int argc,char *argv[])
1537 {
1538   int debug=0,port=0,arg,err,action=-1,ret=KEYSERVER_INTERNAL_ERROR;
1539   char line[MAX_LINE];
1540   int version,failed=0,use_ssl=0,use_tls=0,bound=0;
1541   struct keylist *keylist=NULL,*keyptr=NULL;
1542   unsigned int timeout=DEFAULT_KEYSERVER_TIMEOUT;
1543
1544   console=stderr;
1545
1546   while((arg=getopt(argc,argv,"hVo:"))!=-1)
1547     switch(arg)
1548       {
1549       default:
1550       case 'h':
1551         fprintf(console,"-h\thelp\n");
1552         fprintf(console,"-V\tversion\n");
1553         fprintf(console,"-o\toutput to this file\n");
1554         return KEYSERVER_OK;
1555
1556       case 'V':
1557         fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1558         return KEYSERVER_OK;
1559
1560       case 'o':
1561         output=fopen(optarg,"w");
1562         if(output==NULL)
1563           {
1564             fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1565                     optarg,strerror(errno));
1566             return KEYSERVER_INTERNAL_ERROR;
1567           }
1568
1569         break;
1570       }
1571
1572   if(argc>optind)
1573     {
1574       input=fopen(argv[optind],"r");
1575       if(input==NULL)
1576         {
1577           fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1578                   argv[optind],strerror(errno));
1579           return KEYSERVER_INTERNAL_ERROR;
1580         }
1581     }
1582
1583   if(input==NULL)
1584     input=stdin;
1585
1586   if(output==NULL)
1587     output=stdout;
1588
1589   /* Get the command and info block */
1590
1591   while(fgets(line,MAX_LINE,input)!=NULL)
1592     {
1593       char commandstr[7];
1594       char optionstr[256];
1595       char schemestr[80];
1596       char hash;
1597
1598       if(line[0]=='\n')
1599         break;
1600
1601       if(sscanf(line,"%c",&hash)==1 && hash=='#')
1602         continue;
1603
1604       if(sscanf(line,"COMMAND %6s\n",commandstr)==1)
1605         {
1606           commandstr[6]='\0';
1607
1608           if(strcasecmp(commandstr,"get")==0)
1609             action=GET;
1610           else if(strcasecmp(commandstr,"send")==0)
1611             action=SEND;
1612           else if(strcasecmp(commandstr,"search")==0)
1613             action=SEARCH;
1614
1615           continue;
1616         }
1617
1618       if(sscanf(line,"HOST %79s\n",host)==1)
1619         {
1620           host[79]='\0';
1621           continue;
1622         }
1623
1624       if(sscanf(line,"PORT %9s\n",portstr)==1)
1625         {
1626           portstr[9]='\0';
1627           port=atoi(portstr);
1628           continue;
1629         }
1630
1631       if(sscanf(line,"SCHEME %79s\n",schemestr)==1)
1632         {
1633           schemestr[79]='\0';
1634           if(strcasecmp(schemestr,"ldaps")==0)
1635             {
1636               port=636;
1637               use_ssl=1;
1638             }
1639           continue;
1640         }
1641
1642       if(sscanf(line,"VERSION %d\n",&version)==1)
1643         {
1644           if(version!=KEYSERVER_PROTO_VERSION)
1645             {
1646               ret=KEYSERVER_VERSION_ERROR;
1647               goto fail;
1648             }
1649
1650           continue;
1651         }
1652
1653       if(sscanf(line,"OPTION %255[^\n]\n",optionstr)==1)
1654         {
1655           int no=0;
1656           char *start=&optionstr[0];
1657
1658           optionstr[255]='\0';
1659
1660           if(strncasecmp(optionstr,"no-",3)==0)
1661             {
1662               no=1;
1663               start=&optionstr[3];
1664             }
1665
1666           if(strcasecmp(start,"verbose")==0)
1667             {
1668               if(no)
1669                 verbose--;
1670               else
1671                 verbose++;
1672             }
1673           else if(strcasecmp(start,"include-disabled")==0)
1674             {
1675               if(no)
1676                 include_disabled=0;
1677               else
1678                 include_disabled=1;
1679             }
1680           else if(strcasecmp(start,"include-revoked")==0)
1681             {
1682               if(no)
1683                 include_revoked=0;
1684               else
1685                 include_revoked=1;
1686             }
1687           else if(strcasecmp(start,"include-subkeys")==0)
1688             {
1689               if(no)
1690                 include_subkeys=0;
1691               else
1692                 include_subkeys=1;
1693             }
1694           else if(strncasecmp(start,"tls",3)==0)
1695             {
1696               if(no)
1697                 use_tls=0;
1698               else if(start[3]=='=')
1699                 {
1700                   if(strcasecmp(&start[4],"no")==0)
1701                     use_tls=0;
1702                   else if(strcasecmp(&start[4],"try")==0)
1703                     use_tls=1;
1704                   else if(strcasecmp(&start[4],"warn")==0)
1705                     use_tls=2;
1706                   else if(strcasecmp(&start[4],"require")==0)
1707                     use_tls=3;
1708                   else
1709                     use_tls=1;
1710                 }
1711               else if(start[3]=='\0')
1712                 use_tls=1;
1713             }
1714           else if(strncasecmp(start,"debug",5)==0)
1715             {
1716               if(no)
1717                 debug=0;
1718               else if(start[5]=='=')
1719                 debug=atoi(&start[6]);
1720             }
1721           else if(strncasecmp(start,"basedn",6)==0)
1722             {
1723               if(no)
1724                 {
1725                   free(basekeyspacedn);
1726                   basekeyspacedn=NULL;
1727                 }
1728               else if(start[6]=='=')
1729                 {
1730                   free(basekeyspacedn);
1731                   basekeyspacedn=strdup(&start[7]);
1732                   if(!basekeyspacedn)
1733                     {
1734                       fprintf(console,"gpgkeys: out of memory while creating "
1735                               "base DN\n");
1736                       ret=KEYSERVER_NO_MEMORY;
1737                       goto fail;
1738                     }
1739
1740                   real_ldap=1;
1741                 }
1742             }
1743           else if(strncasecmp(start,"timeout",7)==0)
1744             {
1745               if(no)
1746                 timeout=0;
1747               else
1748                 timeout=atoi(&start[8]);
1749             }
1750
1751           continue;
1752         }
1753     }
1754
1755   if(timeout && register_timeout()==-1)
1756     {
1757       fprintf(console,"gpgkeys: unable to register timeout handler\n");
1758       return KEYSERVER_INTERNAL_ERROR;
1759     }
1760
1761   /* SSL trumps TLS */
1762   if(use_ssl)
1763     use_tls=0;
1764
1765   /* If it's a GET or a SEARCH, the next thing to come in is the
1766      keyids.  If it's a SEND, then there are no keyids. */
1767
1768   if(action==SEND)
1769     while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
1770   else if(action==GET || action==SEARCH)
1771     {
1772       for(;;)
1773         {
1774           struct keylist *work;
1775
1776           if(fgets(line,MAX_LINE,input)==NULL)
1777             break;
1778           else
1779             {
1780               if(line[0]=='\n' || line[0]=='\0')
1781                 break;
1782
1783               work=malloc(sizeof(struct keylist));
1784               if(work==NULL)
1785                 {
1786                   fprintf(console,"gpgkeys: out of memory while "
1787                           "building key list\n");
1788                   ret=KEYSERVER_NO_MEMORY;
1789                   goto fail;
1790                 }
1791
1792               strcpy(work->str,line);
1793
1794               /* Trim the trailing \n */
1795               work->str[strlen(line)-1]='\0';
1796
1797               work->next=NULL;
1798
1799               /* Always attach at the end to keep the list in proper
1800                  order for searching */
1801               if(keylist==NULL)
1802                 keylist=work;
1803               else
1804                 keyptr->next=work;
1805
1806               keyptr=work;
1807             }
1808         }
1809     }
1810   else
1811     {
1812       fprintf(console,"gpgkeys: no keyserver command specified\n");
1813       goto fail;
1814     }
1815
1816   /* Send the response */
1817
1818   fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
1819   fprintf(output,"PROGRAM %s\n\n",VERSION);
1820
1821   if(verbose>1)
1822     {
1823       fprintf(console,"Host:\t\t%s\n",host);
1824       if(port)
1825         fprintf(console,"Port:\t\t%d\n",port);
1826       fprintf(console,"Command:\t%s\n",action==GET?"GET":
1827               action==SEND?"SEND":"SEARCH");
1828     }
1829
1830   if(debug)
1831     {
1832 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
1833       err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&debug);
1834       if(err!=LDAP_SUCCESS)
1835         fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
1836                 ldap_err2string(err));
1837       else
1838         fprintf(console,"gpgkeys: debug level %d\n",debug);
1839 #else
1840       fprintf(console,"gpgkeys: not built with debugging support\n");
1841 #endif
1842     }
1843
1844   /* We have a timeout set for the setup stuff since it could time out
1845      as well. */
1846   set_timeout(timeout);
1847
1848   /* Note that this tries all A records on a given host (or at least,
1849      OpenLDAP does). */
1850   ldap=ldap_init(host,port);
1851   if(ldap==NULL)
1852     {
1853       fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
1854               strerror(errno));
1855       fail_all(keylist,action,KEYSERVER_INTERNAL_ERROR);
1856       goto fail;
1857     }
1858
1859   if(use_ssl)
1860     {
1861 #if defined(LDAP_OPT_X_TLS_HARD) && defined(HAVE_LDAP_SET_OPTION)
1862       int ssl=LDAP_OPT_X_TLS_HARD;
1863       err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
1864       if(err!=LDAP_SUCCESS)
1865         {
1866           fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
1867                   ldap_err2string(err));
1868           fail_all(keylist,action,ldap_err_to_gpg_err(err));
1869           goto fail;
1870         }
1871 #else
1872       fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
1873               "not built with LDAPS support");
1874       fail_all(keylist,action,KEYSERVER_INTERNAL_ERROR);
1875       goto fail;
1876 #endif
1877     }
1878
1879   if(!basekeyspacedn)
1880     if((err=find_basekeyspacedn()) || !basekeyspacedn)
1881       {
1882         fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
1883                 err?ldap_err2string(err):"not found");
1884         fail_all(keylist,action,ldap_err_to_gpg_err(err));
1885         goto fail;
1886       }
1887
1888   /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
1889      3=force use. */
1890   if(use_tls)
1891     {
1892       if(!real_ldap)
1893         {
1894           if(use_tls>=2)
1895             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
1896                     "not supported by the NAI LDAP keyserver");
1897           if(use_tls==3)
1898             {
1899               fail_all(keylist,action,KEYSERVER_INTERNAL_ERROR);
1900               goto fail;
1901             }
1902         }
1903       else
1904         {
1905 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
1906           int ver=LDAP_VERSION3;
1907
1908           err=LDAP_SUCCESS;
1909
1910           err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
1911           if(err==LDAP_SUCCESS)
1912             err=ldap_start_tls_s(ldap,NULL,NULL);
1913
1914           if(err!=LDAP_SUCCESS)
1915             {
1916               if(use_tls==2 || verbose>2)
1917                 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
1918                         ldap_err2string(err));
1919               /* Are we forcing it? */
1920               if(use_tls==3)
1921                 {
1922                   fail_all(keylist,action,ldap_err_to_gpg_err(err));
1923                   goto fail;
1924                 }
1925             }
1926           else if(err==LDAP_SUCCESS && verbose>1)
1927             fprintf(console,"gpgkeys: TLS started successfully.\n");
1928 #else
1929           if(use_tls>=2)
1930             fprintf(console,"gpgkeys: unable to start TLS: %s\n",
1931                     "not built with TLS support");
1932           if(use_tls==3)
1933             {
1934               fail_all(keylist,action,KEYSERVER_INTERNAL_ERROR);
1935               goto fail;
1936             }
1937 #endif
1938         }
1939     }
1940
1941 #if 0
1942   /* The LDAP keyserver doesn't require this, but it might be useful
1943      if someone stores keys on a V2 LDAP server somewhere.  (V3
1944      doesn't require a bind).  Leave this out for now since it is not
1945      clear if anyone server we're likely to use really cares, plus
1946      there are some servers that don't allow it. */
1947
1948   err=ldap_simple_bind_s(ldap,NULL,NULL);
1949   if(err!=0)
1950     {
1951       fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
1952               ldap_err2string(err));
1953       fail_all(keylist,action,ldap_err_to_gpg_err(err));
1954       goto fail;
1955     }
1956   else
1957     bound=1;
1958 #endif
1959
1960   switch(action)
1961     {
1962     case GET:
1963       keyptr=keylist;
1964
1965       while(keyptr!=NULL)
1966         {
1967           set_timeout(timeout);
1968
1969           if(get_key(keyptr->str)!=KEYSERVER_OK)
1970             failed++;
1971
1972           keyptr=keyptr->next;
1973         }
1974       break;
1975
1976     case SEND:
1977       {
1978         int eof=0;
1979
1980         do
1981           {
1982             set_timeout(timeout);
1983
1984             if(real_ldap)
1985               {
1986                 if(send_key(&eof)!=KEYSERVER_OK)
1987                   failed++;
1988               }
1989             else
1990               {
1991                 if(send_key_keyserver(&eof)!=KEYSERVER_OK)
1992                   failed++;
1993               }
1994           }
1995         while(!eof);
1996       }
1997       break;
1998
1999     case SEARCH:
2000       {
2001         char *searchkey=NULL;
2002         int len=0;
2003
2004         set_timeout(timeout);
2005
2006         /* To search, we stick a * in between each key to search for.
2007            This means that if the user enters words, they'll get
2008            "enters*words".  If the user "enters words", they'll get
2009            "enters words" */
2010
2011         keyptr=keylist;
2012         while(keyptr!=NULL)
2013           {
2014             len+=strlen(keyptr->str)+1;
2015             keyptr=keyptr->next;
2016           }
2017
2018         searchkey=malloc(len+1);
2019         if(searchkey==NULL)
2020           {
2021             ret=KEYSERVER_NO_MEMORY;
2022             fail_all(keylist,action,KEYSERVER_NO_MEMORY);
2023             goto fail;
2024           }
2025
2026         searchkey[0]='\0';
2027
2028         keyptr=keylist;
2029         while(keyptr!=NULL)
2030           {
2031             strcat(searchkey,keyptr->str);
2032             strcat(searchkey,"*");
2033             keyptr=keyptr->next;
2034           }
2035
2036         /* Nail that last "*" */
2037         if(*searchkey)
2038           searchkey[strlen(searchkey)-1]='\0';
2039
2040         if(search_key(searchkey)!=KEYSERVER_OK)
2041           failed++;
2042
2043         free(searchkey);
2044       }
2045
2046       break;
2047     }
2048
2049   if(!failed)
2050     ret=KEYSERVER_OK;
2051
2052  fail:
2053
2054   while(keylist!=NULL)
2055     {
2056       struct keylist *current=keylist;
2057       keylist=keylist->next;
2058       free(current);
2059     }
2060
2061   if(input!=stdin)
2062     fclose(input);
2063
2064   if(output!=stdout)
2065     fclose(output);
2066
2067   if(ldap!=NULL && bound)
2068     ldap_unbind_s(ldap);
2069
2070   free(basekeyspacedn);
2071
2072   return ret;
2073 }