2006-05-22 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / keyserver / gpgkeys_ldap.c
blobb4bd00e4f2831af26f29627590c65e966c7a2a6e
1 /* gpgkeys_ldap.c - talk to a LDAP keyserver
2 * Copyright (C) 2001, 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
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.
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.
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.
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>
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 /* For OpenLDAP, to enable the API that we're using. */
41 #define LDAP_DEPRECATED 1
42 #include <ldap.h>
43 #endif
45 #include "util.h"
46 #include "keyserver.h"
47 #include "ksutil.h"
49 #ifdef __riscos__
50 #include "util.h"
51 #endif
53 extern char *optarg;
54 extern int optind;
56 static int real_ldap=0;
57 static char *basekeyspacedn=NULL;
58 static char *pgpkeystr="pgpKey";
59 static FILE *input=NULL,*output=NULL,*console=NULL;
60 static LDAP *ldap=NULL;
61 static struct ks_options *opt;
63 #ifndef HAVE_TIMEGM
64 time_t timegm(struct tm *tm);
65 #endif
67 static int
68 ldap_err_to_gpg_err(int err)
70 int ret;
72 switch(err)
74 case LDAP_ALREADY_EXISTS:
75 ret=KEYSERVER_KEY_EXISTS;
76 break;
78 case LDAP_SERVER_DOWN:
79 ret=KEYSERVER_UNREACHABLE;
80 break;
82 default:
83 ret=KEYSERVER_GENERAL_ERROR;
84 break;
87 return ret;
90 static int
91 ldap_to_gpg_err(LDAP *ld)
93 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
95 int err;
97 if(ldap_get_option(ld,LDAP_OPT_ERROR_NUMBER,&err)==0)
98 return ldap_err_to_gpg_err(err);
99 else
100 return KEYSERVER_GENERAL_ERROR;
102 #elif defined(HAVE_LDAP_LD_ERRNO)
104 return ldap_err_to_gpg_err(ld->ld_errno);
106 #else
108 /* We should never get here since the LDAP library should always
109 have either ldap_get_option or ld_errno, but just in case... */
110 return KEYSERVER_GENERAL_ERROR;
112 #endif
115 static int
116 key_in_keylist(const char *key,struct keylist *list)
118 struct keylist *keyptr=list;
120 while(keyptr!=NULL)
122 if(strcasecmp(key,keyptr->str)==0)
123 return 1;
125 keyptr=keyptr->next;
128 return 0;
131 static int
132 add_key_to_keylist(const char *key,struct keylist **list)
134 struct keylist *keyptr=malloc(sizeof(struct keylist));
136 if(keyptr==NULL)
138 fprintf(console,"gpgkeys: out of memory when deduping "
139 "key list\n");
140 return KEYSERVER_NO_MEMORY;
143 strncpy(keyptr->str,key,MAX_LINE);
144 keyptr->str[MAX_LINE-1]='\0';
145 keyptr->next=*list;
146 *list=keyptr;
148 return 0;
151 static void
152 free_keylist(struct keylist *list)
154 while(list!=NULL)
156 struct keylist *keyptr=list;
158 list=keyptr->next;
159 free(keyptr);
163 static time_t
164 ldap2epochtime(const char *timestr)
166 struct tm pgptime;
167 time_t answer;
169 memset(&pgptime,0,sizeof(pgptime));
171 /* YYYYMMDDHHmmssZ */
173 sscanf(timestr,"%4d%2d%2d%2d%2d%2d",
174 &pgptime.tm_year,
175 &pgptime.tm_mon,
176 &pgptime.tm_mday,
177 &pgptime.tm_hour,
178 &pgptime.tm_min,
179 &pgptime.tm_sec);
181 pgptime.tm_year-=1900;
182 pgptime.tm_isdst=-1;
183 pgptime.tm_mon--;
185 /* mktime() takes the timezone into account, so we use timegm() */
187 answer=timegm(&pgptime);
189 return answer;
192 /* Caller must free */
193 static char *
194 epoch2ldaptime(time_t stamp)
196 struct tm *ldaptime;
197 char buf[16];
199 ldaptime=gmtime(&stamp);
201 ldaptime->tm_year+=1900;
202 ldaptime->tm_mon++;
204 /* YYYYMMDDHHmmssZ */
206 sprintf(buf,"%04d%02d%02d%02d%02d%02dZ",
207 ldaptime->tm_year,
208 ldaptime->tm_mon,
209 ldaptime->tm_mday,
210 ldaptime->tm_hour,
211 ldaptime->tm_min,
212 ldaptime->tm_sec);
214 return strdup(buf);
217 /* Append two onto the end of one. Two is not freed, but its pointers
218 are now part of one. Make sure you don't free them both! */
219 static int
220 join_two_modlists(LDAPMod ***one,LDAPMod **two)
222 int i,one_count=0,two_count=0;
223 LDAPMod **grow;
225 for(grow=*one;*grow;grow++)
226 one_count++;
228 for(grow=two;*grow;grow++)
229 two_count++;
231 grow=realloc(*one,sizeof(LDAPMod *)*(one_count+two_count+1));
232 if(!grow)
233 return 0;
235 for(i=0;i<two_count;i++)
236 grow[one_count+i]=two[i];
238 grow[one_count+i]=NULL;
240 *one=grow;
242 return 1;
245 /* Passing a NULL for value effectively deletes that attribute. This
246 doesn't mean "delete" in the sense of removing something from the
247 modlist, but "delete" in the LDAP sense of adding a modlist item
248 that specifies LDAP_MOD_REPLACE and a null attribute for the given
249 attribute. LDAP_MOD_DELETE doesn't work here as we don't know if
250 the attribute in question exists or not. */
252 static int
253 make_one_attr(LDAPMod ***modlist,char *attr,const char *value)
255 LDAPMod **m;
256 int nummods=0;
258 /* Search modlist for the attribute we're playing with. */
259 for(m=*modlist;*m;m++)
261 if(strcasecmp((*m)->mod_type,attr)==0)
263 char **ptr=(*m)->mod_values;
264 int numvalues=0;
266 /* We have this attribute already, so when the REPLACE
267 happens, the server attributes will be replaced
268 anyway. */
269 if(!value)
270 return 1;
272 if(ptr)
273 for(ptr=(*m)->mod_values;*ptr;ptr++)
275 /* Duplicate value */
276 if(strcmp(*ptr,value)==0)
277 return 1;
278 numvalues++;
281 ptr=realloc((*m)->mod_values,sizeof(char *)*(numvalues+2));
282 if(!ptr)
283 return 0;
285 (*m)->mod_values=ptr;
286 ptr[numvalues]=strdup(value);
287 if(!ptr[numvalues])
288 return 0;
290 ptr[numvalues+1]=NULL;
291 break;
294 nummods++;
297 /* We didn't find the attr, so make one and add it to the end */
298 if(!*m)
300 LDAPMod **grow;
302 grow=realloc(*modlist,sizeof(LDAPMod *)*(nummods+2));
303 if(!grow)
304 return 0;
306 *modlist=grow;
307 grow[nummods]=malloc(sizeof(LDAPMod));
308 if(!grow[nummods])
309 return 0;
310 grow[nummods]->mod_op=LDAP_MOD_REPLACE;
311 grow[nummods]->mod_type=attr;
312 if(value)
314 grow[nummods]->mod_values=malloc(sizeof(char *)*2);
315 if(!grow[nummods]->mod_values)
317 grow[nummods]=NULL;
318 return 0;
321 /* Is this the right thing? Can a UTF8-encoded user ID have
322 embedded nulls? */
323 grow[nummods]->mod_values[0]=strdup(value);
324 if(!grow[nummods]->mod_values[0])
326 free(grow[nummods]->mod_values);
327 grow[nummods]=NULL;
328 return 0;
331 grow[nummods]->mod_values[1]=NULL;
333 else
334 grow[nummods]->mod_values=NULL;
336 grow[nummods+1]=NULL;
339 return 1;
342 static void
343 build_attrs(LDAPMod ***modlist,char *line)
345 char *record;
346 int i;
348 /* Remove trailing whitespace */
349 for(i=strlen(line);i>0;i--)
350 if(ascii_isspace(line[i-1]))
351 line[i-1]='\0';
352 else
353 break;
355 if((record=strsep(&line,":"))==NULL)
356 return;
358 if(ascii_strcasecmp("pub",record)==0)
360 char *tok;
361 int disabled=0,revoked=0;
363 /* The long keyid */
364 if((tok=strsep(&line,":"))==NULL)
365 return;
367 if(strlen(tok)==16)
369 make_one_attr(modlist,"pgpCertID",tok);
370 make_one_attr(modlist,"pgpKeyID",&tok[8]);
372 else
373 return;
375 /* The primary pubkey algo */
376 if((tok=strsep(&line,":"))==NULL)
377 return;
379 switch(atoi(tok))
381 case 1:
382 make_one_attr(modlist,"pgpKeyType","RSA");
383 break;
385 case 17:
386 make_one_attr(modlist,"pgpKeyType","DSS/DH");
387 break;
390 /* Size of primary key */
391 if((tok=strsep(&line,":"))==NULL)
392 return;
394 if(atoi(tok)>0)
396 char padded[6];
397 int val=atoi(tok);
399 /* We zero pad this on the left to make PGP happy. */
401 if(val<99999 && val>0)
403 sprintf(padded,"%05u",atoi(tok));
404 make_one_attr(modlist,"pgpKeySize",padded);
408 /* pk timestamp */
409 if((tok=strsep(&line,":"))==NULL)
410 return;
412 if(atoi(tok)>0)
414 char *stamp=epoch2ldaptime(atoi(tok));
415 if(stamp)
417 make_one_attr(modlist,"pgpKeyCreateTime",stamp);
418 free(stamp);
422 /* pk expire */
423 if((tok=strsep(&line,":"))==NULL)
424 return;
426 if(atoi(tok)>0)
428 char *stamp=epoch2ldaptime(atoi(tok));
429 if(stamp)
431 make_one_attr(modlist,"pgpKeyExpireTime",stamp);
432 free(stamp);
436 /* flags */
437 if((tok=strsep(&line,":"))==NULL)
438 return;
440 while(*tok)
441 switch(*tok++)
443 case 'r':
444 case 'R':
445 revoked=1;
446 break;
448 case 'd':
449 case 'D':
450 disabled=1;
451 break;
455 Note that we always create the pgpDisabled and pgpRevoked
456 attributes, regardless of whether the key is disabled/revoked
457 or not. This is because a very common search is like
458 "(&(pgpUserID=*isabella*)(pgpDisabled=0))"
461 make_one_attr(modlist,"pgpDisabled",disabled?"1":"0");
462 make_one_attr(modlist,"pgpRevoked",revoked?"1":"0");
464 else if(ascii_strcasecmp("sub",record)==0)
466 char *tok;
468 /* The long keyid */
469 if((tok=strsep(&line,":"))==NULL)
470 return;
472 if(strlen(tok)==16)
473 make_one_attr(modlist,"pgpSubKeyID",tok);
474 else
475 return;
477 /* The subkey algo */
478 if((tok=strsep(&line,":"))==NULL)
479 return;
481 /* Size of subkey */
482 if((tok=strsep(&line,":"))==NULL)
483 return;
485 if(atoi(tok)>0)
487 char padded[6];
488 int val=atoi(tok);
490 /* We zero pad this on the left to make PGP happy. */
492 if(val<99999 && val>0)
494 sprintf(padded,"%05u",atoi(tok));
495 make_one_attr(modlist,"pgpKeySize",padded);
499 /* Ignore the rest of the items for subkeys since the LDAP
500 schema doesn't store them. */
502 else if(ascii_strcasecmp("uid",record)==0)
504 char *userid,*tok;
506 /* The user ID string */
507 if((tok=strsep(&line,":"))==NULL)
508 return;
510 if(strlen(tok)==0)
511 return;
513 userid=tok;
515 /* By definition, de-%-encoding is always smaller than the
516 original string so we can decode in place. */
518 i=0;
520 while(*tok)
521 if(tok[0]=='%' && tok[1] && tok[2])
523 if((userid[i]=hextobyte(&tok[1]))==-1)
524 userid[i]='?';
526 i++;
527 tok+=3;
529 else
530 userid[i++]=*tok++;
532 userid[i]='\0';
534 /* We don't care about the other info provided in the uid: line
535 since the LDAP schema doesn't need it. */
537 make_one_attr(modlist,"pgpUserID",userid);
539 else if(ascii_strcasecmp("sig",record)==0)
541 char *tok;
543 if((tok=strsep(&line,":"))==NULL)
544 return;
546 if(strlen(tok)==16)
547 make_one_attr(modlist,"pgpSignerID",tok);
551 static void
552 free_mod_values(LDAPMod *mod)
554 char **ptr;
556 if(!mod->mod_values)
557 return;
559 for(ptr=mod->mod_values;*ptr;ptr++)
560 free(*ptr);
562 free(mod->mod_values);
565 static int
566 send_key(int *eof)
568 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
569 char *dn=NULL,line[MAX_LINE],*key=NULL;
570 char keyid[17];
571 LDAPMod **modlist,**addlist,**ml;
573 modlist=malloc(sizeof(LDAPMod *));
574 if(!modlist)
576 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
577 ret=KEYSERVER_NO_MEMORY;
578 goto fail;
581 *modlist=NULL;
583 addlist=malloc(sizeof(LDAPMod *));
584 if(!addlist)
586 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
587 ret=KEYSERVER_NO_MEMORY;
588 goto fail;
591 *addlist=NULL;
593 /* Start by nulling out all attributes. We try and do a modify
594 operation first, so this ensures that we don't leave old
595 attributes lying around. */
596 make_one_attr(&modlist,"pgpDisabled",NULL);
597 make_one_attr(&modlist,"pgpKeyID",NULL);
598 make_one_attr(&modlist,"pgpKeyType",NULL);
599 make_one_attr(&modlist,"pgpUserID",NULL);
600 make_one_attr(&modlist,"pgpKeyCreateTime",NULL);
601 make_one_attr(&modlist,"pgpSignerID",NULL);
602 make_one_attr(&modlist,"pgpRevoked",NULL);
603 make_one_attr(&modlist,"pgpSubKeyID",NULL);
604 make_one_attr(&modlist,"pgpKeySize",NULL);
605 make_one_attr(&modlist,"pgpKeyExpireTime",NULL);
606 make_one_attr(&modlist,"pgpCertID",NULL);
608 /* Assemble the INFO stuff into LDAP attributes */
610 while(fgets(line,MAX_LINE,input)!=NULL)
611 if(sscanf(line,"INFO %16s BEGIN\n",keyid)==1)
613 begin=1;
614 break;
617 if(!begin)
619 /* i.e. eof before the INFO BEGIN was found. This isn't an
620 error. */
621 *eof=1;
622 ret=KEYSERVER_OK;
623 goto fail;
626 if(strlen(keyid)!=16)
628 *eof=1;
629 ret=KEYSERVER_KEY_INCOMPLETE;
630 goto fail;
633 dn=malloc(strlen("pgpCertID=")+16+1+strlen(basekeyspacedn)+1);
634 if(dn==NULL)
636 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
637 ret=KEYSERVER_NO_MEMORY;
638 goto fail;
641 sprintf(dn,"pgpCertID=%s,%s",keyid,basekeyspacedn);
643 key=malloc(1);
644 if(!key)
646 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
647 ret=KEYSERVER_NO_MEMORY;
648 goto fail;
651 key[0]='\0';
653 /* Now parse each line until we see the END */
655 while(fgets(line,MAX_LINE,input)!=NULL)
656 if(sscanf(line,"INFO %16s END\n",keyid)==1)
658 end=1;
659 break;
661 else
662 build_attrs(&addlist,line);
664 if(!end)
666 fprintf(console,"gpgkeys: no INFO %s END found\n",keyid);
667 *eof=1;
668 ret=KEYSERVER_KEY_INCOMPLETE;
669 goto fail;
672 begin=end=0;
674 /* Read and throw away stdin until we see the BEGIN */
676 while(fgets(line,MAX_LINE,input)!=NULL)
677 if(sscanf(line,"KEY %16s BEGIN\n",keyid)==1)
679 begin=1;
680 break;
683 if(!begin)
685 /* i.e. eof before the KEY BEGIN was found. This isn't an
686 error. */
687 *eof=1;
688 ret=KEYSERVER_OK;
689 goto fail;
692 /* Now slurp up everything until we see the END */
694 while(fgets(line,MAX_LINE,input)!=NULL)
695 if(sscanf(line,"KEY %16s END\n",keyid)==1)
697 end=1;
698 break;
700 else
702 char *tempkey;
703 keysize+=strlen(line);
704 tempkey=realloc(key,keysize);
705 if(tempkey==NULL)
707 fprintf(console,"gpgkeys: unable to reallocate for key\n");
708 ret=KEYSERVER_NO_MEMORY;
709 goto fail;
711 else
712 key=tempkey;
714 strcat(key,line);
717 if(!end)
719 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
720 *eof=1;
721 ret=KEYSERVER_KEY_INCOMPLETE;
722 goto fail;
725 make_one_attr(&addlist,"objectClass","pgpKeyInfo");
726 make_one_attr(&addlist,"pgpKey",key);
728 /* Now append addlist onto modlist */
729 if(!join_two_modlists(&modlist,addlist))
731 fprintf(console,"gpgkeys: unable to merge LDAP modification lists\n");
732 ret=KEYSERVER_NO_MEMORY;
733 goto fail;
736 /* Going on the assumption that modify operations are more frequent
737 than adds, we try a modify first. If it's not there, we just
738 turn around and send an add command for the same key. Otherwise,
739 the modify brings the server copy into compliance with our copy.
740 Note that unlike the LDAP keyserver (and really, any other
741 keyserver) this does NOT merge signatures, but replaces the whole
742 key. This should make some people very happy. */
744 err=ldap_modify_s(ldap,dn,modlist);
745 if(err==LDAP_NO_SUCH_OBJECT)
746 err=ldap_add_s(ldap,dn,addlist);
748 if(err!=LDAP_SUCCESS)
750 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
751 keyid,ldap_err2string(err));
752 ret=ldap_err_to_gpg_err(err);
753 goto fail;
756 ret=KEYSERVER_OK;
758 fail:
759 /* Unwind and free the whole modlist structure */
760 for(ml=modlist;*ml;ml++)
762 free_mod_values(*ml);
763 free(*ml);
766 free(modlist);
767 free(addlist);
768 free(dn);
770 if(ret!=0 && begin)
771 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
773 return ret;
776 static int
777 send_key_keyserver(int *eof)
779 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
780 char *dn=NULL,line[MAX_LINE],*key[2]={NULL,NULL};
781 char keyid[17];
782 LDAPMod mod, *attrs[2];
784 memset(&mod,0,sizeof(mod));
785 mod.mod_op=LDAP_MOD_ADD;
786 mod.mod_type=pgpkeystr;
787 mod.mod_values=key;
788 attrs[0]=&mod;
789 attrs[1]=NULL;
791 dn=malloc(strlen("pgpCertid=virtual,")+strlen(basekeyspacedn)+1);
792 if(dn==NULL)
794 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
795 ret=KEYSERVER_NO_MEMORY;
796 goto fail;
799 strcpy(dn,"pgpCertid=virtual,");
800 strcat(dn,basekeyspacedn);
802 key[0]=malloc(1);
803 if(key[0]==NULL)
805 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
806 ret=KEYSERVER_NO_MEMORY;
807 goto fail;
810 key[0][0]='\0';
812 /* Read and throw away stdin until we see the BEGIN */
814 while(fgets(line,MAX_LINE,input)!=NULL)
815 if(sscanf(line,"KEY %16s BEGIN\n",keyid)==1)
817 begin=1;
818 break;
821 if(!begin)
823 /* i.e. eof before the KEY BEGIN was found. This isn't an
824 error. */
825 *eof=1;
826 ret=KEYSERVER_OK;
827 goto fail;
830 /* Now slurp up everything until we see the END */
832 while(fgets(line,MAX_LINE,input)!=NULL)
833 if(sscanf(line,"KEY %16s END\n",keyid)==1)
835 end=1;
836 break;
838 else
840 keysize+=strlen(line);
841 key[0]=realloc(key[0],keysize);
842 if(key[0]==NULL)
844 fprintf(console,"gpgkeys: unable to reallocate for key\n");
845 ret=KEYSERVER_NO_MEMORY;
846 goto fail;
849 strcat(key[0],line);
852 if(!end)
854 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
855 *eof=1;
856 ret=KEYSERVER_KEY_INCOMPLETE;
857 goto fail;
860 err=ldap_add_s(ldap,dn,attrs);
861 if(err!=LDAP_SUCCESS)
863 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
864 keyid,ldap_err2string(err));
865 ret=ldap_err_to_gpg_err(err);
866 goto fail;
869 ret=KEYSERVER_OK;
871 fail:
873 free(key[0]);
874 free(dn);
876 if(ret!=0 && begin)
877 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
879 /* Not a fatal error */
880 if(ret==KEYSERVER_KEY_EXISTS)
881 ret=KEYSERVER_OK;
883 return ret;
886 static void
887 build_info(const char *certid,LDAPMessage *each)
889 char **vals;
891 fprintf(output,"INFO %s BEGIN\n",certid);
893 fprintf(output,"pub:%s:",certid);
895 vals=ldap_get_values(ldap,each,"pgpkeytype");
896 if(vals!=NULL)
898 if(strcmp(vals[0],"RSA")==0)
899 fprintf(output,"1");
900 else if(strcmp(vals[0],"DSS/DH")==0)
901 fprintf(output,"17");
902 ldap_value_free(vals);
905 fprintf(output,":");
907 vals=ldap_get_values(ldap,each,"pgpkeysize");
908 if(vals!=NULL)
910 if(atoi(vals[0])>0)
911 fprintf(output,"%d",atoi(vals[0]));
912 ldap_value_free(vals);
915 fprintf(output,":");
917 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
918 if(vals!=NULL)
920 if(strlen(vals[0])==15)
921 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
922 ldap_value_free(vals);
925 fprintf(output,":");
927 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
928 if(vals!=NULL)
930 if(strlen(vals[0])==15)
931 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
932 ldap_value_free(vals);
935 fprintf(output,":");
937 vals=ldap_get_values(ldap,each,"pgprevoked");
938 if(vals!=NULL)
940 if(atoi(vals[0])==1)
941 fprintf(output,"r");
942 ldap_value_free(vals);
945 fprintf(output,"\n");
947 vals=ldap_get_values(ldap,each,"pgpuserid");
948 if(vals!=NULL)
950 int i;
952 for(i=0;vals[i];i++)
953 fprintf(output,"uid:%s\n",vals[i]);
954 ldap_value_free(vals);
957 fprintf(output,"INFO %s END\n",certid);
960 /* Note that key-not-found is not a fatal error */
961 static int
962 get_key(char *getkey)
964 LDAPMessage *res,*each;
965 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
966 struct keylist *dupelist=NULL;
967 char search[62];
968 /* This ordering is significant - specifically, "pgpcertid" needs to
969 be the second item in the list, since everything after it may be
970 discarded if the user isn't in verbose mode. */
971 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
972 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
973 "pgpkeysize","pgpkeytype",NULL};
974 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
975 array initializers. */
977 /* Build the search string */
979 /* GPG can send us a v4 fingerprint, a v3 or v4 long key id, or a v3
980 or v4 short key id */
982 if(strncmp(getkey,"0x",2)==0)
983 getkey+=2;
985 if(strlen(getkey)==32)
987 fprintf(console,
988 "gpgkeys: LDAP keyservers do not support v3 fingerprints\n");
989 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
990 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_NOT_SUPPORTED);
991 return KEYSERVER_NOT_SUPPORTED;
994 if(strlen(getkey)>16)
996 char *offset=&getkey[strlen(getkey)-16];
998 /* fingerprint. Take the last 16 characters and treat it like a
999 long key id */
1001 if(opt->flags.include_subkeys)
1002 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1003 offset,offset);
1004 else
1005 sprintf(search,"(pgpcertid=%.16s)",offset);
1007 else if(strlen(getkey)>8)
1009 /* long key id */
1011 if(opt->flags.include_subkeys)
1012 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1013 getkey,getkey);
1014 else
1015 sprintf(search,"(pgpcertid=%.16s)",getkey);
1017 else
1019 /* short key id */
1021 sprintf(search,"(pgpkeyid=%.8s)",getkey);
1024 if(opt->verbose>2)
1025 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1027 if(!opt->verbose)
1028 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1030 err=ldap_search_s(ldap,basekeyspacedn,
1031 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1032 if(err!=0)
1034 int errtag=ldap_err_to_gpg_err(err);
1036 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1037 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1038 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1039 return errtag;
1042 count=ldap_count_entries(ldap,res);
1043 if(count<1)
1045 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1046 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1047 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1049 else
1051 /* There may be more than one unique result for a given keyID,
1052 so we should fetch them all (test this by fetching short key
1053 id 0xDEADBEEF). */
1055 each=ldap_first_entry(ldap,res);
1056 while(each!=NULL)
1058 char **vals,**certid;
1060 /* Use the long keyid to remove duplicates. The LDAP server
1061 returns the same keyid more than once if there are
1062 multiple user IDs on the key. Note that this does NOT
1063 mean that a keyid that exists multiple times on the
1064 keyserver will not be fetched. It means that each KEY,
1065 no matter how many user IDs share its keyid, will be
1066 fetched only once. If a keyid that belongs to more than
1067 one key is fetched, the server quite properly responds
1068 with all matching keys. -ds */
1070 certid=ldap_get_values(ldap,each,"pgpcertid");
1071 if(certid!=NULL)
1073 if(!key_in_keylist(certid[0],dupelist))
1075 /* it's not a duplicate, so add it */
1077 int rc=add_key_to_keylist(certid[0],&dupelist);
1078 if(rc)
1080 ret=rc;
1081 goto fail;
1084 build_info(certid[0],each);
1086 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1088 vals=ldap_get_values(ldap,each,pgpkeystr);
1089 if(vals==NULL)
1091 int errtag=ldap_to_gpg_err(ldap);
1093 fprintf(console,"gpgkeys: unable to retrieve key %s "
1094 "from keyserver\n",getkey);
1095 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1097 else
1099 print_nocr(output,vals[0]);
1100 fprintf(output,"\nKEY 0x%s END\n",getkey);
1102 ldap_value_free(vals);
1106 ldap_value_free(certid);
1109 each=ldap_next_entry(ldap,each);
1113 ret=KEYSERVER_OK;
1115 fail:
1116 ldap_msgfree(res);
1117 free_keylist(dupelist);
1119 return ret;
1122 #define LDAP_ESCAPE_CHARS "*()\\"
1124 /* Append string to buffer in a LDAP-quoted way */
1125 static void
1126 ldap_quote(char *buffer,const char *string)
1128 /* Find the end of buffer */
1129 buffer+=strlen(buffer);
1131 for(;*string;string++)
1133 if(strchr(LDAP_ESCAPE_CHARS,*string))
1135 sprintf(buffer,"\\%02X",*string);
1136 buffer+=3;
1138 else
1139 *buffer++=*string;
1142 *buffer='\0';
1145 /* Note that key-not-found is not a fatal error */
1146 static int
1147 get_name(char *getkey)
1149 LDAPMessage *res,*each;
1150 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
1151 /* The maximum size of the search, including the optional stuff and
1152 the trailing \0 */
1153 char search[2+12+(MAX_LINE*3)+2+15+14+1+1+20];
1154 /* This ordering is significant - specifically, "pgpcertid" needs to
1155 be the second item in the list, since everything after it may be
1156 discarded if the user isn't in verbose mode. */
1157 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
1158 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
1159 "pgpkeysize","pgpkeytype",NULL};
1160 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1161 array initializers. */
1163 /* Build the search string */
1165 search[0]='\0';
1167 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1168 strcat(search,"(&");
1170 strcat(search,"(pgpUserID=*");
1171 ldap_quote(search,getkey);
1172 strcat(search,"*)");
1174 if(!opt->flags.include_disabled)
1175 strcat(search,"(pgpDisabled=0)");
1177 if(!opt->flags.include_revoked)
1178 strcat(search,"(pgpRevoked=0)");
1180 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1181 strcat(search,")");
1183 if(opt->verbose>2)
1184 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1186 if(!opt->verbose)
1187 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1189 err=ldap_search_s(ldap,basekeyspacedn,
1190 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1191 if(err!=0)
1193 int errtag=ldap_err_to_gpg_err(err);
1195 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1196 fprintf(output,"NAME %s BEGIN\n",getkey);
1197 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1198 return errtag;
1201 count=ldap_count_entries(ldap,res);
1202 if(count<1)
1204 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1205 fprintf(output,"NAME %s BEGIN\n",getkey);
1206 fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1208 else
1210 /* There may be more than one result, but we return them all. */
1212 each=ldap_first_entry(ldap,res);
1213 while(each!=NULL)
1215 char **vals,**certid;
1217 certid=ldap_get_values(ldap,each,"pgpcertid");
1218 if(certid!=NULL)
1220 build_info(certid[0],each);
1222 fprintf(output,"NAME %s BEGIN\n",getkey);
1224 vals=ldap_get_values(ldap,each,pgpkeystr);
1225 if(vals==NULL)
1227 int errtag=ldap_to_gpg_err(ldap);
1229 fprintf(console,"gpgkeys: unable to retrieve key %s "
1230 "from keyserver\n",getkey);
1231 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1233 else
1235 print_nocr(output,vals[0]);
1236 fprintf(output,"\nNAME %s END\n",getkey);
1238 ldap_value_free(vals);
1241 ldap_value_free(certid);
1244 each=ldap_next_entry(ldap,each);
1248 ret=KEYSERVER_OK;
1250 ldap_msgfree(res);
1252 return ret;
1255 static void
1256 printquoted(FILE *stream,char *string,char delim)
1258 while(*string)
1260 if(*string==delim || *string=='%')
1261 fprintf(stream,"%%%02x",*string);
1262 else
1263 fputc(*string,stream);
1265 string++;
1269 /* Returns 0 on success and -1 on error. Note that key-not-found is
1270 not an error! */
1271 static int
1272 search_key(const char *searchkey)
1274 char **vals;
1275 LDAPMessage *res,*each;
1276 int err,count=0;
1277 struct keylist *dupelist=NULL;
1278 /* The maximum size of the search, including the optional stuff and
1279 the trailing \0 */
1280 char search[2+1+9+1+3+(MAX_LINE*3)+3+1+15+14+1+1+20];
1281 char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1282 "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1283 "pgpkeysize","pgpkeytype",NULL};
1284 enum ks_search_type search_type;
1286 fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1288 search_type=classify_ks_search(&searchkey);
1290 if(opt->debug)
1291 fprintf(console,"search type is %d, and key is \"%s\"\n",
1292 search_type,searchkey);
1294 /* Build the search string */
1296 search[0]='\0';
1298 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1299 strcat(search,"(&");
1301 strcat(search,"(");
1303 switch(search_type)
1305 case KS_SEARCH_KEYID_SHORT:
1306 strcat(search,"pgpKeyID");
1307 break;
1309 case KS_SEARCH_KEYID_LONG:
1310 strcat(search,"pgpCertID");
1311 break;
1313 default:
1314 strcat(search,"pgpUserID");
1315 break;
1318 strcat(search,"=");
1320 switch(search_type)
1322 case KS_SEARCH_SUBSTR:
1323 strcat(search,"*");
1324 break;
1326 case KS_SEARCH_MAIL:
1327 strcat(search,"*<");
1328 break;
1330 case KS_SEARCH_MAILSUB:
1331 strcat(search,"*<*");
1332 break;
1334 case KS_SEARCH_EXACT:
1335 case KS_SEARCH_KEYID_LONG:
1336 case KS_SEARCH_KEYID_SHORT:
1337 break;
1340 ldap_quote(search,searchkey);
1342 switch(search_type)
1344 case KS_SEARCH_SUBSTR:
1345 strcat(search,"*");
1346 break;
1348 case KS_SEARCH_MAIL:
1349 strcat(search,">*");
1350 break;
1352 case KS_SEARCH_MAILSUB:
1353 strcat(search,"*>*");
1354 break;
1356 case KS_SEARCH_EXACT:
1357 case KS_SEARCH_KEYID_LONG:
1358 case KS_SEARCH_KEYID_SHORT:
1359 break;
1362 strcat(search,")");
1364 if(!opt->flags.include_disabled)
1365 strcat(search,"(pgpDisabled=0)");
1367 if(!opt->flags.include_revoked)
1368 strcat(search,"(pgpRevoked=0)");
1370 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1371 strcat(search,")");
1373 if(opt->verbose>2)
1374 fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1376 err=ldap_search_s(ldap,basekeyspacedn,
1377 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1378 if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1380 int errtag=ldap_err_to_gpg_err(err);
1382 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1383 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1384 return errtag;
1387 /* The LDAP server doesn't return a real count of unique keys, so we
1388 can't use ldap_count_entries here. */
1389 each=ldap_first_entry(ldap,res);
1390 while(each!=NULL)
1392 char **certid=ldap_get_values(ldap,each,"pgpcertid");
1394 if(certid!=NULL)
1396 if(!key_in_keylist(certid[0],dupelist))
1398 int rc=add_key_to_keylist(certid[0],&dupelist);
1399 if(rc!=0)
1401 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1402 free_keylist(dupelist);
1403 return rc;
1406 count++;
1410 each=ldap_next_entry(ldap,each);
1413 if(err==LDAP_SIZELIMIT_EXCEEDED)
1415 if(count==1)
1416 fprintf(console,"gpgkeys: search results exceeded server limit."
1417 " First %d result shown.\n",count);
1418 else
1419 fprintf(console,"gpgkeys: search results exceeded server limit."
1420 " First %d results shown.\n",count);
1423 free_keylist(dupelist);
1424 dupelist=NULL;
1426 if(count<1)
1427 fprintf(output,"info:1:0\n");
1428 else
1430 fprintf(output,"info:1:%d\n",count);
1432 each=ldap_first_entry(ldap,res);
1433 while(each!=NULL)
1435 char **certid;
1437 certid=ldap_get_values(ldap,each,"pgpcertid");
1438 if(certid!=NULL)
1440 LDAPMessage *uids;
1442 /* Have we seen this certid before? */
1443 if(!key_in_keylist(certid[0],dupelist))
1445 int rc=add_key_to_keylist(certid[0],&dupelist);
1446 if(rc)
1448 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1449 free_keylist(dupelist);
1450 ldap_value_free(certid);
1451 ldap_msgfree(res);
1452 return rc;
1455 fprintf(output,"pub:%s:",certid[0]);
1457 vals=ldap_get_values(ldap,each,"pgpkeytype");
1458 if(vals!=NULL)
1460 /* The LDAP server doesn't exactly handle this
1461 well. */
1462 if(strcasecmp(vals[0],"RSA")==0)
1463 fprintf(output,"1");
1464 else if(strcasecmp(vals[0],"DSS/DH")==0)
1465 fprintf(output,"17");
1466 ldap_value_free(vals);
1469 fputc(':',output);
1471 vals=ldap_get_values(ldap,each,"pgpkeysize");
1472 if(vals!=NULL)
1474 /* Not sure why, but some keys are listed with a
1475 key size of 0. Treat that like an
1476 unknown. */
1477 if(atoi(vals[0])>0)
1478 fprintf(output,"%d",atoi(vals[0]));
1479 ldap_value_free(vals);
1482 fputc(':',output);
1484 /* YYYYMMDDHHmmssZ */
1486 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1487 if(vals!=NULL && strlen(vals[0])==15)
1489 fprintf(output,"%u",
1490 (unsigned int)ldap2epochtime(vals[0]));
1491 ldap_value_free(vals);
1494 fputc(':',output);
1496 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
1497 if(vals!=NULL && strlen(vals[0])==15)
1499 fprintf(output,"%u",
1500 (unsigned int)ldap2epochtime(vals[0]));
1501 ldap_value_free(vals);
1504 fputc(':',output);
1506 vals=ldap_get_values(ldap,each,"pgprevoked");
1507 if(vals!=NULL)
1509 if(atoi(vals[0])==1)
1510 fprintf(output,"r");
1511 ldap_value_free(vals);
1514 vals=ldap_get_values(ldap,each,"pgpdisabled");
1515 if(vals!=NULL)
1517 if(atoi(vals[0])==1)
1518 fprintf(output,"d");
1519 ldap_value_free(vals);
1522 #if 0
1523 /* This is not yet specified in the keyserver
1524 protocol, but may be someday. */
1525 fputc(':',output);
1527 vals=ldap_get_values(ldap,each,"modifytimestamp");
1528 if(vals!=NULL && strlen(vals[0])==15)
1530 fprintf(output,"%u",
1531 (unsigned int)ldap2epochtime(vals[0]));
1532 ldap_value_free(vals);
1534 #endif
1536 fprintf(output,"\n");
1538 /* Now print all the uids that have this certid */
1539 uids=ldap_first_entry(ldap,res);
1540 while(uids!=NULL)
1542 vals=ldap_get_values(ldap,uids,"pgpcertid");
1543 if(vals!=NULL)
1545 if(strcasecmp(certid[0],vals[0])==0)
1547 char **uidvals;
1549 fprintf(output,"uid:");
1551 uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1552 if(uidvals!=NULL)
1554 /* Need to escape any colons */
1555 printquoted(output,uidvals[0],':');
1556 ldap_value_free(uidvals);
1559 fprintf(output,"\n");
1562 ldap_value_free(vals);
1565 uids=ldap_next_entry(ldap,uids);
1569 ldap_value_free(certid);
1572 each=ldap_next_entry(ldap,each);
1576 ldap_msgfree(res);
1577 free_keylist(dupelist);
1579 fprintf(output,"SEARCH %s END\n",searchkey);
1581 return KEYSERVER_OK;
1584 static void
1585 fail_all(struct keylist *keylist,int err)
1587 if(!keylist)
1588 return;
1590 if(opt->action==KS_SEARCH)
1592 fprintf(output,"SEARCH ");
1593 while(keylist)
1595 fprintf(output,"%s ",keylist->str);
1596 keylist=keylist->next;
1598 fprintf(output,"FAILED %d\n",err);
1600 else
1601 while(keylist)
1603 fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1604 keylist=keylist->next;
1608 static int
1609 find_basekeyspacedn(void)
1611 int err,i;
1612 char *attr[]={"namingContexts",NULL,NULL,NULL};
1613 LDAPMessage *res;
1614 char **context;
1616 /* Look for namingContexts */
1617 err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1618 if(err==LDAP_SUCCESS)
1620 context=ldap_get_values(ldap,res,"namingContexts");
1621 if(context)
1623 attr[0]="pgpBaseKeySpaceDN";
1624 attr[1]="pgpVersion";
1625 attr[2]="pgpSoftware";
1627 real_ldap=1;
1629 /* We found some, so try each namingContext as the search base
1630 and look for pgpBaseKeySpaceDN. Because we found this, we
1631 know we're talking to a regular-ish LDAP server and not a
1632 LDAP keyserver. */
1634 for(i=0;context[i] && !basekeyspacedn;i++)
1636 char **vals;
1637 LDAPMessage *si_res;
1638 char *object;
1640 object=malloc(17+strlen(context[i])+1);
1641 if(!object)
1642 return -1;
1644 strcpy(object,"cn=pgpServerInfo,");
1645 strcat(object,context[i]);
1647 err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1648 "(objectClass=*)",attr,0,&si_res);
1649 free(object);
1651 if(err==LDAP_NO_SUCH_OBJECT)
1652 continue;
1653 else if(err!=LDAP_SUCCESS)
1654 return err;
1656 vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1657 if(vals)
1659 basekeyspacedn=strdup(vals[0]);
1660 ldap_value_free(vals);
1663 if(opt->verbose>1)
1665 vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1666 if(vals)
1668 fprintf(console,"Server: \t%s\n",vals[0]);
1669 ldap_value_free(vals);
1672 vals=ldap_get_values(ldap,si_res,"pgpVersion");
1673 if(vals)
1675 fprintf(console,"Version:\t%s\n",vals[0]);
1676 ldap_value_free(vals);
1680 ldap_msgfree(si_res);
1683 ldap_value_free(context);
1686 ldap_msgfree(res);
1688 else
1690 /* We don't have an answer yet, which means the server might be
1691 a LDAP keyserver. */
1692 char **vals;
1693 LDAPMessage *si_res;
1695 attr[0]="pgpBaseKeySpaceDN";
1696 attr[1]="version";
1697 attr[2]="software";
1699 err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1700 "(objectClass=*)",attr,0,&si_res);
1701 if(err!=LDAP_SUCCESS)
1702 return err;
1704 /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1705 KEYSPACE,C=US", but it might not be in the future. */
1707 vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1708 if(vals)
1710 basekeyspacedn=strdup(vals[0]);
1711 ldap_value_free(vals);
1714 if(opt->verbose>1)
1716 vals=ldap_get_values(ldap,si_res,"software");
1717 if(vals)
1719 fprintf(console,"Server: \t%s\n",vals[0]);
1720 ldap_value_free(vals);
1724 vals=ldap_get_values(ldap,si_res,"version");
1725 if(vals)
1727 if(opt->verbose>1)
1728 fprintf(console,"Version:\t%s\n",vals[0]);
1730 /* If the version is high enough, use the new pgpKeyV2
1731 attribute. This design if iffy at best, but it matches how
1732 PGP does it. I figure the NAI folks assumed that there would
1733 never be a LDAP keyserver vendor with a different numbering
1734 scheme. */
1735 if(atoi(vals[0])>1)
1736 pgpkeystr="pgpKeyV2";
1738 ldap_value_free(vals);
1741 ldap_msgfree(si_res);
1744 return LDAP_SUCCESS;
1747 static void
1748 show_help (FILE *fp)
1750 fprintf (fp,"-h\thelp\n");
1751 fprintf (fp,"-V\tversion\n");
1752 fprintf (fp,"-o\toutput to this file\n");
1756 main(int argc,char *argv[])
1758 int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1759 char line[MAX_LINE],*binddn=NULL,*bindpw=NULL;
1760 int failed=0,use_ssl=0,use_tls=0,bound=0;
1761 struct keylist *keylist=NULL,*keyptr=NULL;
1763 console=stderr;
1765 /* Kludge to implement standard GNU options. */
1766 if (argc > 1 && !strcmp (argv[1], "--version"))
1768 fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1769 return 0;
1771 else if (argc > 1 && !strcmp (argv[1], "--help"))
1773 show_help (stdout);
1774 return 0;
1777 while((arg=getopt(argc,argv,"hVo:"))!=-1)
1778 switch(arg)
1780 default:
1781 case 'h':
1782 show_help (console);
1783 return KEYSERVER_OK;
1785 case 'V':
1786 fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1787 return KEYSERVER_OK;
1789 case 'o':
1790 output=fopen(optarg,"w");
1791 if(output==NULL)
1793 fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1794 optarg,strerror(errno));
1795 return KEYSERVER_INTERNAL_ERROR;
1798 break;
1801 if(argc>optind)
1803 input=fopen(argv[optind],"r");
1804 if(input==NULL)
1806 fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1807 argv[optind],strerror(errno));
1808 return KEYSERVER_INTERNAL_ERROR;
1812 if(input==NULL)
1813 input=stdin;
1815 if(output==NULL)
1816 output=stdout;
1818 opt=init_ks_options();
1819 if(!opt)
1820 return KEYSERVER_NO_MEMORY;
1822 /* Get the command and info block */
1824 while(fgets(line,MAX_LINE,input)!=NULL)
1826 char optionstr[MAX_OPTION+1];
1828 if(line[0]=='\n')
1829 break;
1831 err=parse_ks_options(line,opt);
1832 if(err>0)
1834 ret=err;
1835 goto fail;
1837 else if(err==0)
1838 continue;
1840 if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1842 int no=0;
1843 char *start=&optionstr[0];
1845 optionstr[MAX_OPTION]='\0';
1847 if(strncasecmp(optionstr,"no-",3)==0)
1849 no=1;
1850 start=&optionstr[3];
1853 if(strncasecmp(start,"tls",3)==0)
1855 if(no)
1856 use_tls=0;
1857 else if(start[3]=='=')
1859 if(strcasecmp(&start[4],"no")==0)
1860 use_tls=0;
1861 else if(strcasecmp(&start[4],"try")==0)
1862 use_tls=1;
1863 else if(strcasecmp(&start[4],"warn")==0)
1864 use_tls=2;
1865 else if(strcasecmp(&start[4],"require")==0)
1866 use_tls=3;
1867 else
1868 use_tls=1;
1870 else if(start[3]=='\0')
1871 use_tls=1;
1873 else if(strncasecmp(start,"basedn",6)==0)
1875 if(no)
1877 free(basekeyspacedn);
1878 basekeyspacedn=NULL;
1880 else if(start[6]=='=')
1882 free(basekeyspacedn);
1883 basekeyspacedn=strdup(&start[7]);
1884 if(!basekeyspacedn)
1886 fprintf(console,"gpgkeys: out of memory while creating "
1887 "base DN\n");
1888 ret=KEYSERVER_NO_MEMORY;
1889 goto fail;
1892 real_ldap=1;
1895 else if(strncasecmp(start,"binddn",6)==0)
1897 if(no)
1899 free(binddn);
1900 binddn=NULL;
1902 else if(start[6]=='=')
1904 free(binddn);
1905 binddn=strdup(&start[7]);
1906 if(!binddn)
1908 fprintf(console,"gpgkeys: out of memory while creating "
1909 "bind DN\n");
1910 ret=KEYSERVER_NO_MEMORY;
1911 goto fail;
1914 real_ldap=1;
1917 else if(strncasecmp(start,"bindpw",6)==0)
1919 if(no)
1921 free(bindpw);
1922 bindpw=NULL;
1924 else if(start[6]=='=')
1926 free(bindpw);
1927 bindpw=strdup(&start[7]);
1928 if(!bindpw)
1930 fprintf(console,"gpgkeys: out of memory while creating "
1931 "bind password\n");
1932 ret=KEYSERVER_NO_MEMORY;
1933 goto fail;
1936 real_ldap=1;
1940 continue;
1944 if(!opt->scheme)
1946 fprintf(console,"gpgkeys: no scheme supplied!\n");
1947 ret=KEYSERVER_SCHEME_NOT_FOUND;
1948 goto fail;
1951 if(strcasecmp(opt->scheme,"ldaps")==0)
1953 port=636;
1954 use_ssl=1;
1957 if(opt->port)
1958 port=atoi(opt->port);
1960 if(!opt->host)
1962 fprintf(console,"gpgkeys: no keyserver host provided\n");
1963 goto fail;
1966 if(opt->timeout && register_timeout()==-1)
1968 fprintf(console,"gpgkeys: unable to register timeout handler\n");
1969 return KEYSERVER_INTERNAL_ERROR;
1972 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
1974 if(opt->ca_cert_file)
1976 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
1977 if(err!=LDAP_SUCCESS)
1979 fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
1980 ldap_err2string(err));
1981 ret=KEYSERVER_INTERNAL_ERROR;
1982 goto fail;
1985 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
1987 /* SSL trumps TLS */
1988 if(use_ssl)
1989 use_tls=0;
1991 /* If it's a GET or a SEARCH, the next thing to come in is the
1992 keyids. If it's a SEND, then there are no keyids. */
1994 if(opt->action==KS_SEND)
1995 while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
1996 else if(opt->action==KS_GET
1997 || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
1999 for(;;)
2001 struct keylist *work;
2003 if(fgets(line,MAX_LINE,input)==NULL)
2004 break;
2005 else
2007 if(line[0]=='\n' || line[0]=='\0')
2008 break;
2010 work=malloc(sizeof(struct keylist));
2011 if(work==NULL)
2013 fprintf(console,"gpgkeys: out of memory while "
2014 "building key list\n");
2015 ret=KEYSERVER_NO_MEMORY;
2016 goto fail;
2019 strcpy(work->str,line);
2021 /* Trim the trailing \n */
2022 work->str[strlen(line)-1]='\0';
2024 work->next=NULL;
2026 /* Always attach at the end to keep the list in proper
2027 order for searching */
2028 if(keylist==NULL)
2029 keylist=work;
2030 else
2031 keyptr->next=work;
2033 keyptr=work;
2037 else
2039 fprintf(console,"gpgkeys: no keyserver command specified\n");
2040 goto fail;
2043 /* Send the response */
2045 fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
2046 fprintf(output,"PROGRAM %s\n\n",VERSION);
2048 if(opt->verbose>1)
2050 fprintf(console,"Host:\t\t%s\n",opt->host);
2051 if(port)
2052 fprintf(console,"Port:\t\t%d\n",port);
2053 fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
2056 if(opt->debug)
2058 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
2059 err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
2060 if(err!=LDAP_SUCCESS)
2061 fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
2062 ldap_err2string(err));
2063 else
2064 fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
2065 #else
2066 fprintf(console,"gpgkeys: not built with debugging support\n");
2067 #endif
2070 /* We have a timeout set for the setup stuff since it could time out
2071 as well. */
2072 set_timeout(opt->timeout);
2074 /* Note that this tries all A records on a given host (or at least,
2075 OpenLDAP does). */
2076 ldap=ldap_init(opt->host,port);
2077 if(ldap==NULL)
2079 fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
2080 strerror(errno));
2081 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2082 goto fail;
2085 if(use_ssl)
2087 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
2088 int ssl=LDAP_OPT_X_TLS_HARD;
2090 err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
2091 if(err!=LDAP_SUCCESS)
2093 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2094 ldap_err2string(err));
2095 fail_all(keylist,ldap_err_to_gpg_err(err));
2096 goto fail;
2099 if(!opt->flags.check_cert)
2100 ssl=LDAP_OPT_X_TLS_NEVER;
2102 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
2103 if(err!=LDAP_SUCCESS)
2105 fprintf(console,
2106 "gpgkeys: unable to set certificate validation: %s\n",
2107 ldap_err2string(err));
2108 fail_all(keylist,ldap_err_to_gpg_err(err));
2109 goto fail;
2111 #else
2112 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2113 "not built with LDAPS support");
2114 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2115 goto fail;
2116 #endif
2119 if(!basekeyspacedn)
2120 if((err=find_basekeyspacedn()) || !basekeyspacedn)
2122 fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
2123 err?ldap_err2string(err):"not found");
2124 fail_all(keylist,ldap_err_to_gpg_err(err));
2125 goto fail;
2128 /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
2129 3=force use. */
2130 if(use_tls)
2132 if(!real_ldap)
2134 if(use_tls>=2)
2135 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2136 "not supported by the NAI LDAP keyserver");
2137 if(use_tls==3)
2139 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2140 goto fail;
2143 else
2145 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
2146 int ver=LDAP_VERSION3;
2148 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2150 #ifdef LDAP_OPT_X_TLS
2151 if(err==LDAP_SUCCESS)
2153 if(opt->flags.check_cert)
2154 ver=LDAP_OPT_X_TLS_HARD;
2155 else
2156 ver=LDAP_OPT_X_TLS_NEVER;
2158 err=ldap_set_option(ldap,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
2160 #endif
2162 if(err==LDAP_SUCCESS)
2163 err=ldap_start_tls_s(ldap,NULL,NULL);
2165 if(err!=LDAP_SUCCESS)
2167 if(use_tls>=2 || opt->verbose>2)
2168 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2169 ldap_err2string(err));
2170 /* Are we forcing it? */
2171 if(use_tls==3)
2173 fail_all(keylist,ldap_err_to_gpg_err(err));
2174 goto fail;
2177 else if(opt->verbose>1)
2178 fprintf(console,"gpgkeys: TLS started successfully.\n");
2179 #else
2180 if(use_tls>=2)
2181 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2182 "not built with TLS support");
2183 if(use_tls==3)
2185 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2186 goto fail;
2188 #endif
2192 /* By default we don't bind as there is usually no need to. For
2193 cases where the server needs some authentication, the user can
2194 use binddn and bindpw for auth. */
2196 if(binddn)
2198 #ifdef HAVE_LDAP_SET_OPTION
2199 int ver=LDAP_VERSION3;
2201 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2202 if(err!=LDAP_SUCCESS)
2204 fprintf(console,"gpgkeys: unable to go to LDAP 3: %s\n",
2205 ldap_err2string(err));
2206 fail_all(keylist,ldap_err_to_gpg_err(err));
2207 goto fail;
2209 #endif
2211 if(opt->verbose>2)
2212 fprintf(console,"gpgkeys: LDAP bind to %s, pw %s\n",binddn,
2213 bindpw?">not shown<":">none<");
2214 err=ldap_simple_bind_s(ldap,binddn,bindpw);
2215 if(err!=LDAP_SUCCESS)
2217 fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
2218 ldap_err2string(err));
2219 fail_all(keylist,ldap_err_to_gpg_err(err));
2220 goto fail;
2222 else
2223 bound=1;
2226 if(opt->action==KS_GET)
2228 keyptr=keylist;
2230 while(keyptr!=NULL)
2232 set_timeout(opt->timeout);
2234 if(get_key(keyptr->str)!=KEYSERVER_OK)
2235 failed++;
2237 keyptr=keyptr->next;
2240 else if(opt->action==KS_GETNAME)
2242 keyptr=keylist;
2244 while(keyptr!=NULL)
2246 set_timeout(opt->timeout);
2248 if(get_name(keyptr->str)!=KEYSERVER_OK)
2249 failed++;
2251 keyptr=keyptr->next;
2254 else if(opt->action==KS_SEND)
2256 int eof=0;
2260 set_timeout(opt->timeout);
2262 if(real_ldap)
2264 if(send_key(&eof)!=KEYSERVER_OK)
2265 failed++;
2267 else
2269 if(send_key_keyserver(&eof)!=KEYSERVER_OK)
2270 failed++;
2273 while(!eof);
2275 else if(opt->action==KS_SEARCH)
2277 char *searchkey=NULL;
2278 int len=0;
2280 set_timeout(opt->timeout);
2282 /* To search, we stick a * in between each key to search for.
2283 This means that if the user enters words, they'll get
2284 "enters*words". If the user "enters words", they'll get
2285 "enters words" */
2287 keyptr=keylist;
2288 while(keyptr!=NULL)
2290 len+=strlen(keyptr->str)+1;
2291 keyptr=keyptr->next;
2294 searchkey=malloc(len+1);
2295 if(searchkey==NULL)
2297 ret=KEYSERVER_NO_MEMORY;
2298 fail_all(keylist,KEYSERVER_NO_MEMORY);
2299 goto fail;
2302 searchkey[0]='\0';
2304 keyptr=keylist;
2305 while(keyptr!=NULL)
2307 strcat(searchkey,keyptr->str);
2308 strcat(searchkey,"*");
2309 keyptr=keyptr->next;
2312 /* Nail that last "*" */
2313 if(*searchkey)
2314 searchkey[strlen(searchkey)-1]='\0';
2316 if(search_key(searchkey)!=KEYSERVER_OK)
2317 failed++;
2319 free(searchkey);
2321 else
2322 BUG();
2324 if(!failed)
2325 ret=KEYSERVER_OK;
2327 fail:
2329 while(keylist!=NULL)
2331 struct keylist *current=keylist;
2332 keylist=keylist->next;
2333 free(current);
2336 if(input!=stdin)
2337 fclose(input);
2339 if(output!=stdout)
2340 fclose(output);
2342 free_ks_options(opt);
2344 if(ldap!=NULL && bound)
2345 ldap_unbind_s(ldap);
2347 free(basekeyspacedn);
2349 return ret;