* gpg.texi (OpenPGP Options): Clarify that personal-foo-preferences
[gnupg.git] / keyserver / gpgkeys_ldap.c
blobbd85234668c896910e7c4c9488a3b66d13bfeab2
1 /* gpgkeys_ldap.c - talk to a LDAP keyserver
2 * Copyright (C) 2001, 2002, 2004, 2005, 2006
3 * 2007 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 * In addition, as a special exception, the Free Software Foundation
21 * gives permission to link the code of the keyserver helper tools:
22 * gpgkeys_ldap, gpgkeys_curl and gpgkeys_hkp with the OpenSSL
23 * project's "OpenSSL" library (or with modified versions of it that
24 * use the same license as the "OpenSSL" library), and distribute the
25 * linked executables. You must obey the GNU General Public License
26 * in all respects for all of the code used other than "OpenSSL". If
27 * you modify this file, you may extend this exception to your version
28 * of the file, but you are not obligated to do so. If you do not
29 * wish to do so, delete this exception statement from your version.
32 #include <config.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <time.h>
36 #include <unistd.h>
37 #ifdef HAVE_GETOPT_H
38 #include <getopt.h>
39 #endif
40 #include <stdlib.h>
41 #include <errno.h>
42 #include <assert.h>
44 #ifdef _WIN32
45 #include <winsock2.h>
46 #include <winldap.h>
47 #else
48 #ifdef NEED_LBER_H
49 #include <lber.h>
50 #endif
51 /* For OpenLDAP, to enable the API that we're using. */
52 #define LDAP_DEPRECATED 1
53 #include <ldap.h>
54 #endif
56 #include "util.h"
57 #include "keyserver.h"
58 #include "ksutil.h"
60 #ifdef __riscos__
61 #include "util.h"
62 #endif
64 extern char *optarg;
65 extern int optind;
67 static int real_ldap=0;
68 static char *basekeyspacedn=NULL;
69 static char *pgpkeystr="pgpKey";
70 static FILE *input=NULL,*output=NULL,*console=NULL;
71 static LDAP *ldap=NULL;
72 static struct ks_options *opt;
74 #ifndef HAVE_TIMEGM
75 time_t timegm(struct tm *tm);
76 #endif
78 static int
79 ldap_err_to_gpg_err(int err)
81 int ret;
83 switch(err)
85 case LDAP_ALREADY_EXISTS:
86 ret=KEYSERVER_KEY_EXISTS;
87 break;
89 case LDAP_SERVER_DOWN:
90 ret=KEYSERVER_UNREACHABLE;
91 break;
93 default:
94 ret=KEYSERVER_GENERAL_ERROR;
95 break;
98 return ret;
101 static int
102 ldap_to_gpg_err(LDAP *ld)
104 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
106 int err;
108 if(ldap_get_option(ld,LDAP_OPT_ERROR_NUMBER,&err)==0)
109 return ldap_err_to_gpg_err(err);
110 else
111 return KEYSERVER_GENERAL_ERROR;
113 #elif defined(HAVE_LDAP_LD_ERRNO)
115 return ldap_err_to_gpg_err(ld->ld_errno);
117 #else
119 /* We should never get here since the LDAP library should always
120 have either ldap_get_option or ld_errno, but just in case... */
121 return KEYSERVER_GENERAL_ERROR;
123 #endif
126 static int
127 key_in_keylist(const char *key,struct keylist *list)
129 struct keylist *keyptr=list;
131 while(keyptr!=NULL)
133 if(strcasecmp(key,keyptr->str)==0)
134 return 1;
136 keyptr=keyptr->next;
139 return 0;
142 static int
143 add_key_to_keylist(const char *key,struct keylist **list)
145 struct keylist *keyptr=malloc(sizeof(struct keylist));
147 if(keyptr==NULL)
149 fprintf(console,"gpgkeys: out of memory when deduping "
150 "key list\n");
151 return KEYSERVER_NO_MEMORY;
154 strncpy(keyptr->str,key,MAX_LINE);
155 keyptr->str[MAX_LINE-1]='\0';
156 keyptr->next=*list;
157 *list=keyptr;
159 return 0;
162 static void
163 free_keylist(struct keylist *list)
165 while(list!=NULL)
167 struct keylist *keyptr=list;
169 list=keyptr->next;
170 free(keyptr);
174 static time_t
175 ldap2epochtime(const char *timestr)
177 struct tm pgptime;
178 time_t answer;
180 memset(&pgptime,0,sizeof(pgptime));
182 /* YYYYMMDDHHmmssZ */
184 sscanf(timestr,"%4d%2d%2d%2d%2d%2d",
185 &pgptime.tm_year,
186 &pgptime.tm_mon,
187 &pgptime.tm_mday,
188 &pgptime.tm_hour,
189 &pgptime.tm_min,
190 &pgptime.tm_sec);
192 pgptime.tm_year-=1900;
193 pgptime.tm_isdst=-1;
194 pgptime.tm_mon--;
196 /* mktime() takes the timezone into account, so we use timegm() */
198 answer=timegm(&pgptime);
200 return answer;
203 /* Caller must free */
204 static char *
205 epoch2ldaptime(time_t stamp)
207 struct tm *ldaptime;
208 char buf[16];
210 ldaptime=gmtime(&stamp);
212 ldaptime->tm_year+=1900;
213 ldaptime->tm_mon++;
215 /* YYYYMMDDHHmmssZ */
217 sprintf(buf,"%04d%02d%02d%02d%02d%02dZ",
218 ldaptime->tm_year,
219 ldaptime->tm_mon,
220 ldaptime->tm_mday,
221 ldaptime->tm_hour,
222 ldaptime->tm_min,
223 ldaptime->tm_sec);
225 return strdup(buf);
228 /* Append two onto the end of one. Two is not freed, but its pointers
229 are now part of one. Make sure you don't free them both! */
230 static int
231 join_two_modlists(LDAPMod ***one,LDAPMod **two)
233 int i,one_count=0,two_count=0;
234 LDAPMod **grow;
236 for(grow=*one;*grow;grow++)
237 one_count++;
239 for(grow=two;*grow;grow++)
240 two_count++;
242 grow=realloc(*one,sizeof(LDAPMod *)*(one_count+two_count+1));
243 if(!grow)
244 return 0;
246 for(i=0;i<two_count;i++)
247 grow[one_count+i]=two[i];
249 grow[one_count+i]=NULL;
251 *one=grow;
253 return 1;
256 /* Passing a NULL for value effectively deletes that attribute. This
257 doesn't mean "delete" in the sense of removing something from the
258 modlist, but "delete" in the LDAP sense of adding a modlist item
259 that specifies LDAP_MOD_REPLACE and a null attribute for the given
260 attribute. LDAP_MOD_DELETE doesn't work here as we don't know if
261 the attribute in question exists or not. */
263 static int
264 make_one_attr(LDAPMod ***modlist,char *attr,const char *value)
266 LDAPMod **m;
267 int nummods=0;
269 /* Search modlist for the attribute we're playing with. */
270 for(m=*modlist;*m;m++)
272 if(strcasecmp((*m)->mod_type,attr)==0)
274 char **ptr=(*m)->mod_values;
275 int numvalues=0;
277 /* We have this attribute already, so when the REPLACE
278 happens, the server attributes will be replaced
279 anyway. */
280 if(!value)
281 return 1;
283 if(ptr)
284 for(ptr=(*m)->mod_values;*ptr;ptr++)
286 /* Duplicate value */
287 if(strcmp(*ptr,value)==0)
288 return 1;
289 numvalues++;
292 ptr=realloc((*m)->mod_values,sizeof(char *)*(numvalues+2));
293 if(!ptr)
294 return 0;
296 (*m)->mod_values=ptr;
297 ptr[numvalues]=strdup(value);
298 if(!ptr[numvalues])
299 return 0;
301 ptr[numvalues+1]=NULL;
302 break;
305 nummods++;
308 /* We didn't find the attr, so make one and add it to the end */
309 if(!*m)
311 LDAPMod **grow;
313 grow=realloc(*modlist,sizeof(LDAPMod *)*(nummods+2));
314 if(!grow)
315 return 0;
317 *modlist=grow;
318 grow[nummods]=malloc(sizeof(LDAPMod));
319 if(!grow[nummods])
320 return 0;
321 grow[nummods]->mod_op=LDAP_MOD_REPLACE;
322 grow[nummods]->mod_type=attr;
323 if(value)
325 grow[nummods]->mod_values=malloc(sizeof(char *)*2);
326 if(!grow[nummods]->mod_values)
328 grow[nummods]=NULL;
329 return 0;
332 /* Is this the right thing? Can a UTF8-encoded user ID have
333 embedded nulls? */
334 grow[nummods]->mod_values[0]=strdup(value);
335 if(!grow[nummods]->mod_values[0])
337 free(grow[nummods]->mod_values);
338 grow[nummods]=NULL;
339 return 0;
342 grow[nummods]->mod_values[1]=NULL;
344 else
345 grow[nummods]->mod_values=NULL;
347 grow[nummods+1]=NULL;
350 return 1;
353 static void
354 build_attrs(LDAPMod ***modlist,char *line)
356 char *record;
357 int i;
359 /* Remove trailing whitespace */
360 for(i=strlen(line);i>0;i--)
361 if(ascii_isspace(line[i-1]))
362 line[i-1]='\0';
363 else
364 break;
366 if((record=strsep(&line,":"))==NULL)
367 return;
369 if(ks_strcasecmp("pub",record)==0)
371 char *tok;
372 int disabled=0,revoked=0;
374 /* The long keyid */
375 if((tok=strsep(&line,":"))==NULL)
376 return;
378 if(strlen(tok)==16)
380 make_one_attr(modlist,"pgpCertID",tok);
381 make_one_attr(modlist,"pgpKeyID",&tok[8]);
383 else
384 return;
386 /* The primary pubkey algo */
387 if((tok=strsep(&line,":"))==NULL)
388 return;
390 switch(atoi(tok))
392 case 1:
393 make_one_attr(modlist,"pgpKeyType","RSA");
394 break;
396 case 17:
397 make_one_attr(modlist,"pgpKeyType","DSS/DH");
398 break;
401 /* Size of primary key */
402 if((tok=strsep(&line,":"))==NULL)
403 return;
405 if(atoi(tok)>0)
407 char padded[6];
408 int val=atoi(tok);
410 /* We zero pad this on the left to make PGP happy. */
412 if(val<99999 && val>0)
414 sprintf(padded,"%05u",atoi(tok));
415 make_one_attr(modlist,"pgpKeySize",padded);
419 /* pk timestamp */
420 if((tok=strsep(&line,":"))==NULL)
421 return;
423 if(atoi(tok)>0)
425 char *stamp=epoch2ldaptime(atoi(tok));
426 if(stamp)
428 make_one_attr(modlist,"pgpKeyCreateTime",stamp);
429 free(stamp);
433 /* pk expire */
434 if((tok=strsep(&line,":"))==NULL)
435 return;
437 if(atoi(tok)>0)
439 char *stamp=epoch2ldaptime(atoi(tok));
440 if(stamp)
442 make_one_attr(modlist,"pgpKeyExpireTime",stamp);
443 free(stamp);
447 /* flags */
448 if((tok=strsep(&line,":"))==NULL)
449 return;
451 while(*tok)
452 switch(*tok++)
454 case 'r':
455 case 'R':
456 revoked=1;
457 break;
459 case 'd':
460 case 'D':
461 disabled=1;
462 break;
466 Note that we always create the pgpDisabled and pgpRevoked
467 attributes, regardless of whether the key is disabled/revoked
468 or not. This is because a very common search is like
469 "(&(pgpUserID=*isabella*)(pgpDisabled=0))"
472 make_one_attr(modlist,"pgpDisabled",disabled?"1":"0");
473 make_one_attr(modlist,"pgpRevoked",revoked?"1":"0");
475 else if(ks_strcasecmp("sub",record)==0)
477 char *tok;
479 /* The long keyid */
480 if((tok=strsep(&line,":"))==NULL)
481 return;
483 if(strlen(tok)==16)
484 make_one_attr(modlist,"pgpSubKeyID",tok);
485 else
486 return;
488 /* The subkey algo */
489 if((tok=strsep(&line,":"))==NULL)
490 return;
492 /* Size of subkey */
493 if((tok=strsep(&line,":"))==NULL)
494 return;
496 if(atoi(tok)>0)
498 char padded[6];
499 int val=atoi(tok);
501 /* We zero pad this on the left to make PGP happy. */
503 if(val<99999 && val>0)
505 sprintf(padded,"%05u",atoi(tok));
506 make_one_attr(modlist,"pgpKeySize",padded);
510 /* Ignore the rest of the items for subkeys since the LDAP
511 schema doesn't store them. */
513 else if(ks_strcasecmp("uid",record)==0)
515 char *userid,*tok;
517 /* The user ID string */
518 if((tok=strsep(&line,":"))==NULL)
519 return;
521 if(strlen(tok)==0)
522 return;
524 userid=tok;
526 /* By definition, de-%-encoding is always smaller than the
527 original string so we can decode in place. */
529 i=0;
531 while(*tok)
532 if(tok[0]=='%' && tok[1] && tok[2])
534 int c;
536 userid[i] = (c=hextobyte(&tok[1])) == -1 ? '?' : c;
537 i++;
538 tok+=3;
540 else
541 userid[i++]=*tok++;
543 userid[i]='\0';
545 /* We don't care about the other info provided in the uid: line
546 since the LDAP schema doesn't need it. */
548 make_one_attr(modlist,"pgpUserID",userid);
550 else if(ks_strcasecmp("sig",record)==0)
552 char *tok;
554 if((tok=strsep(&line,":"))==NULL)
555 return;
557 if(strlen(tok)==16)
558 make_one_attr(modlist,"pgpSignerID",tok);
562 static void
563 free_mod_values(LDAPMod *mod)
565 char **ptr;
567 if(!mod->mod_values)
568 return;
570 for(ptr=mod->mod_values;*ptr;ptr++)
571 free(*ptr);
573 free(mod->mod_values);
576 static int
577 send_key(int *r_eof)
579 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
580 char *dn=NULL,line[MAX_LINE],*key=NULL;
581 char keyid[17],state[6];
582 LDAPMod **modlist,**addlist,**ml;
584 modlist=malloc(sizeof(LDAPMod *));
585 if(!modlist)
587 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
588 ret=KEYSERVER_NO_MEMORY;
589 goto fail;
592 *modlist=NULL;
594 addlist=malloc(sizeof(LDAPMod *));
595 if(!addlist)
597 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
598 ret=KEYSERVER_NO_MEMORY;
599 goto fail;
602 *addlist=NULL;
604 /* Start by nulling out all attributes. We try and do a modify
605 operation first, so this ensures that we don't leave old
606 attributes lying around. */
607 make_one_attr(&modlist,"pgpDisabled",NULL);
608 make_one_attr(&modlist,"pgpKeyID",NULL);
609 make_one_attr(&modlist,"pgpKeyType",NULL);
610 make_one_attr(&modlist,"pgpUserID",NULL);
611 make_one_attr(&modlist,"pgpKeyCreateTime",NULL);
612 make_one_attr(&modlist,"pgpSignerID",NULL);
613 make_one_attr(&modlist,"pgpRevoked",NULL);
614 make_one_attr(&modlist,"pgpSubKeyID",NULL);
615 make_one_attr(&modlist,"pgpKeySize",NULL);
616 make_one_attr(&modlist,"pgpKeyExpireTime",NULL);
617 make_one_attr(&modlist,"pgpCertID",NULL);
619 /* Assemble the INFO stuff into LDAP attributes */
621 while(fgets(line,MAX_LINE,input)!=NULL)
622 if(sscanf(line,"INFO%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
623 && strcmp(state,"BEGIN")==0)
625 begin=1;
626 break;
629 if(!begin)
631 /* i.e. eof before the INFO BEGIN was found. This isn't an
632 error. */
633 *r_eof=1;
634 ret=KEYSERVER_OK;
635 goto fail;
638 if(strlen(keyid)!=16)
640 *r_eof=1;
641 ret=KEYSERVER_KEY_INCOMPLETE;
642 goto fail;
645 dn=malloc(strlen("pgpCertID=")+16+1+strlen(basekeyspacedn)+1);
646 if(dn==NULL)
648 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
649 ret=KEYSERVER_NO_MEMORY;
650 goto fail;
653 sprintf(dn,"pgpCertID=%s,%s",keyid,basekeyspacedn);
655 key=malloc(1);
656 if(!key)
658 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
659 ret=KEYSERVER_NO_MEMORY;
660 goto fail;
663 key[0]='\0';
665 /* Now parse each line until we see the END */
667 while(fgets(line,MAX_LINE,input)!=NULL)
668 if(sscanf(line,"INFO%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
669 && strcmp(state,"END")==0)
671 end=1;
672 break;
674 else
675 build_attrs(&addlist,line);
677 if(!end)
679 fprintf(console,"gpgkeys: no INFO %s END found\n",keyid);
680 *r_eof=1;
681 ret=KEYSERVER_KEY_INCOMPLETE;
682 goto fail;
685 begin=end=0;
687 /* Read and throw away stdin until we see the BEGIN */
689 while(fgets(line,MAX_LINE,input)!=NULL)
690 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
691 && strcmp(state,"BEGIN")==0)
693 begin=1;
694 break;
697 if(!begin)
699 /* i.e. eof before the KEY BEGIN was found. This isn't an
700 error. */
701 *r_eof=1;
702 ret=KEYSERVER_OK;
703 goto fail;
706 /* Now slurp up everything until we see the END */
708 while(fgets(line,MAX_LINE,input)!=NULL)
709 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
710 && strcmp(state,"END")==0)
712 end=1;
713 break;
715 else
717 char *tempkey;
718 keysize+=strlen(line);
719 tempkey=realloc(key,keysize);
720 if(tempkey==NULL)
722 fprintf(console,"gpgkeys: unable to reallocate for key\n");
723 ret=KEYSERVER_NO_MEMORY;
724 goto fail;
726 else
727 key=tempkey;
729 strcat(key,line);
732 if(!end)
734 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
735 *r_eof=1;
736 ret=KEYSERVER_KEY_INCOMPLETE;
737 goto fail;
740 make_one_attr(&addlist,"objectClass","pgpKeyInfo");
741 make_one_attr(&addlist,"pgpKey",key);
743 /* Now append addlist onto modlist */
744 if(!join_two_modlists(&modlist,addlist))
746 fprintf(console,"gpgkeys: unable to merge LDAP modification lists\n");
747 ret=KEYSERVER_NO_MEMORY;
748 goto fail;
751 /* Going on the assumption that modify operations are more frequent
752 than adds, we try a modify first. If it's not there, we just
753 turn around and send an add command for the same key. Otherwise,
754 the modify brings the server copy into compliance with our copy.
755 Note that unlike the LDAP keyserver (and really, any other
756 keyserver) this does NOT merge signatures, but replaces the whole
757 key. This should make some people very happy. */
759 err=ldap_modify_s(ldap,dn,modlist);
760 if(err==LDAP_NO_SUCH_OBJECT)
761 err=ldap_add_s(ldap,dn,addlist);
763 if(err!=LDAP_SUCCESS)
765 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
766 keyid,ldap_err2string(err));
767 ret=ldap_err_to_gpg_err(err);
768 goto fail;
771 ret=KEYSERVER_OK;
773 fail:
774 if (modlist)
776 /* Unwind and free the whole modlist structure */
777 for(ml=modlist;*ml;ml++)
779 free_mod_values(*ml);
780 free(*ml);
782 free(modlist);
784 free(addlist);
785 free(dn);
786 free(key);
788 if(ret!=0 && begin)
789 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
791 return ret;
794 static int
795 send_key_keyserver(int *r_eof)
797 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
798 char *dn=NULL,line[MAX_LINE],*key[2]={NULL,NULL};
799 char keyid[17],state[6];
800 LDAPMod mod, *attrs[2];
802 memset(&mod,0,sizeof(mod));
803 mod.mod_op=LDAP_MOD_ADD;
804 mod.mod_type=pgpkeystr;
805 mod.mod_values=key;
806 attrs[0]=&mod;
807 attrs[1]=NULL;
809 dn=malloc(strlen("pgpCertid=virtual,")+strlen(basekeyspacedn)+1);
810 if(dn==NULL)
812 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
813 ret=KEYSERVER_NO_MEMORY;
814 goto fail;
817 strcpy(dn,"pgpCertid=virtual,");
818 strcat(dn,basekeyspacedn);
820 key[0]=malloc(1);
821 if(key[0]==NULL)
823 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
824 ret=KEYSERVER_NO_MEMORY;
825 goto fail;
828 key[0][0]='\0';
830 /* Read and throw away stdin until we see the BEGIN */
832 while(fgets(line,MAX_LINE,input)!=NULL)
833 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
834 && strcmp(state,"BEGIN")==0)
836 begin=1;
837 break;
840 if(!begin)
842 /* i.e. eof before the KEY BEGIN was found. This isn't an
843 error. */
844 *r_eof=1;
845 ret=KEYSERVER_OK;
846 goto fail;
849 /* Now slurp up everything until we see the END */
851 while(fgets(line,MAX_LINE,input)!=NULL)
852 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
853 && strcmp(state,"END")==0)
855 end=1;
856 break;
858 else
860 keysize+=strlen(line);
861 key[0]=realloc(key[0],keysize);
862 if(key[0]==NULL)
864 fprintf(console,"gpgkeys: unable to reallocate for key\n");
865 ret=KEYSERVER_NO_MEMORY;
866 goto fail;
869 strcat(key[0],line);
872 if(!end)
874 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
875 *r_eof=1;
876 ret=KEYSERVER_KEY_INCOMPLETE;
877 goto fail;
880 err=ldap_add_s(ldap,dn,attrs);
881 if(err!=LDAP_SUCCESS)
883 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
884 keyid,ldap_err2string(err));
885 ret=ldap_err_to_gpg_err(err);
886 goto fail;
889 ret=KEYSERVER_OK;
891 fail:
893 free(key[0]);
894 free(dn);
896 if(ret!=0 && begin)
897 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
899 /* Not a fatal error */
900 if(ret==KEYSERVER_KEY_EXISTS)
901 ret=KEYSERVER_OK;
903 return ret;
906 static void
907 build_info(const char *certid,LDAPMessage *each)
909 char **vals;
911 fprintf(output,"INFO %s BEGIN\n",certid);
913 fprintf(output,"pub:%s:",certid);
915 vals=ldap_get_values(ldap,each,"pgpkeytype");
916 if(vals!=NULL)
918 if(strcmp(vals[0],"RSA")==0)
919 fprintf(output,"1");
920 else if(strcmp(vals[0],"DSS/DH")==0)
921 fprintf(output,"17");
922 ldap_value_free(vals);
925 fprintf(output,":");
927 vals=ldap_get_values(ldap,each,"pgpkeysize");
928 if(vals!=NULL)
930 if(atoi(vals[0])>0)
931 fprintf(output,"%d",atoi(vals[0]));
932 ldap_value_free(vals);
935 fprintf(output,":");
937 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
938 if(vals!=NULL)
940 if(strlen(vals[0])==15)
941 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
942 ldap_value_free(vals);
945 fprintf(output,":");
947 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
948 if(vals!=NULL)
950 if(strlen(vals[0])==15)
951 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
952 ldap_value_free(vals);
955 fprintf(output,":");
957 vals=ldap_get_values(ldap,each,"pgprevoked");
958 if(vals!=NULL)
960 if(atoi(vals[0])==1)
961 fprintf(output,"r");
962 ldap_value_free(vals);
965 fprintf(output,"\n");
967 vals=ldap_get_values(ldap,each,"pgpuserid");
968 if(vals!=NULL)
970 int i;
972 for(i=0;vals[i];i++)
973 fprintf(output,"uid:%s\n",vals[i]);
974 ldap_value_free(vals);
977 fprintf(output,"INFO %s END\n",certid);
980 /* Note that key-not-found is not a fatal error */
981 static int
982 get_key(char *getkey)
984 LDAPMessage *res,*each;
985 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
986 struct keylist *dupelist=NULL;
987 char search[62];
988 /* This ordering is significant - specifically, "pgpcertid" needs to
989 be the second item in the list, since everything after it may be
990 discarded if the user isn't in verbose mode. */
991 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
992 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
993 "pgpkeysize","pgpkeytype",NULL};
994 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
995 array initializers. */
997 /* Build the search string */
999 /* GPG can send us a v4 fingerprint, a v3 or v4 long key id, or a v3
1000 or v4 short key id */
1002 if(strncmp(getkey,"0x",2)==0)
1003 getkey+=2;
1005 if(strlen(getkey)==32)
1007 fprintf(console,
1008 "gpgkeys: LDAP keyservers do not support v3 fingerprints\n");
1009 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1010 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_NOT_SUPPORTED);
1011 return KEYSERVER_NOT_SUPPORTED;
1014 if(strlen(getkey)>16)
1016 char *offset=&getkey[strlen(getkey)-16];
1018 /* fingerprint. Take the last 16 characters and treat it like a
1019 long key id */
1021 if(opt->flags.include_subkeys)
1022 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1023 offset,offset);
1024 else
1025 sprintf(search,"(pgpcertid=%.16s)",offset);
1027 else if(strlen(getkey)>8)
1029 /* long key id */
1031 if(opt->flags.include_subkeys)
1032 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1033 getkey,getkey);
1034 else
1035 sprintf(search,"(pgpcertid=%.16s)",getkey);
1037 else
1039 /* short key id */
1041 sprintf(search,"(pgpkeyid=%.8s)",getkey);
1044 if(opt->verbose>2)
1045 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1047 if(!opt->verbose)
1048 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1050 err=ldap_search_s(ldap,basekeyspacedn,
1051 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1052 if(err!=0)
1054 int errtag=ldap_err_to_gpg_err(err);
1056 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1057 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1058 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1059 return errtag;
1062 count=ldap_count_entries(ldap,res);
1063 if(count<1)
1065 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1066 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1067 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1069 else
1071 /* There may be more than one unique result for a given keyID,
1072 so we should fetch them all (test this by fetching short key
1073 id 0xDEADBEEF). */
1075 each=ldap_first_entry(ldap,res);
1076 while(each!=NULL)
1078 char **vals,**certid;
1080 /* Use the long keyid to remove duplicates. The LDAP server
1081 returns the same keyid more than once if there are
1082 multiple user IDs on the key. Note that this does NOT
1083 mean that a keyid that exists multiple times on the
1084 keyserver will not be fetched. It means that each KEY,
1085 no matter how many user IDs share its keyid, will be
1086 fetched only once. If a keyid that belongs to more than
1087 one key is fetched, the server quite properly responds
1088 with all matching keys. -ds */
1090 certid=ldap_get_values(ldap,each,"pgpcertid");
1091 if(certid!=NULL)
1093 if(!key_in_keylist(certid[0],dupelist))
1095 /* it's not a duplicate, so add it */
1097 int rc=add_key_to_keylist(certid[0],&dupelist);
1098 if(rc)
1100 ret=rc;
1101 goto fail;
1104 build_info(certid[0],each);
1106 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1108 vals=ldap_get_values(ldap,each,pgpkeystr);
1109 if(vals==NULL)
1111 int errtag=ldap_to_gpg_err(ldap);
1113 fprintf(console,"gpgkeys: unable to retrieve key %s "
1114 "from keyserver\n",getkey);
1115 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1117 else
1119 print_nocr(output,vals[0]);
1120 fprintf(output,"\nKEY 0x%s END\n",getkey);
1122 ldap_value_free(vals);
1126 ldap_value_free(certid);
1129 each=ldap_next_entry(ldap,each);
1133 ret=KEYSERVER_OK;
1135 fail:
1136 ldap_msgfree(res);
1137 free_keylist(dupelist);
1139 return ret;
1142 #define LDAP_ESCAPE_CHARS "*()\\"
1144 /* Append string to buffer in a LDAP-quoted way */
1145 static void
1146 ldap_quote(char *buffer,const char *string)
1148 /* Find the end of buffer */
1149 buffer+=strlen(buffer);
1151 for(;*string;string++)
1153 if(strchr(LDAP_ESCAPE_CHARS,*string))
1155 sprintf(buffer,"\\%02X",*string);
1156 buffer+=3;
1158 else
1159 *buffer++=*string;
1162 *buffer='\0';
1165 /* Note that key-not-found is not a fatal error */
1166 static int
1167 get_name(char *getkey)
1169 LDAPMessage *res,*each;
1170 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
1171 /* The maximum size of the search, including the optional stuff and
1172 the trailing \0 */
1173 char search[2+12+(MAX_LINE*3)+2+15+14+1+1+20];
1174 /* This ordering is significant - specifically, "pgpcertid" needs to
1175 be the second item in the list, since everything after it may be
1176 discarded if the user isn't in verbose mode. */
1177 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
1178 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
1179 "pgpkeysize","pgpkeytype",NULL};
1180 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1181 array initializers. */
1183 /* Build the search string */
1185 search[0]='\0';
1187 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1188 strcat(search,"(&");
1190 strcat(search,"(pgpUserID=*");
1191 ldap_quote(search,getkey);
1192 strcat(search,"*)");
1194 if(!opt->flags.include_disabled)
1195 strcat(search,"(pgpDisabled=0)");
1197 if(!opt->flags.include_revoked)
1198 strcat(search,"(pgpRevoked=0)");
1200 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1201 strcat(search,")");
1203 if(opt->verbose>2)
1204 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1206 if(!opt->verbose)
1207 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1209 err=ldap_search_s(ldap,basekeyspacedn,
1210 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1211 if(err!=0)
1213 int errtag=ldap_err_to_gpg_err(err);
1215 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1216 fprintf(output,"NAME %s BEGIN\n",getkey);
1217 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1218 return errtag;
1221 count=ldap_count_entries(ldap,res);
1222 if(count<1)
1224 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1225 fprintf(output,"NAME %s BEGIN\n",getkey);
1226 fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1228 else
1230 /* There may be more than one result, but we return them all. */
1232 each=ldap_first_entry(ldap,res);
1233 while(each!=NULL)
1235 char **vals,**certid;
1237 certid=ldap_get_values(ldap,each,"pgpcertid");
1238 if(certid!=NULL)
1240 build_info(certid[0],each);
1242 fprintf(output,"NAME %s BEGIN\n",getkey);
1244 vals=ldap_get_values(ldap,each,pgpkeystr);
1245 if(vals==NULL)
1247 int errtag=ldap_to_gpg_err(ldap);
1249 fprintf(console,"gpgkeys: unable to retrieve key %s "
1250 "from keyserver\n",getkey);
1251 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1253 else
1255 print_nocr(output,vals[0]);
1256 fprintf(output,"\nNAME %s END\n",getkey);
1258 ldap_value_free(vals);
1261 ldap_value_free(certid);
1264 each=ldap_next_entry(ldap,each);
1268 ret=KEYSERVER_OK;
1270 ldap_msgfree(res);
1272 return ret;
1275 static void
1276 printquoted(FILE *stream,char *string,char delim)
1278 while(*string)
1280 if(*string==delim || *string=='%')
1281 fprintf(stream,"%%%02x",*string);
1282 else
1283 fputc(*string,stream);
1285 string++;
1289 /* Returns 0 on success and -1 on error. Note that key-not-found is
1290 not an error! */
1291 static int
1292 search_key(const char *searchkey)
1294 char **vals,*search;
1295 LDAPMessage *res,*each;
1296 int err,count=0;
1297 struct keylist *dupelist=NULL;
1298 /* The maximum size of the search, including the optional stuff and
1299 the trailing \0 */
1300 char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1301 "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1302 "pgpkeysize","pgpkeytype",NULL};
1303 enum ks_search_type search_type;
1305 search=malloc(2+1+9+1+3+strlen(searchkey)+3+1+15+14+1+1+20);
1306 if(!search)
1308 fprintf(console,"gpgkeys: out of memory when building search list\n");
1309 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,KEYSERVER_NO_MEMORY);
1310 return KEYSERVER_NO_MEMORY;
1313 fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1315 search_type=classify_ks_search(&searchkey);
1317 if(opt->debug)
1318 fprintf(console,"search type is %d, and key is \"%s\"\n",
1319 search_type,searchkey);
1321 /* Build the search string */
1323 search[0]='\0';
1325 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1326 strcat(search,"(&");
1328 strcat(search,"(");
1330 switch(search_type)
1332 case KS_SEARCH_KEYID_SHORT:
1333 strcat(search,"pgpKeyID");
1334 break;
1336 case KS_SEARCH_KEYID_LONG:
1337 strcat(search,"pgpCertID");
1338 break;
1340 default:
1341 strcat(search,"pgpUserID");
1342 break;
1345 strcat(search,"=");
1347 switch(search_type)
1349 case KS_SEARCH_SUBSTR:
1350 strcat(search,"*");
1351 break;
1353 case KS_SEARCH_MAIL:
1354 strcat(search,"*<");
1355 break;
1357 case KS_SEARCH_MAILSUB:
1358 strcat(search,"*<*");
1359 break;
1361 case KS_SEARCH_EXACT:
1362 case KS_SEARCH_KEYID_LONG:
1363 case KS_SEARCH_KEYID_SHORT:
1364 break;
1367 strcat(search,searchkey);
1369 switch(search_type)
1371 case KS_SEARCH_SUBSTR:
1372 strcat(search,"*");
1373 break;
1375 case KS_SEARCH_MAIL:
1376 strcat(search,">*");
1377 break;
1379 case KS_SEARCH_MAILSUB:
1380 strcat(search,"*>*");
1381 break;
1383 case KS_SEARCH_EXACT:
1384 case KS_SEARCH_KEYID_LONG:
1385 case KS_SEARCH_KEYID_SHORT:
1386 break;
1389 strcat(search,")");
1391 if(!opt->flags.include_disabled)
1392 strcat(search,"(pgpDisabled=0)");
1394 if(!opt->flags.include_revoked)
1395 strcat(search,"(pgpRevoked=0)");
1397 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1398 strcat(search,")");
1400 if(opt->verbose>2)
1401 fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1403 err=ldap_search_s(ldap,basekeyspacedn,
1404 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1405 free(search);
1406 if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1408 int errtag=ldap_err_to_gpg_err(err);
1410 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1411 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1412 return errtag;
1415 /* The LDAP server doesn't return a real count of unique keys, so we
1416 can't use ldap_count_entries here. */
1417 each=ldap_first_entry(ldap,res);
1418 while(each!=NULL)
1420 char **certid=ldap_get_values(ldap,each,"pgpcertid");
1422 if(certid!=NULL)
1424 if(!key_in_keylist(certid[0],dupelist))
1426 int rc=add_key_to_keylist(certid[0],&dupelist);
1427 if(rc!=0)
1429 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1430 free_keylist(dupelist);
1431 return rc;
1434 count++;
1438 each=ldap_next_entry(ldap,each);
1441 if(err==LDAP_SIZELIMIT_EXCEEDED)
1443 if(count==1)
1444 fprintf(console,"gpgkeys: search results exceeded server limit."
1445 " First %d result shown.\n",count);
1446 else
1447 fprintf(console,"gpgkeys: search results exceeded server limit."
1448 " First %d results shown.\n",count);
1451 free_keylist(dupelist);
1452 dupelist=NULL;
1454 if(count<1)
1455 fprintf(output,"info:1:0\n");
1456 else
1458 fprintf(output,"info:1:%d\n",count);
1460 each=ldap_first_entry(ldap,res);
1461 while(each!=NULL)
1463 char **certid;
1465 certid=ldap_get_values(ldap,each,"pgpcertid");
1466 if(certid!=NULL)
1468 LDAPMessage *uids;
1470 /* Have we seen this certid before? */
1471 if(!key_in_keylist(certid[0],dupelist))
1473 int rc=add_key_to_keylist(certid[0],&dupelist);
1474 if(rc)
1476 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1477 free_keylist(dupelist);
1478 ldap_value_free(certid);
1479 ldap_msgfree(res);
1480 return rc;
1483 fprintf(output,"pub:%s:",certid[0]);
1485 vals=ldap_get_values(ldap,each,"pgpkeytype");
1486 if(vals!=NULL)
1488 /* The LDAP server doesn't exactly handle this
1489 well. */
1490 if(strcasecmp(vals[0],"RSA")==0)
1491 fprintf(output,"1");
1492 else if(strcasecmp(vals[0],"DSS/DH")==0)
1493 fprintf(output,"17");
1494 ldap_value_free(vals);
1497 fputc(':',output);
1499 vals=ldap_get_values(ldap,each,"pgpkeysize");
1500 if(vals!=NULL)
1502 /* Not sure why, but some keys are listed with a
1503 key size of 0. Treat that like an
1504 unknown. */
1505 if(atoi(vals[0])>0)
1506 fprintf(output,"%d",atoi(vals[0]));
1507 ldap_value_free(vals);
1510 fputc(':',output);
1512 /* YYYYMMDDHHmmssZ */
1514 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1515 if(vals!=NULL && strlen(vals[0])==15)
1517 fprintf(output,"%u",
1518 (unsigned int)ldap2epochtime(vals[0]));
1519 ldap_value_free(vals);
1522 fputc(':',output);
1524 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
1525 if(vals!=NULL && strlen(vals[0])==15)
1527 fprintf(output,"%u",
1528 (unsigned int)ldap2epochtime(vals[0]));
1529 ldap_value_free(vals);
1532 fputc(':',output);
1534 vals=ldap_get_values(ldap,each,"pgprevoked");
1535 if(vals!=NULL)
1537 if(atoi(vals[0])==1)
1538 fprintf(output,"r");
1539 ldap_value_free(vals);
1542 vals=ldap_get_values(ldap,each,"pgpdisabled");
1543 if(vals!=NULL)
1545 if(atoi(vals[0])==1)
1546 fprintf(output,"d");
1547 ldap_value_free(vals);
1550 #if 0
1551 /* This is not yet specified in the keyserver
1552 protocol, but may be someday. */
1553 fputc(':',output);
1555 vals=ldap_get_values(ldap,each,"modifytimestamp");
1556 if(vals!=NULL && strlen(vals[0])==15)
1558 fprintf(output,"%u",
1559 (unsigned int)ldap2epochtime(vals[0]));
1560 ldap_value_free(vals);
1562 #endif
1564 fprintf(output,"\n");
1566 /* Now print all the uids that have this certid */
1567 uids=ldap_first_entry(ldap,res);
1568 while(uids!=NULL)
1570 vals=ldap_get_values(ldap,uids,"pgpcertid");
1571 if(vals!=NULL)
1573 if(strcasecmp(certid[0],vals[0])==0)
1575 char **uidvals;
1577 fprintf(output,"uid:");
1579 uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1580 if(uidvals!=NULL)
1582 /* Need to escape any colons */
1583 printquoted(output,uidvals[0],':');
1584 ldap_value_free(uidvals);
1587 fprintf(output,"\n");
1590 ldap_value_free(vals);
1593 uids=ldap_next_entry(ldap,uids);
1597 ldap_value_free(certid);
1600 each=ldap_next_entry(ldap,each);
1604 ldap_msgfree(res);
1605 free_keylist(dupelist);
1607 fprintf(output,"SEARCH %s END\n",searchkey);
1609 return KEYSERVER_OK;
1612 static void
1613 fail_all(struct keylist *keylist,int err)
1615 if(!keylist)
1616 return;
1618 if(opt->action==KS_SEARCH)
1620 fprintf(output,"SEARCH ");
1621 while(keylist)
1623 fprintf(output,"%s ",keylist->str);
1624 keylist=keylist->next;
1626 fprintf(output,"FAILED %d\n",err);
1628 else
1629 while(keylist)
1631 fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1632 keylist=keylist->next;
1636 static int
1637 find_basekeyspacedn(void)
1639 int err,i;
1640 char *attr[]={"namingContexts",NULL,NULL,NULL};
1641 LDAPMessage *res;
1642 char **context;
1644 /* Look for namingContexts */
1645 err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1646 if(err==LDAP_SUCCESS)
1648 context=ldap_get_values(ldap,res,"namingContexts");
1649 if(context)
1651 attr[0]="pgpBaseKeySpaceDN";
1652 attr[1]="pgpVersion";
1653 attr[2]="pgpSoftware";
1655 real_ldap=1;
1657 /* We found some, so try each namingContext as the search base
1658 and look for pgpBaseKeySpaceDN. Because we found this, we
1659 know we're talking to a regular-ish LDAP server and not a
1660 LDAP keyserver. */
1662 for(i=0;context[i] && !basekeyspacedn;i++)
1664 char **vals;
1665 LDAPMessage *si_res;
1666 char *object;
1668 object=malloc(17+strlen(context[i])+1);
1669 if(!object)
1670 return -1;
1672 strcpy(object,"cn=pgpServerInfo,");
1673 strcat(object,context[i]);
1675 err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1676 "(objectClass=*)",attr,0,&si_res);
1677 free(object);
1679 if(err==LDAP_NO_SUCH_OBJECT)
1680 continue;
1681 else if(err!=LDAP_SUCCESS)
1682 return err;
1684 vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1685 if(vals)
1687 basekeyspacedn=strdup(vals[0]);
1688 ldap_value_free(vals);
1691 if(opt->verbose>1)
1693 vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1694 if(vals)
1696 fprintf(console,"Server: \t%s\n",vals[0]);
1697 ldap_value_free(vals);
1700 vals=ldap_get_values(ldap,si_res,"pgpVersion");
1701 if(vals)
1703 fprintf(console,"Version:\t%s\n",vals[0]);
1704 ldap_value_free(vals);
1708 ldap_msgfree(si_res);
1711 ldap_value_free(context);
1714 ldap_msgfree(res);
1716 else
1718 /* We don't have an answer yet, which means the server might be
1719 a LDAP keyserver. */
1720 char **vals;
1721 LDAPMessage *si_res;
1723 attr[0]="pgpBaseKeySpaceDN";
1724 attr[1]="version";
1725 attr[2]="software";
1727 err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1728 "(objectClass=*)",attr,0,&si_res);
1729 if(err!=LDAP_SUCCESS)
1730 return err;
1732 /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1733 KEYSPACE,C=US", but it might not be in the future. */
1735 vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1736 if(vals)
1738 basekeyspacedn=strdup(vals[0]);
1739 ldap_value_free(vals);
1742 if(opt->verbose>1)
1744 vals=ldap_get_values(ldap,si_res,"software");
1745 if(vals)
1747 fprintf(console,"Server: \t%s\n",vals[0]);
1748 ldap_value_free(vals);
1752 vals=ldap_get_values(ldap,si_res,"version");
1753 if(vals)
1755 if(opt->verbose>1)
1756 fprintf(console,"Version:\t%s\n",vals[0]);
1758 /* If the version is high enough, use the new pgpKeyV2
1759 attribute. This design if iffy at best, but it matches how
1760 PGP does it. I figure the NAI folks assumed that there would
1761 never be a LDAP keyserver vendor with a different numbering
1762 scheme. */
1763 if(atoi(vals[0])>1)
1764 pgpkeystr="pgpKeyV2";
1766 ldap_value_free(vals);
1769 ldap_msgfree(si_res);
1772 return LDAP_SUCCESS;
1775 static void
1776 show_help (FILE *fp)
1778 fprintf (fp,"-h, --help\thelp\n");
1779 fprintf (fp,"-V\t\tmachine readable version\n");
1780 fprintf (fp,"--version\thuman readable version\n");
1781 fprintf (fp,"-o\t\toutput to this file\n");
1785 main(int argc,char *argv[])
1787 int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1788 char line[MAX_LINE],*binddn=NULL,*bindpw=NULL;
1789 int failed=0,use_ssl=0,use_tls=0,bound=0;
1790 struct keylist *keylist=NULL,*keyptr=NULL;
1792 console=stderr;
1794 /* Kludge to implement standard GNU options. */
1795 if (argc > 1 && !strcmp (argv[1], "--version"))
1797 fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1798 return 0;
1800 else if (argc > 1 && !strcmp (argv[1], "--help"))
1802 show_help (stdout);
1803 return 0;
1806 while((arg=getopt(argc,argv,"hVo:"))!=-1)
1807 switch(arg)
1809 default:
1810 case 'h':
1811 show_help (console);
1812 return KEYSERVER_OK;
1814 case 'V':
1815 fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1816 return KEYSERVER_OK;
1818 case 'o':
1819 output=fopen(optarg,"w");
1820 if(output==NULL)
1822 fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1823 optarg,strerror(errno));
1824 return KEYSERVER_INTERNAL_ERROR;
1827 break;
1830 if(argc>optind)
1832 input=fopen(argv[optind],"r");
1833 if(input==NULL)
1835 fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1836 argv[optind],strerror(errno));
1837 return KEYSERVER_INTERNAL_ERROR;
1841 if(input==NULL)
1842 input=stdin;
1844 if(output==NULL)
1845 output=stdout;
1847 opt=init_ks_options();
1848 if(!opt)
1849 return KEYSERVER_NO_MEMORY;
1851 /* Get the command and info block */
1853 while(fgets(line,MAX_LINE,input)!=NULL)
1855 char optionstr[MAX_OPTION+1];
1857 if(line[0]=='\n')
1858 break;
1860 err=parse_ks_options(line,opt);
1861 if(err>0)
1863 ret=err;
1864 goto fail;
1866 else if(err==0)
1867 continue;
1869 if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1871 int no=0;
1872 char *start=&optionstr[0];
1874 optionstr[MAX_OPTION]='\0';
1876 if(strncasecmp(optionstr,"no-",3)==0)
1878 no=1;
1879 start=&optionstr[3];
1882 if(strncasecmp(start,"tls",3)==0)
1884 if(no)
1885 use_tls=0;
1886 else if(start[3]=='=')
1888 if(strcasecmp(&start[4],"no")==0)
1889 use_tls=0;
1890 else if(strcasecmp(&start[4],"try")==0)
1891 use_tls=1;
1892 else if(strcasecmp(&start[4],"warn")==0)
1893 use_tls=2;
1894 else if(strcasecmp(&start[4],"require")==0)
1895 use_tls=3;
1896 else
1897 use_tls=1;
1899 else if(start[3]=='\0')
1900 use_tls=1;
1902 else if(strncasecmp(start,"basedn",6)==0)
1904 if(no)
1906 free(basekeyspacedn);
1907 basekeyspacedn=NULL;
1909 else if(start[6]=='=')
1911 free(basekeyspacedn);
1912 basekeyspacedn=strdup(&start[7]);
1913 if(!basekeyspacedn)
1915 fprintf(console,"gpgkeys: out of memory while creating "
1916 "base DN\n");
1917 ret=KEYSERVER_NO_MEMORY;
1918 goto fail;
1921 real_ldap=1;
1924 else if(strncasecmp(start,"binddn",6)==0)
1926 if(no)
1928 free(binddn);
1929 binddn=NULL;
1931 else if(start[6]=='=')
1933 free(binddn);
1934 binddn=strdup(&start[7]);
1935 if(!binddn)
1937 fprintf(console,"gpgkeys: out of memory while creating "
1938 "bind DN\n");
1939 ret=KEYSERVER_NO_MEMORY;
1940 goto fail;
1943 real_ldap=1;
1946 else if(strncasecmp(start,"bindpw",6)==0)
1948 if(no)
1950 free(bindpw);
1951 bindpw=NULL;
1953 else if(start[6]=='=')
1955 free(bindpw);
1956 bindpw=strdup(&start[7]);
1957 if(!bindpw)
1959 fprintf(console,"gpgkeys: out of memory while creating "
1960 "bind password\n");
1961 ret=KEYSERVER_NO_MEMORY;
1962 goto fail;
1965 real_ldap=1;
1969 continue;
1973 if(!opt->scheme)
1975 fprintf(console,"gpgkeys: no scheme supplied!\n");
1976 ret=KEYSERVER_SCHEME_NOT_FOUND;
1977 goto fail;
1980 if(strcasecmp(opt->scheme,"ldaps")==0)
1982 port=636;
1983 use_ssl=1;
1986 if(opt->port)
1987 port=atoi(opt->port);
1989 if(!opt->host)
1991 fprintf(console,"gpgkeys: no keyserver host provided\n");
1992 goto fail;
1995 if(opt->timeout && register_timeout()==-1)
1997 fprintf(console,"gpgkeys: unable to register timeout handler\n");
1998 return KEYSERVER_INTERNAL_ERROR;
2001 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
2003 if(opt->ca_cert_file)
2005 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
2006 if(err!=LDAP_SUCCESS)
2008 fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
2009 ldap_err2string(err));
2010 ret=KEYSERVER_INTERNAL_ERROR;
2011 goto fail;
2014 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
2016 /* SSL trumps TLS */
2017 if(use_ssl)
2018 use_tls=0;
2020 /* If it's a GET or a SEARCH, the next thing to come in is the
2021 keyids. If it's a SEND, then there are no keyids. */
2023 if(opt->action==KS_SEND)
2024 while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
2025 else if(opt->action==KS_GET
2026 || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
2028 for(;;)
2030 struct keylist *work;
2032 if(fgets(line,MAX_LINE,input)==NULL)
2033 break;
2034 else
2036 if(line[0]=='\n' || line[0]=='\0')
2037 break;
2039 work=malloc(sizeof(struct keylist));
2040 if(work==NULL)
2042 fprintf(console,"gpgkeys: out of memory while "
2043 "building key list\n");
2044 ret=KEYSERVER_NO_MEMORY;
2045 goto fail;
2048 strcpy(work->str,line);
2050 /* Trim the trailing \n */
2051 work->str[strlen(line)-1]='\0';
2053 work->next=NULL;
2055 /* Always attach at the end to keep the list in proper
2056 order for searching */
2057 if(keylist==NULL)
2058 keylist=work;
2059 else
2060 keyptr->next=work;
2062 keyptr=work;
2066 else
2068 fprintf(console,"gpgkeys: no keyserver command specified\n");
2069 goto fail;
2072 /* Send the response */
2074 fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
2075 fprintf(output,"PROGRAM %s\n\n",VERSION);
2077 if(opt->verbose>1)
2079 fprintf(console,"Host:\t\t%s\n",opt->host);
2080 if(port)
2081 fprintf(console,"Port:\t\t%d\n",port);
2082 fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
2085 if(opt->debug)
2087 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
2088 err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
2089 if(err!=LDAP_SUCCESS)
2090 fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
2091 ldap_err2string(err));
2092 else
2093 fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
2094 #else
2095 fprintf(console,"gpgkeys: not built with debugging support\n");
2096 #endif
2099 /* We have a timeout set for the setup stuff since it could time out
2100 as well. */
2101 set_timeout(opt->timeout);
2103 /* Note that this tries all A records on a given host (or at least,
2104 OpenLDAP does). */
2105 ldap=ldap_init(opt->host,port);
2106 if(ldap==NULL)
2108 fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
2109 strerror(errno));
2110 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2111 goto fail;
2114 if(use_ssl)
2116 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
2117 int ssl=LDAP_OPT_X_TLS_HARD;
2119 err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
2120 if(err!=LDAP_SUCCESS)
2122 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2123 ldap_err2string(err));
2124 fail_all(keylist,ldap_err_to_gpg_err(err));
2125 goto fail;
2128 if(!opt->flags.check_cert)
2129 ssl=LDAP_OPT_X_TLS_NEVER;
2131 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
2132 if(err!=LDAP_SUCCESS)
2134 fprintf(console,
2135 "gpgkeys: unable to set certificate validation: %s\n",
2136 ldap_err2string(err));
2137 fail_all(keylist,ldap_err_to_gpg_err(err));
2138 goto fail;
2140 #else
2141 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2142 "not built with LDAPS support");
2143 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2144 goto fail;
2145 #endif
2148 if(!basekeyspacedn)
2149 if((err=find_basekeyspacedn()) || !basekeyspacedn)
2151 fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
2152 err?ldap_err2string(err):"not found");
2153 fail_all(keylist,ldap_err_to_gpg_err(err));
2154 goto fail;
2157 /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
2158 3=force use. */
2159 if(use_tls)
2161 if(!real_ldap)
2163 if(use_tls>=2)
2164 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2165 "not supported by the NAI LDAP keyserver");
2166 if(use_tls==3)
2168 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2169 goto fail;
2172 else
2174 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
2175 int ver=LDAP_VERSION3;
2177 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2179 #ifdef LDAP_OPT_X_TLS
2180 if(err==LDAP_SUCCESS)
2182 if(opt->flags.check_cert)
2183 ver=LDAP_OPT_X_TLS_HARD;
2184 else
2185 ver=LDAP_OPT_X_TLS_NEVER;
2187 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
2189 #endif
2191 if(err==LDAP_SUCCESS)
2192 err=ldap_start_tls_s(ldap,NULL,NULL);
2194 if(err!=LDAP_SUCCESS)
2196 if(use_tls>=2 || opt->verbose>2)
2197 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2198 ldap_err2string(err));
2199 /* Are we forcing it? */
2200 if(use_tls==3)
2202 fail_all(keylist,ldap_err_to_gpg_err(err));
2203 goto fail;
2206 else if(opt->verbose>1)
2207 fprintf(console,"gpgkeys: TLS started successfully.\n");
2208 #else
2209 if(use_tls>=2)
2210 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2211 "not built with TLS support");
2212 if(use_tls==3)
2214 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2215 goto fail;
2217 #endif
2221 /* By default we don't bind as there is usually no need to. For
2222 cases where the server needs some authentication, the user can
2223 use binddn and bindpw for auth. */
2225 if(binddn)
2227 #ifdef HAVE_LDAP_SET_OPTION
2228 int ver=LDAP_VERSION3;
2230 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2231 if(err!=LDAP_SUCCESS)
2233 fprintf(console,"gpgkeys: unable to go to LDAP 3: %s\n",
2234 ldap_err2string(err));
2235 fail_all(keylist,ldap_err_to_gpg_err(err));
2236 goto fail;
2238 #endif
2240 if(opt->verbose>2)
2241 fprintf(console,"gpgkeys: LDAP bind to %s, pw %s\n",binddn,
2242 bindpw?">not shown<":">none<");
2243 err=ldap_simple_bind_s(ldap,binddn,bindpw);
2244 if(err!=LDAP_SUCCESS)
2246 fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
2247 ldap_err2string(err));
2248 fail_all(keylist,ldap_err_to_gpg_err(err));
2249 goto fail;
2251 else
2252 bound=1;
2255 if(opt->action==KS_GET)
2257 keyptr=keylist;
2259 while(keyptr!=NULL)
2261 set_timeout(opt->timeout);
2263 if(get_key(keyptr->str)!=KEYSERVER_OK)
2264 failed++;
2266 keyptr=keyptr->next;
2269 else if(opt->action==KS_GETNAME)
2271 keyptr=keylist;
2273 while(keyptr!=NULL)
2275 set_timeout(opt->timeout);
2277 if(get_name(keyptr->str)!=KEYSERVER_OK)
2278 failed++;
2280 keyptr=keyptr->next;
2283 else if(opt->action==KS_SEND)
2285 int eof_seen = 0;
2289 set_timeout(opt->timeout);
2291 if(real_ldap)
2293 if (send_key(&eof_seen) != KEYSERVER_OK)
2294 failed++;
2296 else
2298 if (send_key_keyserver(&eof_seen) != KEYSERVER_OK)
2299 failed++;
2302 while (!eof_seen);
2304 else if(opt->action==KS_SEARCH)
2306 char *searchkey=NULL;
2307 int len=0;
2309 set_timeout(opt->timeout);
2311 /* To search, we stick a * in between each key to search for.
2312 This means that if the user enters words, they'll get
2313 "enters*words". If the user "enters words", they'll get
2314 "enters words" */
2316 keyptr=keylist;
2317 while(keyptr!=NULL)
2319 len+=strlen(keyptr->str)+1;
2320 keyptr=keyptr->next;
2323 searchkey=malloc((len*3)+1);
2324 if(searchkey==NULL)
2326 ret=KEYSERVER_NO_MEMORY;
2327 fail_all(keylist,KEYSERVER_NO_MEMORY);
2328 goto fail;
2331 searchkey[0]='\0';
2333 keyptr=keylist;
2334 while(keyptr!=NULL)
2336 ldap_quote(searchkey,keyptr->str);
2337 strcat(searchkey,"*");
2338 keyptr=keyptr->next;
2341 /* Nail that last "*" */
2342 if(*searchkey)
2343 searchkey[strlen(searchkey)-1]='\0';
2345 if(search_key(searchkey)!=KEYSERVER_OK)
2346 failed++;
2348 free(searchkey);
2350 else
2351 assert (!"bad action");
2353 if(!failed)
2354 ret=KEYSERVER_OK;
2356 fail:
2358 while(keylist!=NULL)
2360 struct keylist *current=keylist;
2361 keylist=keylist->next;
2362 free(current);
2365 if(input!=stdin)
2366 fclose(input);
2368 if(output!=stdout)
2369 fclose(output);
2371 free_ks_options(opt);
2373 if(ldap!=NULL && bound)
2374 ldap_unbind_s(ldap);
2376 free(basekeyspacedn);
2378 return ret;