* gpg.texi (GPG Configuration Options): Make http_proxy option
[gnupg.git] / keyserver / gpgkeys_ldap.c
blobdf4279ff7e50628fcfec854943a8cb3eaa839370
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.
21 * In addition, as a special exception, the Free Software Foundation
22 * gives permission to link the code of the keyserver helper tools:
23 * gpgkeys_ldap, gpgkeys_curl and gpgkeys_hkp with the OpenSSL
24 * project's "OpenSSL" library (or with modified versions of it that
25 * use the same license as the "OpenSSL" library), and distribute the
26 * linked executables. You must obey the GNU General Public License
27 * in all respects for all of the code used other than "OpenSSL". If
28 * you modify this file, you may extend this exception to your version
29 * of the file, but you are not obligated to do so. If you do not
30 * wish to do so, delete this exception statement from your version.
33 #include <config.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <time.h>
37 #include <unistd.h>
38 #ifdef HAVE_GETOPT_H
39 #include <getopt.h>
40 #endif
41 #include <stdlib.h>
42 #include <errno.h>
43 #include <assert.h>
45 #ifdef _WIN32
46 #include <winsock2.h>
47 #include <winldap.h>
48 #else
49 #ifdef NEED_LBER_H
50 #include <lber.h>
51 #endif
52 /* For OpenLDAP, to enable the API that we're using. */
53 #define LDAP_DEPRECATED 1
54 #include <ldap.h>
55 #endif
57 #include "util.h"
58 #include "keyserver.h"
59 #include "ksutil.h"
61 #ifdef __riscos__
62 #include "util.h"
63 #endif
65 extern char *optarg;
66 extern int optind;
68 static int real_ldap=0;
69 static char *basekeyspacedn=NULL;
70 static char *pgpkeystr="pgpKey";
71 static FILE *input=NULL,*output=NULL,*console=NULL;
72 static LDAP *ldap=NULL;
73 static struct ks_options *opt;
75 #ifndef HAVE_TIMEGM
76 time_t timegm(struct tm *tm);
77 #endif
79 static int
80 ldap_err_to_gpg_err(int err)
82 int ret;
84 switch(err)
86 case LDAP_ALREADY_EXISTS:
87 ret=KEYSERVER_KEY_EXISTS;
88 break;
90 case LDAP_SERVER_DOWN:
91 ret=KEYSERVER_UNREACHABLE;
92 break;
94 default:
95 ret=KEYSERVER_GENERAL_ERROR;
96 break;
99 return ret;
102 static int
103 ldap_to_gpg_err(LDAP *ld)
105 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
107 int err;
109 if(ldap_get_option(ld,LDAP_OPT_ERROR_NUMBER,&err)==0)
110 return ldap_err_to_gpg_err(err);
111 else
112 return KEYSERVER_GENERAL_ERROR;
114 #elif defined(HAVE_LDAP_LD_ERRNO)
116 return ldap_err_to_gpg_err(ld->ld_errno);
118 #else
120 /* We should never get here since the LDAP library should always
121 have either ldap_get_option or ld_errno, but just in case... */
122 return KEYSERVER_GENERAL_ERROR;
124 #endif
127 static int
128 key_in_keylist(const char *key,struct keylist *list)
130 struct keylist *keyptr=list;
132 while(keyptr!=NULL)
134 if(strcasecmp(key,keyptr->str)==0)
135 return 1;
137 keyptr=keyptr->next;
140 return 0;
143 static int
144 add_key_to_keylist(const char *key,struct keylist **list)
146 struct keylist *keyptr=malloc(sizeof(struct keylist));
148 if(keyptr==NULL)
150 fprintf(console,"gpgkeys: out of memory when deduping "
151 "key list\n");
152 return KEYSERVER_NO_MEMORY;
155 strncpy(keyptr->str,key,MAX_LINE);
156 keyptr->str[MAX_LINE-1]='\0';
157 keyptr->next=*list;
158 *list=keyptr;
160 return 0;
163 static void
164 free_keylist(struct keylist *list)
166 while(list!=NULL)
168 struct keylist *keyptr=list;
170 list=keyptr->next;
171 free(keyptr);
175 static time_t
176 ldap2epochtime(const char *timestr)
178 struct tm pgptime;
179 time_t answer;
181 memset(&pgptime,0,sizeof(pgptime));
183 /* YYYYMMDDHHmmssZ */
185 sscanf(timestr,"%4d%2d%2d%2d%2d%2d",
186 &pgptime.tm_year,
187 &pgptime.tm_mon,
188 &pgptime.tm_mday,
189 &pgptime.tm_hour,
190 &pgptime.tm_min,
191 &pgptime.tm_sec);
193 pgptime.tm_year-=1900;
194 pgptime.tm_isdst=-1;
195 pgptime.tm_mon--;
197 /* mktime() takes the timezone into account, so we use timegm() */
199 answer=timegm(&pgptime);
201 return answer;
204 /* Caller must free */
205 static char *
206 epoch2ldaptime(time_t stamp)
208 struct tm *ldaptime;
209 char buf[16];
211 ldaptime=gmtime(&stamp);
213 ldaptime->tm_year+=1900;
214 ldaptime->tm_mon++;
216 /* YYYYMMDDHHmmssZ */
218 sprintf(buf,"%04d%02d%02d%02d%02d%02dZ",
219 ldaptime->tm_year,
220 ldaptime->tm_mon,
221 ldaptime->tm_mday,
222 ldaptime->tm_hour,
223 ldaptime->tm_min,
224 ldaptime->tm_sec);
226 return strdup(buf);
229 /* Append two onto the end of one. Two is not freed, but its pointers
230 are now part of one. Make sure you don't free them both! */
231 static int
232 join_two_modlists(LDAPMod ***one,LDAPMod **two)
234 int i,one_count=0,two_count=0;
235 LDAPMod **grow;
237 for(grow=*one;*grow;grow++)
238 one_count++;
240 for(grow=two;*grow;grow++)
241 two_count++;
243 grow=realloc(*one,sizeof(LDAPMod *)*(one_count+two_count+1));
244 if(!grow)
245 return 0;
247 for(i=0;i<two_count;i++)
248 grow[one_count+i]=two[i];
250 grow[one_count+i]=NULL;
252 *one=grow;
254 return 1;
257 /* Passing a NULL for value effectively deletes that attribute. This
258 doesn't mean "delete" in the sense of removing something from the
259 modlist, but "delete" in the LDAP sense of adding a modlist item
260 that specifies LDAP_MOD_REPLACE and a null attribute for the given
261 attribute. LDAP_MOD_DELETE doesn't work here as we don't know if
262 the attribute in question exists or not. */
264 static int
265 make_one_attr(LDAPMod ***modlist,char *attr,const char *value)
267 LDAPMod **m;
268 int nummods=0;
270 /* Search modlist for the attribute we're playing with. */
271 for(m=*modlist;*m;m++)
273 if(strcasecmp((*m)->mod_type,attr)==0)
275 char **ptr=(*m)->mod_values;
276 int numvalues=0;
278 /* We have this attribute already, so when the REPLACE
279 happens, the server attributes will be replaced
280 anyway. */
281 if(!value)
282 return 1;
284 if(ptr)
285 for(ptr=(*m)->mod_values;*ptr;ptr++)
287 /* Duplicate value */
288 if(strcmp(*ptr,value)==0)
289 return 1;
290 numvalues++;
293 ptr=realloc((*m)->mod_values,sizeof(char *)*(numvalues+2));
294 if(!ptr)
295 return 0;
297 (*m)->mod_values=ptr;
298 ptr[numvalues]=strdup(value);
299 if(!ptr[numvalues])
300 return 0;
302 ptr[numvalues+1]=NULL;
303 break;
306 nummods++;
309 /* We didn't find the attr, so make one and add it to the end */
310 if(!*m)
312 LDAPMod **grow;
314 grow=realloc(*modlist,sizeof(LDAPMod *)*(nummods+2));
315 if(!grow)
316 return 0;
318 *modlist=grow;
319 grow[nummods]=malloc(sizeof(LDAPMod));
320 if(!grow[nummods])
321 return 0;
322 grow[nummods]->mod_op=LDAP_MOD_REPLACE;
323 grow[nummods]->mod_type=attr;
324 if(value)
326 grow[nummods]->mod_values=malloc(sizeof(char *)*2);
327 if(!grow[nummods]->mod_values)
329 grow[nummods]=NULL;
330 return 0;
333 /* Is this the right thing? Can a UTF8-encoded user ID have
334 embedded nulls? */
335 grow[nummods]->mod_values[0]=strdup(value);
336 if(!grow[nummods]->mod_values[0])
338 free(grow[nummods]->mod_values);
339 grow[nummods]=NULL;
340 return 0;
343 grow[nummods]->mod_values[1]=NULL;
345 else
346 grow[nummods]->mod_values=NULL;
348 grow[nummods+1]=NULL;
351 return 1;
354 static void
355 build_attrs(LDAPMod ***modlist,char *line)
357 char *record;
358 int i;
360 /* Remove trailing whitespace */
361 for(i=strlen(line);i>0;i--)
362 if(ascii_isspace(line[i-1]))
363 line[i-1]='\0';
364 else
365 break;
367 if((record=strsep(&line,":"))==NULL)
368 return;
370 if(ks_strcasecmp("pub",record)==0)
372 char *tok;
373 int disabled=0,revoked=0;
375 /* The long keyid */
376 if((tok=strsep(&line,":"))==NULL)
377 return;
379 if(strlen(tok)==16)
381 make_one_attr(modlist,"pgpCertID",tok);
382 make_one_attr(modlist,"pgpKeyID",&tok[8]);
384 else
385 return;
387 /* The primary pubkey algo */
388 if((tok=strsep(&line,":"))==NULL)
389 return;
391 switch(atoi(tok))
393 case 1:
394 make_one_attr(modlist,"pgpKeyType","RSA");
395 break;
397 case 17:
398 make_one_attr(modlist,"pgpKeyType","DSS/DH");
399 break;
402 /* Size of primary key */
403 if((tok=strsep(&line,":"))==NULL)
404 return;
406 if(atoi(tok)>0)
408 char padded[6];
409 int val=atoi(tok);
411 /* We zero pad this on the left to make PGP happy. */
413 if(val<99999 && val>0)
415 sprintf(padded,"%05u",atoi(tok));
416 make_one_attr(modlist,"pgpKeySize",padded);
420 /* pk timestamp */
421 if((tok=strsep(&line,":"))==NULL)
422 return;
424 if(atoi(tok)>0)
426 char *stamp=epoch2ldaptime(atoi(tok));
427 if(stamp)
429 make_one_attr(modlist,"pgpKeyCreateTime",stamp);
430 free(stamp);
434 /* pk expire */
435 if((tok=strsep(&line,":"))==NULL)
436 return;
438 if(atoi(tok)>0)
440 char *stamp=epoch2ldaptime(atoi(tok));
441 if(stamp)
443 make_one_attr(modlist,"pgpKeyExpireTime",stamp);
444 free(stamp);
448 /* flags */
449 if((tok=strsep(&line,":"))==NULL)
450 return;
452 while(*tok)
453 switch(*tok++)
455 case 'r':
456 case 'R':
457 revoked=1;
458 break;
460 case 'd':
461 case 'D':
462 disabled=1;
463 break;
467 Note that we always create the pgpDisabled and pgpRevoked
468 attributes, regardless of whether the key is disabled/revoked
469 or not. This is because a very common search is like
470 "(&(pgpUserID=*isabella*)(pgpDisabled=0))"
473 make_one_attr(modlist,"pgpDisabled",disabled?"1":"0");
474 make_one_attr(modlist,"pgpRevoked",revoked?"1":"0");
476 else if(ks_strcasecmp("sub",record)==0)
478 char *tok;
480 /* The long keyid */
481 if((tok=strsep(&line,":"))==NULL)
482 return;
484 if(strlen(tok)==16)
485 make_one_attr(modlist,"pgpSubKeyID",tok);
486 else
487 return;
489 /* The subkey algo */
490 if((tok=strsep(&line,":"))==NULL)
491 return;
493 /* Size of subkey */
494 if((tok=strsep(&line,":"))==NULL)
495 return;
497 if(atoi(tok)>0)
499 char padded[6];
500 int val=atoi(tok);
502 /* We zero pad this on the left to make PGP happy. */
504 if(val<99999 && val>0)
506 sprintf(padded,"%05u",atoi(tok));
507 make_one_attr(modlist,"pgpKeySize",padded);
511 /* Ignore the rest of the items for subkeys since the LDAP
512 schema doesn't store them. */
514 else if(ks_strcasecmp("uid",record)==0)
516 char *userid,*tok;
518 /* The user ID string */
519 if((tok=strsep(&line,":"))==NULL)
520 return;
522 if(strlen(tok)==0)
523 return;
525 userid=tok;
527 /* By definition, de-%-encoding is always smaller than the
528 original string so we can decode in place. */
530 i=0;
532 while(*tok)
533 if(tok[0]=='%' && tok[1] && tok[2])
535 if((userid[i]=ks_hextobyte(&tok[1]))==-1)
536 userid[i]='?';
538 i++;
539 tok+=3;
541 else
542 userid[i++]=*tok++;
544 userid[i]='\0';
546 /* We don't care about the other info provided in the uid: line
547 since the LDAP schema doesn't need it. */
549 make_one_attr(modlist,"pgpUserID",userid);
551 else if(ks_strcasecmp("sig",record)==0)
553 char *tok;
555 if((tok=strsep(&line,":"))==NULL)
556 return;
558 if(strlen(tok)==16)
559 make_one_attr(modlist,"pgpSignerID",tok);
563 static void
564 free_mod_values(LDAPMod *mod)
566 char **ptr;
568 if(!mod->mod_values)
569 return;
571 for(ptr=mod->mod_values;*ptr;ptr++)
572 free(*ptr);
574 free(mod->mod_values);
577 static int
578 send_key(int *eof)
580 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
581 char *dn=NULL,line[MAX_LINE],*key=NULL;
582 char keyid[17],state[6];
583 LDAPMod **modlist,**addlist,**ml;
585 modlist=malloc(sizeof(LDAPMod *));
586 if(!modlist)
588 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
589 ret=KEYSERVER_NO_MEMORY;
590 goto fail;
593 *modlist=NULL;
595 addlist=malloc(sizeof(LDAPMod *));
596 if(!addlist)
598 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
599 ret=KEYSERVER_NO_MEMORY;
600 goto fail;
603 *addlist=NULL;
605 /* Start by nulling out all attributes. We try and do a modify
606 operation first, so this ensures that we don't leave old
607 attributes lying around. */
608 make_one_attr(&modlist,"pgpDisabled",NULL);
609 make_one_attr(&modlist,"pgpKeyID",NULL);
610 make_one_attr(&modlist,"pgpKeyType",NULL);
611 make_one_attr(&modlist,"pgpUserID",NULL);
612 make_one_attr(&modlist,"pgpKeyCreateTime",NULL);
613 make_one_attr(&modlist,"pgpSignerID",NULL);
614 make_one_attr(&modlist,"pgpRevoked",NULL);
615 make_one_attr(&modlist,"pgpSubKeyID",NULL);
616 make_one_attr(&modlist,"pgpKeySize",NULL);
617 make_one_attr(&modlist,"pgpKeyExpireTime",NULL);
618 make_one_attr(&modlist,"pgpCertID",NULL);
620 /* Assemble the INFO stuff into LDAP attributes */
622 while(fgets(line,MAX_LINE,input)!=NULL)
623 if(sscanf(line,"INFO%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
624 && strcmp(state,"BEGIN")==0)
626 begin=1;
627 break;
630 if(!begin)
632 /* i.e. eof before the INFO BEGIN was found. This isn't an
633 error. */
634 *eof=1;
635 ret=KEYSERVER_OK;
636 goto fail;
639 if(strlen(keyid)!=16)
641 *eof=1;
642 ret=KEYSERVER_KEY_INCOMPLETE;
643 goto fail;
646 dn=malloc(strlen("pgpCertID=")+16+1+strlen(basekeyspacedn)+1);
647 if(dn==NULL)
649 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
650 ret=KEYSERVER_NO_MEMORY;
651 goto fail;
654 sprintf(dn,"pgpCertID=%s,%s",keyid,basekeyspacedn);
656 key=malloc(1);
657 if(!key)
659 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
660 ret=KEYSERVER_NO_MEMORY;
661 goto fail;
664 key[0]='\0';
666 /* Now parse each line until we see the END */
668 while(fgets(line,MAX_LINE,input)!=NULL)
669 if(sscanf(line,"INFO%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
670 && strcmp(state,"END")==0)
672 end=1;
673 break;
675 else
676 build_attrs(&addlist,line);
678 if(!end)
680 fprintf(console,"gpgkeys: no INFO %s END found\n",keyid);
681 *eof=1;
682 ret=KEYSERVER_KEY_INCOMPLETE;
683 goto fail;
686 begin=end=0;
688 /* Read and throw away stdin until we see the BEGIN */
690 while(fgets(line,MAX_LINE,input)!=NULL)
691 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
692 && strcmp(state,"BEGIN")==0)
694 begin=1;
695 break;
698 if(!begin)
700 /* i.e. eof before the KEY BEGIN was found. This isn't an
701 error. */
702 *eof=1;
703 ret=KEYSERVER_OK;
704 goto fail;
707 /* Now slurp up everything until we see the END */
709 while(fgets(line,MAX_LINE,input)!=NULL)
710 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
711 && strcmp(state,"END")==0)
713 end=1;
714 break;
716 else
718 char *tempkey;
719 keysize+=strlen(line);
720 tempkey=realloc(key,keysize);
721 if(tempkey==NULL)
723 fprintf(console,"gpgkeys: unable to reallocate for key\n");
724 ret=KEYSERVER_NO_MEMORY;
725 goto fail;
727 else
728 key=tempkey;
730 strcat(key,line);
733 if(!end)
735 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
736 *eof=1;
737 ret=KEYSERVER_KEY_INCOMPLETE;
738 goto fail;
741 make_one_attr(&addlist,"objectClass","pgpKeyInfo");
742 make_one_attr(&addlist,"pgpKey",key);
744 /* Now append addlist onto modlist */
745 if(!join_two_modlists(&modlist,addlist))
747 fprintf(console,"gpgkeys: unable to merge LDAP modification lists\n");
748 ret=KEYSERVER_NO_MEMORY;
749 goto fail;
752 /* Going on the assumption that modify operations are more frequent
753 than adds, we try a modify first. If it's not there, we just
754 turn around and send an add command for the same key. Otherwise,
755 the modify brings the server copy into compliance with our copy.
756 Note that unlike the LDAP keyserver (and really, any other
757 keyserver) this does NOT merge signatures, but replaces the whole
758 key. This should make some people very happy. */
760 err=ldap_modify_s(ldap,dn,modlist);
761 if(err==LDAP_NO_SUCH_OBJECT)
762 err=ldap_add_s(ldap,dn,addlist);
764 if(err!=LDAP_SUCCESS)
766 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
767 keyid,ldap_err2string(err));
768 ret=ldap_err_to_gpg_err(err);
769 goto fail;
772 ret=KEYSERVER_OK;
774 fail:
775 /* Unwind and free the whole modlist structure */
776 for(ml=modlist;*ml;ml++)
778 free_mod_values(*ml);
779 free(*ml);
782 free(modlist);
783 free(addlist);
784 free(dn);
786 if(ret!=0 && begin)
787 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
789 return ret;
792 static int
793 send_key_keyserver(int *eof)
795 int err,begin=0,end=0,keysize=1,ret=KEYSERVER_INTERNAL_ERROR;
796 char *dn=NULL,line[MAX_LINE],*key[2]={NULL,NULL};
797 char keyid[17],state[6];
798 LDAPMod mod, *attrs[2];
800 memset(&mod,0,sizeof(mod));
801 mod.mod_op=LDAP_MOD_ADD;
802 mod.mod_type=pgpkeystr;
803 mod.mod_values=key;
804 attrs[0]=&mod;
805 attrs[1]=NULL;
807 dn=malloc(strlen("pgpCertid=virtual,")+strlen(basekeyspacedn)+1);
808 if(dn==NULL)
810 fprintf(console,"gpgkeys: can't allocate memory for keyserver record\n");
811 ret=KEYSERVER_NO_MEMORY;
812 goto fail;
815 strcpy(dn,"pgpCertid=virtual,");
816 strcat(dn,basekeyspacedn);
818 key[0]=malloc(1);
819 if(key[0]==NULL)
821 fprintf(console,"gpgkeys: unable to allocate memory for key\n");
822 ret=KEYSERVER_NO_MEMORY;
823 goto fail;
826 key[0][0]='\0';
828 /* Read and throw away stdin until we see the BEGIN */
830 while(fgets(line,MAX_LINE,input)!=NULL)
831 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%5s\n",keyid,state)==2
832 && strcmp(state,"BEGIN")==0)
834 begin=1;
835 break;
838 if(!begin)
840 /* i.e. eof before the KEY BEGIN was found. This isn't an
841 error. */
842 *eof=1;
843 ret=KEYSERVER_OK;
844 goto fail;
847 /* Now slurp up everything until we see the END */
849 while(fgets(line,MAX_LINE,input)!=NULL)
850 if(sscanf(line,"KEY%*[ ]%16s%*[ ]%3s\n",keyid,state)==2
851 && strcmp(state,"END")==0)
853 end=1;
854 break;
856 else
858 keysize+=strlen(line);
859 key[0]=realloc(key[0],keysize);
860 if(key[0]==NULL)
862 fprintf(console,"gpgkeys: unable to reallocate for key\n");
863 ret=KEYSERVER_NO_MEMORY;
864 goto fail;
867 strcat(key[0],line);
870 if(!end)
872 fprintf(console,"gpgkeys: no KEY %s END found\n",keyid);
873 *eof=1;
874 ret=KEYSERVER_KEY_INCOMPLETE;
875 goto fail;
878 err=ldap_add_s(ldap,dn,attrs);
879 if(err!=LDAP_SUCCESS)
881 fprintf(console,"gpgkeys: error adding key %s to keyserver: %s\n",
882 keyid,ldap_err2string(err));
883 ret=ldap_err_to_gpg_err(err);
884 goto fail;
887 ret=KEYSERVER_OK;
889 fail:
891 free(key[0]);
892 free(dn);
894 if(ret!=0 && begin)
895 fprintf(output,"KEY %s FAILED %d\n",keyid,ret);
897 /* Not a fatal error */
898 if(ret==KEYSERVER_KEY_EXISTS)
899 ret=KEYSERVER_OK;
901 return ret;
904 static void
905 build_info(const char *certid,LDAPMessage *each)
907 char **vals;
909 fprintf(output,"INFO %s BEGIN\n",certid);
911 fprintf(output,"pub:%s:",certid);
913 vals=ldap_get_values(ldap,each,"pgpkeytype");
914 if(vals!=NULL)
916 if(strcmp(vals[0],"RSA")==0)
917 fprintf(output,"1");
918 else if(strcmp(vals[0],"DSS/DH")==0)
919 fprintf(output,"17");
920 ldap_value_free(vals);
923 fprintf(output,":");
925 vals=ldap_get_values(ldap,each,"pgpkeysize");
926 if(vals!=NULL)
928 if(atoi(vals[0])>0)
929 fprintf(output,"%d",atoi(vals[0]));
930 ldap_value_free(vals);
933 fprintf(output,":");
935 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
936 if(vals!=NULL)
938 if(strlen(vals[0])==15)
939 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
940 ldap_value_free(vals);
943 fprintf(output,":");
945 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
946 if(vals!=NULL)
948 if(strlen(vals[0])==15)
949 fprintf(output,"%u",(unsigned int)ldap2epochtime(vals[0]));
950 ldap_value_free(vals);
953 fprintf(output,":");
955 vals=ldap_get_values(ldap,each,"pgprevoked");
956 if(vals!=NULL)
958 if(atoi(vals[0])==1)
959 fprintf(output,"r");
960 ldap_value_free(vals);
963 fprintf(output,"\n");
965 vals=ldap_get_values(ldap,each,"pgpuserid");
966 if(vals!=NULL)
968 int i;
970 for(i=0;vals[i];i++)
971 fprintf(output,"uid:%s\n",vals[i]);
972 ldap_value_free(vals);
975 fprintf(output,"INFO %s END\n",certid);
978 /* Note that key-not-found is not a fatal error */
979 static int
980 get_key(char *getkey)
982 LDAPMessage *res,*each;
983 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
984 struct keylist *dupelist=NULL;
985 char search[62];
986 /* This ordering is significant - specifically, "pgpcertid" needs to
987 be the second item in the list, since everything after it may be
988 discarded if the user isn't in verbose mode. */
989 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
990 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
991 "pgpkeysize","pgpkeytype",NULL};
992 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
993 array initializers. */
995 /* Build the search string */
997 /* GPG can send us a v4 fingerprint, a v3 or v4 long key id, or a v3
998 or v4 short key id */
1000 if(strncmp(getkey,"0x",2)==0)
1001 getkey+=2;
1003 if(strlen(getkey)==32)
1005 fprintf(console,
1006 "gpgkeys: LDAP keyservers do not support v3 fingerprints\n");
1007 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1008 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_NOT_SUPPORTED);
1009 return KEYSERVER_NOT_SUPPORTED;
1012 if(strlen(getkey)>16)
1014 char *offset=&getkey[strlen(getkey)-16];
1016 /* fingerprint. Take the last 16 characters and treat it like a
1017 long key id */
1019 if(opt->flags.include_subkeys)
1020 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1021 offset,offset);
1022 else
1023 sprintf(search,"(pgpcertid=%.16s)",offset);
1025 else if(strlen(getkey)>8)
1027 /* long key id */
1029 if(opt->flags.include_subkeys)
1030 sprintf(search,"(|(pgpcertid=%.16s)(pgpsubkeyid=%.16s))",
1031 getkey,getkey);
1032 else
1033 sprintf(search,"(pgpcertid=%.16s)",getkey);
1035 else
1037 /* short key id */
1039 sprintf(search,"(pgpkeyid=%.8s)",getkey);
1042 if(opt->verbose>2)
1043 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1045 if(!opt->verbose)
1046 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1048 err=ldap_search_s(ldap,basekeyspacedn,
1049 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1050 if(err!=0)
1052 int errtag=ldap_err_to_gpg_err(err);
1054 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1055 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1056 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1057 return errtag;
1060 count=ldap_count_entries(ldap,res);
1061 if(count<1)
1063 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1064 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1065 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1067 else
1069 /* There may be more than one unique result for a given keyID,
1070 so we should fetch them all (test this by fetching short key
1071 id 0xDEADBEEF). */
1073 each=ldap_first_entry(ldap,res);
1074 while(each!=NULL)
1076 char **vals,**certid;
1078 /* Use the long keyid to remove duplicates. The LDAP server
1079 returns the same keyid more than once if there are
1080 multiple user IDs on the key. Note that this does NOT
1081 mean that a keyid that exists multiple times on the
1082 keyserver will not be fetched. It means that each KEY,
1083 no matter how many user IDs share its keyid, will be
1084 fetched only once. If a keyid that belongs to more than
1085 one key is fetched, the server quite properly responds
1086 with all matching keys. -ds */
1088 certid=ldap_get_values(ldap,each,"pgpcertid");
1089 if(certid!=NULL)
1091 if(!key_in_keylist(certid[0],dupelist))
1093 /* it's not a duplicate, so add it */
1095 int rc=add_key_to_keylist(certid[0],&dupelist);
1096 if(rc)
1098 ret=rc;
1099 goto fail;
1102 build_info(certid[0],each);
1104 fprintf(output,"KEY 0x%s BEGIN\n",getkey);
1106 vals=ldap_get_values(ldap,each,pgpkeystr);
1107 if(vals==NULL)
1109 int errtag=ldap_to_gpg_err(ldap);
1111 fprintf(console,"gpgkeys: unable to retrieve key %s "
1112 "from keyserver\n",getkey);
1113 fprintf(output,"KEY 0x%s FAILED %d\n",getkey,errtag);
1115 else
1117 print_nocr(output,vals[0]);
1118 fprintf(output,"\nKEY 0x%s END\n",getkey);
1120 ldap_value_free(vals);
1124 ldap_value_free(certid);
1127 each=ldap_next_entry(ldap,each);
1131 ret=KEYSERVER_OK;
1133 fail:
1134 ldap_msgfree(res);
1135 free_keylist(dupelist);
1137 return ret;
1140 #define LDAP_ESCAPE_CHARS "*()\\"
1142 /* Append string to buffer in a LDAP-quoted way */
1143 static void
1144 ldap_quote(char *buffer,const char *string)
1146 /* Find the end of buffer */
1147 buffer+=strlen(buffer);
1149 for(;*string;string++)
1151 if(strchr(LDAP_ESCAPE_CHARS,*string))
1153 sprintf(buffer,"\\%02X",*string);
1154 buffer+=3;
1156 else
1157 *buffer++=*string;
1160 *buffer='\0';
1163 /* Note that key-not-found is not a fatal error */
1164 static int
1165 get_name(char *getkey)
1167 LDAPMessage *res,*each;
1168 int ret=KEYSERVER_INTERNAL_ERROR,err,count;
1169 /* The maximum size of the search, including the optional stuff and
1170 the trailing \0 */
1171 char search[2+12+(MAX_LINE*3)+2+15+14+1+1+20];
1172 /* This ordering is significant - specifically, "pgpcertid" needs to
1173 be the second item in the list, since everything after it may be
1174 discarded if the user isn't in verbose mode. */
1175 char *attrs[]={"replaceme","pgpcertid","pgpuserid","pgpkeyid","pgprevoked",
1176 "pgpdisabled","pgpkeycreatetime","modifytimestamp",
1177 "pgpkeysize","pgpkeytype",NULL};
1178 attrs[0]=pgpkeystr; /* Some compilers don't like using variables as
1179 array initializers. */
1181 /* Build the search string */
1183 search[0]='\0';
1185 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1186 strcat(search,"(&");
1188 strcat(search,"(pgpUserID=*");
1189 ldap_quote(search,getkey);
1190 strcat(search,"*)");
1192 if(!opt->flags.include_disabled)
1193 strcat(search,"(pgpDisabled=0)");
1195 if(!opt->flags.include_revoked)
1196 strcat(search,"(pgpRevoked=0)");
1198 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1199 strcat(search,")");
1201 if(opt->verbose>2)
1202 fprintf(console,"gpgkeys: LDAP fetch for: %s\n",search);
1204 if(!opt->verbose)
1205 attrs[2]=NULL; /* keep only pgpkey(v2) and pgpcertid */
1207 err=ldap_search_s(ldap,basekeyspacedn,
1208 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1209 if(err!=0)
1211 int errtag=ldap_err_to_gpg_err(err);
1213 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1214 fprintf(output,"NAME %s BEGIN\n",getkey);
1215 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1216 return errtag;
1219 count=ldap_count_entries(ldap,res);
1220 if(count<1)
1222 fprintf(console,"gpgkeys: key %s not found on keyserver\n",getkey);
1223 fprintf(output,"NAME %s BEGIN\n",getkey);
1224 fprintf(output,"NAME %s FAILED %d\n",getkey,KEYSERVER_KEY_NOT_FOUND);
1226 else
1228 /* There may be more than one result, but we return them all. */
1230 each=ldap_first_entry(ldap,res);
1231 while(each!=NULL)
1233 char **vals,**certid;
1235 certid=ldap_get_values(ldap,each,"pgpcertid");
1236 if(certid!=NULL)
1238 build_info(certid[0],each);
1240 fprintf(output,"NAME %s BEGIN\n",getkey);
1242 vals=ldap_get_values(ldap,each,pgpkeystr);
1243 if(vals==NULL)
1245 int errtag=ldap_to_gpg_err(ldap);
1247 fprintf(console,"gpgkeys: unable to retrieve key %s "
1248 "from keyserver\n",getkey);
1249 fprintf(output,"NAME %s FAILED %d\n",getkey,errtag);
1251 else
1253 print_nocr(output,vals[0]);
1254 fprintf(output,"\nNAME %s END\n",getkey);
1256 ldap_value_free(vals);
1259 ldap_value_free(certid);
1262 each=ldap_next_entry(ldap,each);
1266 ret=KEYSERVER_OK;
1268 ldap_msgfree(res);
1270 return ret;
1273 static void
1274 printquoted(FILE *stream,char *string,char delim)
1276 while(*string)
1278 if(*string==delim || *string=='%')
1279 fprintf(stream,"%%%02x",*string);
1280 else
1281 fputc(*string,stream);
1283 string++;
1287 /* Returns 0 on success and -1 on error. Note that key-not-found is
1288 not an error! */
1289 static int
1290 search_key(const char *searchkey)
1292 char **vals;
1293 LDAPMessage *res,*each;
1294 int err,count=0;
1295 struct keylist *dupelist=NULL;
1296 /* The maximum size of the search, including the optional stuff and
1297 the trailing \0 */
1298 char search[2+1+9+1+3+(MAX_LINE*3)+3+1+15+14+1+1+20];
1299 char *attrs[]={"pgpcertid","pgpuserid","pgprevoked","pgpdisabled",
1300 "pgpkeycreatetime","pgpkeyexpiretime","modifytimestamp",
1301 "pgpkeysize","pgpkeytype",NULL};
1302 enum ks_search_type search_type;
1304 fprintf(output,"SEARCH %s BEGIN\n",searchkey);
1306 search_type=classify_ks_search(&searchkey);
1308 if(opt->debug)
1309 fprintf(console,"search type is %d, and key is \"%s\"\n",
1310 search_type,searchkey);
1312 /* Build the search string */
1314 search[0]='\0';
1316 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1317 strcat(search,"(&");
1319 strcat(search,"(");
1321 switch(search_type)
1323 case KS_SEARCH_KEYID_SHORT:
1324 strcat(search,"pgpKeyID");
1325 break;
1327 case KS_SEARCH_KEYID_LONG:
1328 strcat(search,"pgpCertID");
1329 break;
1331 default:
1332 strcat(search,"pgpUserID");
1333 break;
1336 strcat(search,"=");
1338 switch(search_type)
1340 case KS_SEARCH_SUBSTR:
1341 strcat(search,"*");
1342 break;
1344 case KS_SEARCH_MAIL:
1345 strcat(search,"*<");
1346 break;
1348 case KS_SEARCH_MAILSUB:
1349 strcat(search,"*<*");
1350 break;
1352 case KS_SEARCH_EXACT:
1353 case KS_SEARCH_KEYID_LONG:
1354 case KS_SEARCH_KEYID_SHORT:
1355 break;
1358 ldap_quote(search,searchkey);
1360 switch(search_type)
1362 case KS_SEARCH_SUBSTR:
1363 strcat(search,"*");
1364 break;
1366 case KS_SEARCH_MAIL:
1367 strcat(search,">*");
1368 break;
1370 case KS_SEARCH_MAILSUB:
1371 strcat(search,"*>*");
1372 break;
1374 case KS_SEARCH_EXACT:
1375 case KS_SEARCH_KEYID_LONG:
1376 case KS_SEARCH_KEYID_SHORT:
1377 break;
1380 strcat(search,")");
1382 if(!opt->flags.include_disabled)
1383 strcat(search,"(pgpDisabled=0)");
1385 if(!opt->flags.include_revoked)
1386 strcat(search,"(pgpRevoked=0)");
1388 if(!opt->flags.include_disabled || !opt->flags.include_revoked)
1389 strcat(search,")");
1391 if(opt->verbose>2)
1392 fprintf(console,"gpgkeys: LDAP search for: %s\n",search);
1394 err=ldap_search_s(ldap,basekeyspacedn,
1395 LDAP_SCOPE_SUBTREE,search,attrs,0,&res);
1396 if(err!=LDAP_SUCCESS && err!=LDAP_SIZELIMIT_EXCEEDED)
1398 int errtag=ldap_err_to_gpg_err(err);
1400 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,errtag);
1401 fprintf(console,"gpgkeys: LDAP search error: %s\n",ldap_err2string(err));
1402 return errtag;
1405 /* The LDAP server doesn't return a real count of unique keys, so we
1406 can't use ldap_count_entries here. */
1407 each=ldap_first_entry(ldap,res);
1408 while(each!=NULL)
1410 char **certid=ldap_get_values(ldap,each,"pgpcertid");
1412 if(certid!=NULL)
1414 if(!key_in_keylist(certid[0],dupelist))
1416 int rc=add_key_to_keylist(certid[0],&dupelist);
1417 if(rc!=0)
1419 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1420 free_keylist(dupelist);
1421 return rc;
1424 count++;
1428 each=ldap_next_entry(ldap,each);
1431 if(err==LDAP_SIZELIMIT_EXCEEDED)
1433 if(count==1)
1434 fprintf(console,"gpgkeys: search results exceeded server limit."
1435 " First %d result shown.\n",count);
1436 else
1437 fprintf(console,"gpgkeys: search results exceeded server limit."
1438 " First %d results shown.\n",count);
1441 free_keylist(dupelist);
1442 dupelist=NULL;
1444 if(count<1)
1445 fprintf(output,"info:1:0\n");
1446 else
1448 fprintf(output,"info:1:%d\n",count);
1450 each=ldap_first_entry(ldap,res);
1451 while(each!=NULL)
1453 char **certid;
1455 certid=ldap_get_values(ldap,each,"pgpcertid");
1456 if(certid!=NULL)
1458 LDAPMessage *uids;
1460 /* Have we seen this certid before? */
1461 if(!key_in_keylist(certid[0],dupelist))
1463 int rc=add_key_to_keylist(certid[0],&dupelist);
1464 if(rc)
1466 fprintf(output,"SEARCH %s FAILED %d\n",searchkey,rc);
1467 free_keylist(dupelist);
1468 ldap_value_free(certid);
1469 ldap_msgfree(res);
1470 return rc;
1473 fprintf(output,"pub:%s:",certid[0]);
1475 vals=ldap_get_values(ldap,each,"pgpkeytype");
1476 if(vals!=NULL)
1478 /* The LDAP server doesn't exactly handle this
1479 well. */
1480 if(strcasecmp(vals[0],"RSA")==0)
1481 fprintf(output,"1");
1482 else if(strcasecmp(vals[0],"DSS/DH")==0)
1483 fprintf(output,"17");
1484 ldap_value_free(vals);
1487 fputc(':',output);
1489 vals=ldap_get_values(ldap,each,"pgpkeysize");
1490 if(vals!=NULL)
1492 /* Not sure why, but some keys are listed with a
1493 key size of 0. Treat that like an
1494 unknown. */
1495 if(atoi(vals[0])>0)
1496 fprintf(output,"%d",atoi(vals[0]));
1497 ldap_value_free(vals);
1500 fputc(':',output);
1502 /* YYYYMMDDHHmmssZ */
1504 vals=ldap_get_values(ldap,each,"pgpkeycreatetime");
1505 if(vals!=NULL && strlen(vals[0])==15)
1507 fprintf(output,"%u",
1508 (unsigned int)ldap2epochtime(vals[0]));
1509 ldap_value_free(vals);
1512 fputc(':',output);
1514 vals=ldap_get_values(ldap,each,"pgpkeyexpiretime");
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,"pgprevoked");
1525 if(vals!=NULL)
1527 if(atoi(vals[0])==1)
1528 fprintf(output,"r");
1529 ldap_value_free(vals);
1532 vals=ldap_get_values(ldap,each,"pgpdisabled");
1533 if(vals!=NULL)
1535 if(atoi(vals[0])==1)
1536 fprintf(output,"d");
1537 ldap_value_free(vals);
1540 #if 0
1541 /* This is not yet specified in the keyserver
1542 protocol, but may be someday. */
1543 fputc(':',output);
1545 vals=ldap_get_values(ldap,each,"modifytimestamp");
1546 if(vals!=NULL && strlen(vals[0])==15)
1548 fprintf(output,"%u",
1549 (unsigned int)ldap2epochtime(vals[0]));
1550 ldap_value_free(vals);
1552 #endif
1554 fprintf(output,"\n");
1556 /* Now print all the uids that have this certid */
1557 uids=ldap_first_entry(ldap,res);
1558 while(uids!=NULL)
1560 vals=ldap_get_values(ldap,uids,"pgpcertid");
1561 if(vals!=NULL)
1563 if(strcasecmp(certid[0],vals[0])==0)
1565 char **uidvals;
1567 fprintf(output,"uid:");
1569 uidvals=ldap_get_values(ldap,uids,"pgpuserid");
1570 if(uidvals!=NULL)
1572 /* Need to escape any colons */
1573 printquoted(output,uidvals[0],':');
1574 ldap_value_free(uidvals);
1577 fprintf(output,"\n");
1580 ldap_value_free(vals);
1583 uids=ldap_next_entry(ldap,uids);
1587 ldap_value_free(certid);
1590 each=ldap_next_entry(ldap,each);
1594 ldap_msgfree(res);
1595 free_keylist(dupelist);
1597 fprintf(output,"SEARCH %s END\n",searchkey);
1599 return KEYSERVER_OK;
1602 static void
1603 fail_all(struct keylist *keylist,int err)
1605 if(!keylist)
1606 return;
1608 if(opt->action==KS_SEARCH)
1610 fprintf(output,"SEARCH ");
1611 while(keylist)
1613 fprintf(output,"%s ",keylist->str);
1614 keylist=keylist->next;
1616 fprintf(output,"FAILED %d\n",err);
1618 else
1619 while(keylist)
1621 fprintf(output,"KEY %s FAILED %d\n",keylist->str,err);
1622 keylist=keylist->next;
1626 static int
1627 find_basekeyspacedn(void)
1629 int err,i;
1630 char *attr[]={"namingContexts",NULL,NULL,NULL};
1631 LDAPMessage *res;
1632 char **context;
1634 /* Look for namingContexts */
1635 err=ldap_search_s(ldap,"",LDAP_SCOPE_BASE,"(objectClass=*)",attr,0,&res);
1636 if(err==LDAP_SUCCESS)
1638 context=ldap_get_values(ldap,res,"namingContexts");
1639 if(context)
1641 attr[0]="pgpBaseKeySpaceDN";
1642 attr[1]="pgpVersion";
1643 attr[2]="pgpSoftware";
1645 real_ldap=1;
1647 /* We found some, so try each namingContext as the search base
1648 and look for pgpBaseKeySpaceDN. Because we found this, we
1649 know we're talking to a regular-ish LDAP server and not a
1650 LDAP keyserver. */
1652 for(i=0;context[i] && !basekeyspacedn;i++)
1654 char **vals;
1655 LDAPMessage *si_res;
1656 char *object;
1658 object=malloc(17+strlen(context[i])+1);
1659 if(!object)
1660 return -1;
1662 strcpy(object,"cn=pgpServerInfo,");
1663 strcat(object,context[i]);
1665 err=ldap_search_s(ldap,object,LDAP_SCOPE_BASE,
1666 "(objectClass=*)",attr,0,&si_res);
1667 free(object);
1669 if(err==LDAP_NO_SUCH_OBJECT)
1670 continue;
1671 else if(err!=LDAP_SUCCESS)
1672 return err;
1674 vals=ldap_get_values(ldap,si_res,"pgpBaseKeySpaceDN");
1675 if(vals)
1677 basekeyspacedn=strdup(vals[0]);
1678 ldap_value_free(vals);
1681 if(opt->verbose>1)
1683 vals=ldap_get_values(ldap,si_res,"pgpSoftware");
1684 if(vals)
1686 fprintf(console,"Server: \t%s\n",vals[0]);
1687 ldap_value_free(vals);
1690 vals=ldap_get_values(ldap,si_res,"pgpVersion");
1691 if(vals)
1693 fprintf(console,"Version:\t%s\n",vals[0]);
1694 ldap_value_free(vals);
1698 ldap_msgfree(si_res);
1701 ldap_value_free(context);
1704 ldap_msgfree(res);
1706 else
1708 /* We don't have an answer yet, which means the server might be
1709 a LDAP keyserver. */
1710 char **vals;
1711 LDAPMessage *si_res;
1713 attr[0]="pgpBaseKeySpaceDN";
1714 attr[1]="version";
1715 attr[2]="software";
1717 err=ldap_search_s(ldap,"cn=pgpServerInfo",LDAP_SCOPE_BASE,
1718 "(objectClass=*)",attr,0,&si_res);
1719 if(err!=LDAP_SUCCESS)
1720 return err;
1722 /* For the LDAP keyserver, this is always "OU=ACTIVE,O=PGP
1723 KEYSPACE,C=US", but it might not be in the future. */
1725 vals=ldap_get_values(ldap,si_res,"baseKeySpaceDN");
1726 if(vals)
1728 basekeyspacedn=strdup(vals[0]);
1729 ldap_value_free(vals);
1732 if(opt->verbose>1)
1734 vals=ldap_get_values(ldap,si_res,"software");
1735 if(vals)
1737 fprintf(console,"Server: \t%s\n",vals[0]);
1738 ldap_value_free(vals);
1742 vals=ldap_get_values(ldap,si_res,"version");
1743 if(vals)
1745 if(opt->verbose>1)
1746 fprintf(console,"Version:\t%s\n",vals[0]);
1748 /* If the version is high enough, use the new pgpKeyV2
1749 attribute. This design if iffy at best, but it matches how
1750 PGP does it. I figure the NAI folks assumed that there would
1751 never be a LDAP keyserver vendor with a different numbering
1752 scheme. */
1753 if(atoi(vals[0])>1)
1754 pgpkeystr="pgpKeyV2";
1756 ldap_value_free(vals);
1759 ldap_msgfree(si_res);
1762 return LDAP_SUCCESS;
1765 static void
1766 show_help (FILE *fp)
1768 fprintf (fp,"-h\thelp\n");
1769 fprintf (fp,"-V\tversion\n");
1770 fprintf (fp,"-o\toutput to this file\n");
1774 main(int argc,char *argv[])
1776 int port=0,arg,err,ret=KEYSERVER_INTERNAL_ERROR;
1777 char line[MAX_LINE],*binddn=NULL,*bindpw=NULL;
1778 int failed=0,use_ssl=0,use_tls=0,bound=0;
1779 struct keylist *keylist=NULL,*keyptr=NULL;
1781 console=stderr;
1783 /* Kludge to implement standard GNU options. */
1784 if (argc > 1 && !strcmp (argv[1], "--version"))
1786 fputs ("gpgkeys_ldap (GnuPG) " VERSION"\n", stdout);
1787 return 0;
1789 else if (argc > 1 && !strcmp (argv[1], "--help"))
1791 show_help (stdout);
1792 return 0;
1795 while((arg=getopt(argc,argv,"hVo:"))!=-1)
1796 switch(arg)
1798 default:
1799 case 'h':
1800 show_help (console);
1801 return KEYSERVER_OK;
1803 case 'V':
1804 fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
1805 return KEYSERVER_OK;
1807 case 'o':
1808 output=fopen(optarg,"w");
1809 if(output==NULL)
1811 fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
1812 optarg,strerror(errno));
1813 return KEYSERVER_INTERNAL_ERROR;
1816 break;
1819 if(argc>optind)
1821 input=fopen(argv[optind],"r");
1822 if(input==NULL)
1824 fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
1825 argv[optind],strerror(errno));
1826 return KEYSERVER_INTERNAL_ERROR;
1830 if(input==NULL)
1831 input=stdin;
1833 if(output==NULL)
1834 output=stdout;
1836 opt=init_ks_options();
1837 if(!opt)
1838 return KEYSERVER_NO_MEMORY;
1840 /* Get the command and info block */
1842 while(fgets(line,MAX_LINE,input)!=NULL)
1844 char optionstr[MAX_OPTION+1];
1846 if(line[0]=='\n')
1847 break;
1849 err=parse_ks_options(line,opt);
1850 if(err>0)
1852 ret=err;
1853 goto fail;
1855 else if(err==0)
1856 continue;
1858 if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "[^\n]\n",optionstr)==1)
1860 int no=0;
1861 char *start=&optionstr[0];
1863 optionstr[MAX_OPTION]='\0';
1865 if(strncasecmp(optionstr,"no-",3)==0)
1867 no=1;
1868 start=&optionstr[3];
1871 if(strncasecmp(start,"tls",3)==0)
1873 if(no)
1874 use_tls=0;
1875 else if(start[3]=='=')
1877 if(strcasecmp(&start[4],"no")==0)
1878 use_tls=0;
1879 else if(strcasecmp(&start[4],"try")==0)
1880 use_tls=1;
1881 else if(strcasecmp(&start[4],"warn")==0)
1882 use_tls=2;
1883 else if(strcasecmp(&start[4],"require")==0)
1884 use_tls=3;
1885 else
1886 use_tls=1;
1888 else if(start[3]=='\0')
1889 use_tls=1;
1891 else if(strncasecmp(start,"basedn",6)==0)
1893 if(no)
1895 free(basekeyspacedn);
1896 basekeyspacedn=NULL;
1898 else if(start[6]=='=')
1900 free(basekeyspacedn);
1901 basekeyspacedn=strdup(&start[7]);
1902 if(!basekeyspacedn)
1904 fprintf(console,"gpgkeys: out of memory while creating "
1905 "base DN\n");
1906 ret=KEYSERVER_NO_MEMORY;
1907 goto fail;
1910 real_ldap=1;
1913 else if(strncasecmp(start,"binddn",6)==0)
1915 if(no)
1917 free(binddn);
1918 binddn=NULL;
1920 else if(start[6]=='=')
1922 free(binddn);
1923 binddn=strdup(&start[7]);
1924 if(!binddn)
1926 fprintf(console,"gpgkeys: out of memory while creating "
1927 "bind DN\n");
1928 ret=KEYSERVER_NO_MEMORY;
1929 goto fail;
1932 real_ldap=1;
1935 else if(strncasecmp(start,"bindpw",6)==0)
1937 if(no)
1939 free(bindpw);
1940 bindpw=NULL;
1942 else if(start[6]=='=')
1944 free(bindpw);
1945 bindpw=strdup(&start[7]);
1946 if(!bindpw)
1948 fprintf(console,"gpgkeys: out of memory while creating "
1949 "bind password\n");
1950 ret=KEYSERVER_NO_MEMORY;
1951 goto fail;
1954 real_ldap=1;
1958 continue;
1962 if(!opt->scheme)
1964 fprintf(console,"gpgkeys: no scheme supplied!\n");
1965 ret=KEYSERVER_SCHEME_NOT_FOUND;
1966 goto fail;
1969 if(strcasecmp(opt->scheme,"ldaps")==0)
1971 port=636;
1972 use_ssl=1;
1975 if(opt->port)
1976 port=atoi(opt->port);
1978 if(!opt->host)
1980 fprintf(console,"gpgkeys: no keyserver host provided\n");
1981 goto fail;
1984 if(opt->timeout && register_timeout()==-1)
1986 fprintf(console,"gpgkeys: unable to register timeout handler\n");
1987 return KEYSERVER_INTERNAL_ERROR;
1990 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
1992 if(opt->ca_cert_file)
1994 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_CACERTFILE,opt->ca_cert_file);
1995 if(err!=LDAP_SUCCESS)
1997 fprintf(console,"gpgkeys: unable to set ca-cert-file: %s\n",
1998 ldap_err2string(err));
1999 ret=KEYSERVER_INTERNAL_ERROR;
2000 goto fail;
2003 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
2005 /* SSL trumps TLS */
2006 if(use_ssl)
2007 use_tls=0;
2009 /* If it's a GET or a SEARCH, the next thing to come in is the
2010 keyids. If it's a SEND, then there are no keyids. */
2012 if(opt->action==KS_SEND)
2013 while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
2014 else if(opt->action==KS_GET
2015 || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
2017 for(;;)
2019 struct keylist *work;
2021 if(fgets(line,MAX_LINE,input)==NULL)
2022 break;
2023 else
2025 if(line[0]=='\n' || line[0]=='\0')
2026 break;
2028 work=malloc(sizeof(struct keylist));
2029 if(work==NULL)
2031 fprintf(console,"gpgkeys: out of memory while "
2032 "building key list\n");
2033 ret=KEYSERVER_NO_MEMORY;
2034 goto fail;
2037 strcpy(work->str,line);
2039 /* Trim the trailing \n */
2040 work->str[strlen(line)-1]='\0';
2042 work->next=NULL;
2044 /* Always attach at the end to keep the list in proper
2045 order for searching */
2046 if(keylist==NULL)
2047 keylist=work;
2048 else
2049 keyptr->next=work;
2051 keyptr=work;
2055 else
2057 fprintf(console,"gpgkeys: no keyserver command specified\n");
2058 goto fail;
2061 /* Send the response */
2063 fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
2064 fprintf(output,"PROGRAM %s\n\n",VERSION);
2066 if(opt->verbose>1)
2068 fprintf(console,"Host:\t\t%s\n",opt->host);
2069 if(port)
2070 fprintf(console,"Port:\t\t%d\n",port);
2071 fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
2074 if(opt->debug)
2076 #if defined(LDAP_OPT_DEBUG_LEVEL) && defined(HAVE_LDAP_SET_OPTION)
2077 err=ldap_set_option(NULL,LDAP_OPT_DEBUG_LEVEL,&opt->debug);
2078 if(err!=LDAP_SUCCESS)
2079 fprintf(console,"gpgkeys: unable to set debug mode: %s\n",
2080 ldap_err2string(err));
2081 else
2082 fprintf(console,"gpgkeys: debug level %d\n",opt->debug);
2083 #else
2084 fprintf(console,"gpgkeys: not built with debugging support\n");
2085 #endif
2088 /* We have a timeout set for the setup stuff since it could time out
2089 as well. */
2090 set_timeout(opt->timeout);
2092 /* Note that this tries all A records on a given host (or at least,
2093 OpenLDAP does). */
2094 ldap=ldap_init(opt->host,port);
2095 if(ldap==NULL)
2097 fprintf(console,"gpgkeys: internal LDAP init error: %s\n",
2098 strerror(errno));
2099 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2100 goto fail;
2103 if(use_ssl)
2105 #if defined(LDAP_OPT_X_TLS) && defined(HAVE_LDAP_SET_OPTION)
2106 int ssl=LDAP_OPT_X_TLS_HARD;
2108 err=ldap_set_option(ldap,LDAP_OPT_X_TLS,&ssl);
2109 if(err!=LDAP_SUCCESS)
2111 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2112 ldap_err2string(err));
2113 fail_all(keylist,ldap_err_to_gpg_err(err));
2114 goto fail;
2117 if(!opt->flags.check_cert)
2118 ssl=LDAP_OPT_X_TLS_NEVER;
2120 err=ldap_set_option(NULL,LDAP_OPT_X_TLS_REQUIRE_CERT,&ssl);
2121 if(err!=LDAP_SUCCESS)
2123 fprintf(console,
2124 "gpgkeys: unable to set certificate validation: %s\n",
2125 ldap_err2string(err));
2126 fail_all(keylist,ldap_err_to_gpg_err(err));
2127 goto fail;
2129 #else
2130 fprintf(console,"gpgkeys: unable to make SSL connection: %s\n",
2131 "not built with LDAPS support");
2132 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2133 goto fail;
2134 #endif
2137 if(!basekeyspacedn)
2138 if((err=find_basekeyspacedn()) || !basekeyspacedn)
2140 fprintf(console,"gpgkeys: unable to retrieve LDAP base: %s\n",
2141 err?ldap_err2string(err):"not found");
2142 fail_all(keylist,ldap_err_to_gpg_err(err));
2143 goto fail;
2146 /* use_tls: 0=don't use, 1=try silently to use, 2=try loudly to use,
2147 3=force use. */
2148 if(use_tls)
2150 if(!real_ldap)
2152 if(use_tls>=2)
2153 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2154 "not supported by the NAI LDAP keyserver");
2155 if(use_tls==3)
2157 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2158 goto fail;
2161 else
2163 #if defined(HAVE_LDAP_START_TLS_S) && defined(HAVE_LDAP_SET_OPTION)
2164 int ver=LDAP_VERSION3;
2166 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2168 #ifdef LDAP_OPT_X_TLS
2169 if(err==LDAP_SUCCESS)
2171 if(opt->flags.check_cert)
2172 ver=LDAP_OPT_X_TLS_HARD;
2173 else
2174 ver=LDAP_OPT_X_TLS_NEVER;
2176 err=ldap_set_option(ldap,LDAP_OPT_X_TLS_REQUIRE_CERT,&ver);
2178 #endif
2180 if(err==LDAP_SUCCESS)
2181 err=ldap_start_tls_s(ldap,NULL,NULL);
2183 if(err!=LDAP_SUCCESS)
2185 if(use_tls>=2 || opt->verbose>2)
2186 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2187 ldap_err2string(err));
2188 /* Are we forcing it? */
2189 if(use_tls==3)
2191 fail_all(keylist,ldap_err_to_gpg_err(err));
2192 goto fail;
2195 else if(opt->verbose>1)
2196 fprintf(console,"gpgkeys: TLS started successfully.\n");
2197 #else
2198 if(use_tls>=2)
2199 fprintf(console,"gpgkeys: unable to start TLS: %s\n",
2200 "not built with TLS support");
2201 if(use_tls==3)
2203 fail_all(keylist,KEYSERVER_INTERNAL_ERROR);
2204 goto fail;
2206 #endif
2210 /* By default we don't bind as there is usually no need to. For
2211 cases where the server needs some authentication, the user can
2212 use binddn and bindpw for auth. */
2214 if(binddn)
2216 #ifdef HAVE_LDAP_SET_OPTION
2217 int ver=LDAP_VERSION3;
2219 err=ldap_set_option(ldap,LDAP_OPT_PROTOCOL_VERSION,&ver);
2220 if(err!=LDAP_SUCCESS)
2222 fprintf(console,"gpgkeys: unable to go to LDAP 3: %s\n",
2223 ldap_err2string(err));
2224 fail_all(keylist,ldap_err_to_gpg_err(err));
2225 goto fail;
2227 #endif
2229 if(opt->verbose>2)
2230 fprintf(console,"gpgkeys: LDAP bind to %s, pw %s\n",binddn,
2231 bindpw?">not shown<":">none<");
2232 err=ldap_simple_bind_s(ldap,binddn,bindpw);
2233 if(err!=LDAP_SUCCESS)
2235 fprintf(console,"gpgkeys: internal LDAP bind error: %s\n",
2236 ldap_err2string(err));
2237 fail_all(keylist,ldap_err_to_gpg_err(err));
2238 goto fail;
2240 else
2241 bound=1;
2244 if(opt->action==KS_GET)
2246 keyptr=keylist;
2248 while(keyptr!=NULL)
2250 set_timeout(opt->timeout);
2252 if(get_key(keyptr->str)!=KEYSERVER_OK)
2253 failed++;
2255 keyptr=keyptr->next;
2258 else if(opt->action==KS_GETNAME)
2260 keyptr=keylist;
2262 while(keyptr!=NULL)
2264 set_timeout(opt->timeout);
2266 if(get_name(keyptr->str)!=KEYSERVER_OK)
2267 failed++;
2269 keyptr=keyptr->next;
2272 else if(opt->action==KS_SEND)
2274 int eof=0;
2278 set_timeout(opt->timeout);
2280 if(real_ldap)
2282 if(send_key(&eof)!=KEYSERVER_OK)
2283 failed++;
2285 else
2287 if(send_key_keyserver(&eof)!=KEYSERVER_OK)
2288 failed++;
2291 while(!eof);
2293 else if(opt->action==KS_SEARCH)
2295 char *searchkey=NULL;
2296 int len=0;
2298 set_timeout(opt->timeout);
2300 /* To search, we stick a * in between each key to search for.
2301 This means that if the user enters words, they'll get
2302 "enters*words". If the user "enters words", they'll get
2303 "enters words" */
2305 keyptr=keylist;
2306 while(keyptr!=NULL)
2308 len+=strlen(keyptr->str)+1;
2309 keyptr=keyptr->next;
2312 searchkey=malloc(len+1);
2313 if(searchkey==NULL)
2315 ret=KEYSERVER_NO_MEMORY;
2316 fail_all(keylist,KEYSERVER_NO_MEMORY);
2317 goto fail;
2320 searchkey[0]='\0';
2322 keyptr=keylist;
2323 while(keyptr!=NULL)
2325 strcat(searchkey,keyptr->str);
2326 strcat(searchkey,"*");
2327 keyptr=keyptr->next;
2330 /* Nail that last "*" */
2331 if(*searchkey)
2332 searchkey[strlen(searchkey)-1]='\0';
2334 if(search_key(searchkey)!=KEYSERVER_OK)
2335 failed++;
2337 free(searchkey);
2339 else
2340 assert (!"bad action");
2342 if(!failed)
2343 ret=KEYSERVER_OK;
2345 fail:
2347 while(keylist!=NULL)
2349 struct keylist *current=keylist;
2350 keylist=keylist->next;
2351 free(current);
2354 if(input!=stdin)
2355 fclose(input);
2357 if(output!=stdout)
2358 fclose(output);
2360 free_ks_options(opt);
2362 if(ldap!=NULL && bound)
2363 ldap_unbind_s(ldap);
2365 free(basekeyspacedn);
2367 return ret;