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