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