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