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