Imported Upstream version 2.2.26
[platform/upstream/gpg2.git] / dirmngr / ks-engine-ldap.c
1 /* ks-engine-ldap.c - talk to a LDAP keyserver
2  * Copyright (C) 2001, 2002, 2004, 2005, 2006
3  *               2007  Free Software Foundation, Inc.
4  * Copyright (C) 2015, 2020  g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <time.h>
26 #include <unistd.h>
27 #ifdef HAVE_GETOPT_H
28 # include <getopt.h>
29 #endif
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <assert.h>
33
34 #ifdef _WIN32
35 # include <winsock2.h>
36 # include <winldap.h>
37 #else
38 # ifdef NEED_LBER_H
39 #  include <lber.h>
40 # endif
41 /* For OpenLDAP, to enable the API that we're using. */
42 # define LDAP_DEPRECATED 1
43 # include <ldap.h>
44 #endif
45 #include <npth.h>
46
47 #include "dirmngr.h"
48 #include "misc.h"
49 #include "../common/userids.h"
50 #include "../common/mbox-util.h"
51 #include "ks-engine.h"
52 #include "ldap-parse-uri.h"
53
54
55 /* Flags with infos from the connected server.  */
56 #define SERVERINFO_REALLDAP 1 /* This is not the PGP keyserver.      */
57 #define SERVERINFO_PGPKEYV2 2 /* Needs "pgpeyV2" instead of "pgpKey" */
58 #define SERVERINFO_SCHEMAV2 4 /* Version 2 of the Schema.            */
59 #define SERVERINFO_NTDS     8 /* Server is an Active Directory.      */
60
61
62
63 #ifndef HAVE_TIMEGM
64 time_t timegm(struct tm *tm);
65 #endif
66 \f
67 /* Convert an LDAP error to a GPG error.  */
68 static int
69 ldap_err_to_gpg_err (int code)
70 {
71   gpg_err_code_t ec;
72
73   switch (code)
74     {
75 #ifdef LDAP_X_CONNECTING
76     case LDAP_X_CONNECTING: ec = GPG_ERR_LDAP_X_CONNECTING; break;
77 #endif
78
79     case LDAP_REFERRAL_LIMIT_EXCEEDED: ec = GPG_ERR_LDAP_REFERRAL_LIMIT; break;
80     case LDAP_CLIENT_LOOP: ec = GPG_ERR_LDAP_CLIENT_LOOP; break;
81     case LDAP_NO_RESULTS_RETURNED: ec = GPG_ERR_LDAP_NO_RESULTS; break;
82     case LDAP_CONTROL_NOT_FOUND: ec = GPG_ERR_LDAP_CONTROL_NOT_FOUND; break;
83     case LDAP_NOT_SUPPORTED: ec = GPG_ERR_LDAP_NOT_SUPPORTED; break;
84     case LDAP_CONNECT_ERROR: ec = GPG_ERR_LDAP_CONNECT; break;
85     case LDAP_NO_MEMORY: ec = GPG_ERR_LDAP_NO_MEMORY; break;
86     case LDAP_PARAM_ERROR: ec = GPG_ERR_LDAP_PARAM; break;
87     case LDAP_USER_CANCELLED: ec = GPG_ERR_LDAP_USER_CANCELLED; break;
88     case LDAP_FILTER_ERROR: ec = GPG_ERR_LDAP_FILTER; break;
89     case LDAP_AUTH_UNKNOWN: ec = GPG_ERR_LDAP_AUTH_UNKNOWN; break;
90     case LDAP_TIMEOUT: ec = GPG_ERR_LDAP_TIMEOUT; break;
91     case LDAP_DECODING_ERROR: ec = GPG_ERR_LDAP_DECODING; break;
92     case LDAP_ENCODING_ERROR: ec = GPG_ERR_LDAP_ENCODING; break;
93     case LDAP_LOCAL_ERROR: ec = GPG_ERR_LDAP_LOCAL; break;
94     case LDAP_SERVER_DOWN: ec = GPG_ERR_LDAP_SERVER_DOWN; break;
95
96     case LDAP_SUCCESS: ec = GPG_ERR_LDAP_SUCCESS; break;
97
98     case LDAP_OPERATIONS_ERROR: ec = GPG_ERR_LDAP_OPERATIONS; break;
99     case LDAP_PROTOCOL_ERROR: ec = GPG_ERR_LDAP_PROTOCOL; break;
100     case LDAP_TIMELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_TIMELIMIT; break;
101     case LDAP_SIZELIMIT_EXCEEDED: ec = GPG_ERR_LDAP_SIZELIMIT; break;
102     case LDAP_COMPARE_FALSE: ec = GPG_ERR_LDAP_COMPARE_FALSE; break;
103     case LDAP_COMPARE_TRUE: ec = GPG_ERR_LDAP_COMPARE_TRUE; break;
104     case LDAP_AUTH_METHOD_NOT_SUPPORTED: ec=GPG_ERR_LDAP_UNSUPPORTED_AUTH;break;
105     case LDAP_STRONG_AUTH_REQUIRED: ec = GPG_ERR_LDAP_STRONG_AUTH_RQRD; break;
106     case LDAP_PARTIAL_RESULTS: ec = GPG_ERR_LDAP_PARTIAL_RESULTS; break;
107     case LDAP_REFERRAL: ec = GPG_ERR_LDAP_REFERRAL; break;
108
109 #ifdef LDAP_ADMINLIMIT_EXCEEDED
110     case LDAP_ADMINLIMIT_EXCEEDED: ec = GPG_ERR_LDAP_ADMINLIMIT; break;
111 #endif
112
113 #ifdef LDAP_UNAVAILABLE_CRITICAL_EXTENSION
114     case LDAP_UNAVAILABLE_CRITICAL_EXTENSION:
115                                ec = GPG_ERR_LDAP_UNAVAIL_CRIT_EXTN; break;
116 #endif
117
118     case LDAP_CONFIDENTIALITY_REQUIRED: ec = GPG_ERR_LDAP_CONFIDENT_RQRD; break;
119     case LDAP_SASL_BIND_IN_PROGRESS: ec = GPG_ERR_LDAP_SASL_BIND_INPROG; break;
120     case LDAP_NO_SUCH_ATTRIBUTE: ec = GPG_ERR_LDAP_NO_SUCH_ATTRIBUTE; break;
121     case LDAP_UNDEFINED_TYPE: ec = GPG_ERR_LDAP_UNDEFINED_TYPE; break;
122     case LDAP_INAPPROPRIATE_MATCHING: ec = GPG_ERR_LDAP_BAD_MATCHING; break;
123     case LDAP_CONSTRAINT_VIOLATION: ec = GPG_ERR_LDAP_CONST_VIOLATION; break;
124
125 #ifdef LDAP_TYPE_OR_VALUE_EXISTS
126     case LDAP_TYPE_OR_VALUE_EXISTS: ec = GPG_ERR_LDAP_TYPE_VALUE_EXISTS; break;
127 #endif
128
129     case LDAP_INVALID_SYNTAX: ec = GPG_ERR_LDAP_INV_SYNTAX; break;
130     case LDAP_NO_SUCH_OBJECT: ec = GPG_ERR_LDAP_NO_SUCH_OBJ; break;
131     case LDAP_ALIAS_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_PROBLEM; break;
132     case LDAP_INVALID_DN_SYNTAX: ec = GPG_ERR_LDAP_INV_DN_SYNTAX; break;
133     case LDAP_IS_LEAF: ec = GPG_ERR_LDAP_IS_LEAF; break;
134     case LDAP_ALIAS_DEREF_PROBLEM: ec = GPG_ERR_LDAP_ALIAS_DEREF; break;
135
136 #ifdef LDAP_X_PROXY_AUTHZ_FAILURE
137     case LDAP_X_PROXY_AUTHZ_FAILURE: ec = GPG_ERR_LDAP_X_PROXY_AUTH_FAIL; break;
138 #endif
139
140     case LDAP_INAPPROPRIATE_AUTH: ec = GPG_ERR_LDAP_BAD_AUTH; break;
141     case LDAP_INVALID_CREDENTIALS: ec = GPG_ERR_LDAP_INV_CREDENTIALS; break;
142
143 #ifdef LDAP_INSUFFICIENT_ACCESS
144     case LDAP_INSUFFICIENT_ACCESS: ec = GPG_ERR_LDAP_INSUFFICIENT_ACC; break;
145 #endif
146
147     case LDAP_BUSY: ec = GPG_ERR_LDAP_BUSY; break;
148     case LDAP_UNAVAILABLE: ec = GPG_ERR_LDAP_UNAVAILABLE; break;
149     case LDAP_UNWILLING_TO_PERFORM: ec = GPG_ERR_LDAP_UNWILL_TO_PERFORM; break;
150     case LDAP_LOOP_DETECT: ec = GPG_ERR_LDAP_LOOP_DETECT; break;
151     case LDAP_NAMING_VIOLATION: ec = GPG_ERR_LDAP_NAMING_VIOLATION; break;
152     case LDAP_OBJECT_CLASS_VIOLATION: ec = GPG_ERR_LDAP_OBJ_CLS_VIOLATION; break;
153     case LDAP_NOT_ALLOWED_ON_NONLEAF: ec=GPG_ERR_LDAP_NOT_ALLOW_NONLEAF;break;
154     case LDAP_NOT_ALLOWED_ON_RDN: ec = GPG_ERR_LDAP_NOT_ALLOW_ON_RDN; break;
155     case LDAP_ALREADY_EXISTS: ec = GPG_ERR_LDAP_ALREADY_EXISTS; break;
156     case LDAP_NO_OBJECT_CLASS_MODS: ec = GPG_ERR_LDAP_NO_OBJ_CLASS_MODS; break;
157     case LDAP_RESULTS_TOO_LARGE: ec = GPG_ERR_LDAP_RESULTS_TOO_LARGE; break;
158     case LDAP_AFFECTS_MULTIPLE_DSAS: ec = GPG_ERR_LDAP_AFFECTS_MULT_DSAS; break;
159
160 #ifdef LDAP_VLV_ERROR
161     case LDAP_VLV_ERROR: ec = GPG_ERR_LDAP_VLV; break;
162 #endif
163
164     case LDAP_OTHER: ec = GPG_ERR_LDAP_OTHER; break;
165
166 #ifdef LDAP_CUP_RESOURCES_EXHAUSTED
167     case LDAP_CUP_RESOURCES_EXHAUSTED: ec=GPG_ERR_LDAP_CUP_RESOURCE_LIMIT;break;
168     case LDAP_CUP_SECURITY_VIOLATION: ec=GPG_ERR_LDAP_CUP_SEC_VIOLATION; break;
169     case LDAP_CUP_INVALID_DATA: ec = GPG_ERR_LDAP_CUP_INV_DATA; break;
170     case LDAP_CUP_UNSUPPORTED_SCHEME: ec = GPG_ERR_LDAP_CUP_UNSUP_SCHEME; break;
171     case LDAP_CUP_RELOAD_REQUIRED: ec = GPG_ERR_LDAP_CUP_RELOAD; break;
172 #endif
173
174 #ifdef LDAP_CANCELLED
175     case LDAP_CANCELLED: ec = GPG_ERR_LDAP_CANCELLED; break;
176 #endif
177
178 #ifdef LDAP_NO_SUCH_OPERATION
179     case LDAP_NO_SUCH_OPERATION: ec = GPG_ERR_LDAP_NO_SUCH_OPERATION; break;
180 #endif
181
182 #ifdef LDAP_TOO_LATE
183     case LDAP_TOO_LATE: ec = GPG_ERR_LDAP_TOO_LATE; break;
184 #endif
185
186 #ifdef LDAP_CANNOT_CANCEL
187     case LDAP_CANNOT_CANCEL: ec = GPG_ERR_LDAP_CANNOT_CANCEL; break;
188 #endif
189
190 #ifdef LDAP_ASSERTION_FAILED
191     case LDAP_ASSERTION_FAILED: ec = GPG_ERR_LDAP_ASSERTION_FAILED; break;
192 #endif
193
194 #ifdef LDAP_PROXIED_AUTHORIZATION_DENIED
195     case LDAP_PROXIED_AUTHORIZATION_DENIED:
196                                       ec = GPG_ERR_LDAP_PROX_AUTH_DENIED; break;
197 #endif
198
199     default:
200 #if defined(LDAP_E_ERROR) && defined(LDAP_X_ERROR)
201       if (LDAP_E_ERROR (code))
202         ec = GPG_ERR_LDAP_E_GENERAL;
203       else if (LDAP_X_ERROR (code))
204         ec = GPG_ERR_LDAP_X_GENERAL;
205       else
206 #endif
207         ec = GPG_ERR_LDAP_GENERAL;
208       break;
209     }
210
211   return ec;
212 }
213
214 /* Retrieve an LDAP error and return it's GPG equivalent.  */
215 static int
216 ldap_to_gpg_err (LDAP *ld)
217 {
218 #if defined(HAVE_LDAP_GET_OPTION) && defined(LDAP_OPT_ERROR_NUMBER)
219   int err;
220
221   if (ldap_get_option (ld, LDAP_OPT_ERROR_NUMBER, &err) == 0)
222     return ldap_err_to_gpg_err (err);
223   else
224     return GPG_ERR_GENERAL;
225 #elif defined(HAVE_LDAP_LD_ERRNO)
226   return ldap_err_to_gpg_err (ld->ld_errno);
227 #else
228   /* We should never get here since the LDAP library should always
229      have either ldap_get_option or ld_errno, but just in case... */
230   return GPG_ERR_INTERNAL;
231 #endif
232 }
233 \f
234 static time_t
235 ldap2epochtime (const char *timestr)
236 {
237   struct tm pgptime;
238   time_t answer;
239
240   memset (&pgptime, 0, sizeof(pgptime));
241
242   /* YYYYMMDDHHmmssZ */
243
244   sscanf (timestr, "%4d%2d%2d%2d%2d%2d",
245           &pgptime.tm_year,
246           &pgptime.tm_mon,
247           &pgptime.tm_mday,
248           &pgptime.tm_hour,
249           &pgptime.tm_min,
250           &pgptime.tm_sec);
251
252   pgptime.tm_year -= 1900;
253   pgptime.tm_isdst = -1;
254   pgptime.tm_mon--;
255
256   /* mktime() takes the timezone into account, so we use timegm() */
257
258   answer = timegm (&pgptime);
259
260   return answer;
261 }
262
263 /* Caller must free the result.  */
264 static char *
265 tm2ldaptime (struct tm *tm)
266 {
267   struct tm tmp = *tm;
268   char buf[16];
269
270   /* YYYYMMDDHHmmssZ */
271
272   tmp.tm_year += 1900;
273   tmp.tm_mon ++;
274
275   snprintf (buf, sizeof buf, "%04d%02d%02d%02d%02d%02dZ",
276            tmp.tm_year,
277            tmp.tm_mon,
278            tmp.tm_mday,
279            tmp.tm_hour,
280            tmp.tm_min,
281            tmp.tm_sec);
282
283   return xstrdup (buf);
284 }
285
286 #if 0
287 /* Caller must free */
288 static char *
289 epoch2ldaptime (time_t stamp)
290 {
291   struct tm tm;
292   if (gmtime_r (&stamp, &tm))
293     return tm2ldaptime (&tm);
294   else
295     return xstrdup ("INVALID TIME");
296 }
297 #endif
298 \f
299 /* Print a help output for the schemata supported by this module. */
300 gpg_error_t
301 ks_ldap_help (ctrl_t ctrl, parsed_uri_t uri)
302 {
303   const char data[] =
304     "Handler for LDAP URLs:\n"
305     "  ldap://host:port/[BASEDN]???[bindname=BINDNAME,password=PASSWORD]\n"
306     "\n"
307     "Note: basedn, bindname and password need to be percent escaped. In\n"
308     "particular, spaces need to be replaced with %20 and commas with %2c.\n"
309     "bindname will typically be of the form:\n"
310     "\n"
311     "  uid=user%2cou=PGP%20Users%2cdc=EXAMPLE%2cdc=ORG\n"
312     "\n"
313     "The ldaps:// and ldapi:// schemes are also supported.  If ldaps is used\n"
314     "then the server's certificate will be checked.  If it is not valid, any\n"
315     "operation will be aborted.\n"
316     "\n"
317     "Supported methods: search, get, put\n";
318   gpg_error_t err;
319
320   if(!uri)
321     err = ks_print_help (ctrl, "  ldap");
322   else if (strcmp (uri->scheme, "ldap") == 0
323       || strcmp (uri->scheme, "ldaps") == 0
324       || strcmp (uri->scheme, "ldapi") == 0)
325     err = ks_print_help (ctrl, data);
326   else
327     err = 0;
328
329   return err;
330 }
331 \f
332 /* Convert a keyspec to a filter.  Return an error if the keyspec is
333    bad or is not supported.  The filter is escaped and returned in
334    *filter.  It is the caller's responsibility to free *filter.
335    *filter is only set if this function returns success (i.e., 0).  */
336 static gpg_error_t
337 keyspec_to_ldap_filter (const char *keyspec, char **filter, int only_exact,
338                         unsigned int serverinfo)
339 {
340   /* Remove search type indicator and adjust PATTERN accordingly.
341      Note: don't include a preceding 0x when searching by keyid.  */
342
343   /* XXX: Should we include disabled / revoke options?  */
344   KEYDB_SEARCH_DESC desc;
345   char *f = NULL;
346   char *freeme = NULL;
347   char *p;
348
349   gpg_error_t err = classify_user_id (keyspec, &desc, 1);
350   if (err)
351     return err;
352
353   switch (desc.mode)
354     {
355     case KEYDB_SEARCH_MODE_EXACT:
356       f = xasprintf ("(pgpUserID=%s)",
357                      (freeme = ldap_escape_filter (desc.u.name)));
358       break;
359
360     case KEYDB_SEARCH_MODE_SUBSTR:
361       if (! only_exact)
362         f = xasprintf ("(pgpUserID=*%s*)",
363                        (freeme = ldap_escape_filter (desc.u.name)));
364       break;
365
366     case KEYDB_SEARCH_MODE_MAIL:
367       freeme = ldap_escape_filter (desc.u.name);
368       if (!freeme)
369         break;
370       if (*freeme == '<' && freeme[1] && freeme[2])
371         {
372           /* Strip angle brackets.  Note that it is does not
373            * matter whether we work on the plan or LDAP escaped
374            * version of the mailbox.  */
375           p = freeme + 1;
376           if (p[strlen(p)-1] == '>')
377             p[strlen(p)-1] = 0;
378         }
379       else
380         p = freeme;
381       if ((serverinfo & SERVERINFO_SCHEMAV2))
382         f = xasprintf ("(gpgMailbox=%s)", p);
383       else if (!only_exact)
384         f = xasprintf ("(pgpUserID=*<%s>*)", p);
385       break;
386
387     case KEYDB_SEARCH_MODE_MAILSUB:
388       if (! only_exact)
389         f = xasprintf ("(pgpUserID=*<*%s*>*)",
390                        (freeme = ldap_escape_filter (desc.u.name)));
391       break;
392
393     case KEYDB_SEARCH_MODE_MAILEND:
394       if (! only_exact)
395         f = xasprintf ("(pgpUserID=*<*%s>*)",
396                        (freeme = ldap_escape_filter (desc.u.name)));
397       break;
398
399     case KEYDB_SEARCH_MODE_SHORT_KID:
400       f = xasprintf ("(pgpKeyID=%08lX)", (ulong) desc.u.kid[1]);
401       break;
402     case KEYDB_SEARCH_MODE_LONG_KID:
403       f = xasprintf ("(pgpCertID=%08lX%08lX)",
404                      (ulong) desc.u.kid[0], (ulong) desc.u.kid[1]);
405       break;
406
407     case KEYDB_SEARCH_MODE_FPR16:
408     case KEYDB_SEARCH_MODE_FPR20:
409     case KEYDB_SEARCH_MODE_FPR:
410       if ((serverinfo & SERVERINFO_SCHEMAV2))
411         {
412           freeme = bin2hex (desc.u.fpr, 20, NULL);
413           if (!freeme)
414             return gpg_error_from_syserror ();
415           f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))",
416                          freeme, freeme);
417           /* FIXME: For an exact search and in case of a match on
418            * gpgSubFingerprint we need to check that there is only one
419            * matching value.  */
420         }
421       break;
422
423     case KEYDB_SEARCH_MODE_ISSUER:
424     case KEYDB_SEARCH_MODE_ISSUER_SN:
425     case KEYDB_SEARCH_MODE_SN:
426     case KEYDB_SEARCH_MODE_SUBJECT:
427     case KEYDB_SEARCH_MODE_KEYGRIP:
428     case KEYDB_SEARCH_MODE_WORDS:
429     case KEYDB_SEARCH_MODE_FIRST:
430     case KEYDB_SEARCH_MODE_NEXT:
431     default:
432       break;
433     }
434
435   xfree (freeme);
436
437   if (! f)
438     {
439       log_error ("Unsupported search mode.\n");
440       return gpg_error (GPG_ERR_NOT_SUPPORTED);
441     }
442
443   *filter = f;
444
445   return 0;
446 }
447
448
449 \f
450 /* Connect to an LDAP server and interrogate it.
451
452      - uri describes the server to connect to and various options
453        including whether to use TLS and the username and password (see
454        ldap_parse_uri for a description of the various fields).
455
456    This function returns:
457
458      - The ldap connection handle in *LDAP_CONNP.
459
460      - The base DN for the PGP key space by querying the
461        pgpBaseKeySpaceDN attribute (This is normally
462        'ou=PGP Keys,dc=EXAMPLE,dc=ORG').
463
464      - The attribute to lookup to find the pgp key.  This is either
465        'pgpKey' or 'pgpKeyV2'.
466
467      - Whether this is a real ldap server.  (It's unclear what this
468        exactly means.)
469
470    The values are returned in the passed variables.  If you pass NULL,
471    then the value won't be returned.  It is the caller's
472    responsibility to release *LDAP_CONNP with ldap_unbind and xfree
473    *BASEDNP.
474
475    If this function successfully interrogated the server, it returns
476    0.  If there was an LDAP error, it returns the LDAP error code.  If
477    an error occurred, *basednp, etc., are undefined (and don't need to
478    be freed.)
479
480    R_SERVERINFO receives information about the server.
481
482    If no LDAP error occurred, you still need to check that *basednp is
483    valid.  If it is NULL, then the server does not appear to be an
484    OpenPGP Keyserver.  */
485 static int
486 my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp,
487                  char **basednp, unsigned int *r_serverinfo)
488 {
489   int err = 0;
490   LDAP *ldap_conn = NULL;
491   char *user = uri->auth;
492   struct uri_tuple_s *password_param;
493   char *password;
494   char *basedn = NULL;
495
496   *r_serverinfo = 0;
497
498   password_param = uri_query_lookup (uri, "password");
499   password = password_param ? password_param->value : NULL;
500
501   if (opt.debug)
502     log_debug ("my_ldap_connect(%s:%d/%s????%s%s%s%s%s%s)\n",
503                uri->host, uri->port,
504                uri->path ? uri->path : "",
505                uri->auth ? "bindname=" : "",
506                uri->auth ? uri->auth : "",
507                uri->auth && password ? "," : "",
508                password ? "password=" : "",
509                password ? ">not shown<": "",
510                uri->ad_current? " auth=>current_user<":"");
511
512   /* If the uri specifies a secure connection and we don't support
513      TLS, then fail; don't silently revert to an insecure
514      connection.  */
515   if (uri->use_tls)
516     {
517 #ifndef HAVE_LDAP_START_TLS_S
518       log_error ("Can't use LDAP to connect to the server: no TLS support.");
519       err = GPG_ERR_LDAP_NOT_SUPPORTED;
520       goto out;
521 #endif
522     }
523
524   if (uri->ad_current)
525     ldap_conn = ldap_init (NULL, uri->port);
526   else
527     ldap_conn = ldap_init (uri->host, uri->port);
528   if (!ldap_conn)
529     {
530       err = gpg_err_code_from_syserror ();
531       if (uri->ad_current)
532         log_error ("error initializing LDAP for current user\n");
533       else
534         log_error ("error initializing LDAP for (%s://%s:%d)\n",
535                    uri->scheme, uri->host, uri->port);
536       goto out;
537     }
538
539 #ifdef HAVE_LDAP_SET_OPTION
540   {
541     int ver = LDAP_VERSION3;
542
543     err = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
544     if (err != LDAP_SUCCESS)
545       {
546         log_error ("ks-ldap: unable to go to LDAP 3: %s\n",
547                    ldap_err2string (err));
548         goto out;
549       }
550   }
551 #endif
552
553   /* XXX: It would be nice to have an option to provide the server's
554      certificate.  */
555 #if 0
556 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
557   err = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, ca_cert_file);
558   if (err)
559     {
560       log_error ("unable to set ca-cert-file to '%s': %s\n",
561                  ca_cert_file, ldap_err2string (err));
562       goto out;
563     }
564 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
565 #endif
566
567 #ifdef HAVE_LDAP_START_TLS_S
568   if (uri->use_tls)
569     {
570       /* XXX: We need an option to determine whether to abort if the
571          certificate is bad or not.  Right now we conservatively
572          default to checking the certificate and aborting.  */
573 #ifndef HAVE_W32_SYSTEM
574       int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
575
576       err = ldap_set_option (ldap_conn,
577                              LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
578       if (err)
579         {
580           log_error ("error setting TLS option on LDAP connection\n");
581           goto out;
582         }
583 #else
584       /* On Windows, the certificates are checked by default.  If the
585          option to disable checking mentioned above is ever
586          implemented, the way to do that on Windows is to install a
587          callback routine using ldap_set_option (..,
588          LDAP_OPT_SERVER_CERTIFICATE, ..); */
589 #endif
590
591       npth_unprotect ();
592       err = ldap_start_tls_s (ldap_conn,
593 #ifdef HAVE_W32_SYSTEM
594                               /* ServerReturnValue, result */
595                               NULL, NULL,
596 #endif
597                               /* ServerControls, ClientControls */
598                               NULL, NULL);
599       npth_protect ();
600       if (err)
601         {
602           log_error ("error connecting to LDAP server with TLS\n");
603           goto out;
604         }
605     }
606 #endif
607
608   if (uri->ad_current)
609     {
610       if (opt.debug)
611         log_debug ("LDAP bind to current user via AD\n");
612 #ifdef HAVE_W32_SYSTEM
613       npth_unprotect ();
614       err = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE);
615       npth_protect ();
616 #else
617       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
618 #endif
619       if (err != LDAP_SUCCESS)
620         {
621           log_error ("error binding to LDAP via AD: %s\n",
622                      ldap_err2string (err));
623           goto out;
624         }
625     }
626   else if (uri->auth)
627     {
628       if (opt.debug)
629         log_debug ("LDAP bind to %s, password %s\n",
630                    user, password ? ">not shown<" : ">none<");
631
632       npth_unprotect ();
633       err = ldap_simple_bind_s (ldap_conn, user, password);
634       npth_protect ();
635       if (err != LDAP_SUCCESS)
636         {
637           log_error ("error binding to LDAP: %s\n", ldap_err2string (err));
638           goto out;
639         }
640     }
641   else
642     {
643       /* By default we don't bind as there is usually no need to.  */
644     }
645
646   if (uri->path && *uri->path)
647     {
648       /* User specified base DN.  */
649       basedn = xstrdup (uri->path);
650
651       /* If the user specifies a base DN, then we know the server is a
652        * real LDAP server.  */
653       *r_serverinfo |= SERVERINFO_REALLDAP;
654     }
655   else
656     { /* Look for namingContexts.  */
657       LDAPMessage *res = NULL;
658       char *attr[] = { "namingContexts", NULL };
659
660       npth_unprotect ();
661       err = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
662                            "(objectClass=*)", attr, 0, &res);
663       npth_protect ();
664
665       if (err == LDAP_SUCCESS)
666         {
667           char **context;
668
669           npth_unprotect ();
670           context = ldap_get_values (ldap_conn, res, "namingContexts");
671           npth_protect ();
672           if (context)
673             {
674               /* We found some, so try each namingContext as the
675                * search base and look for pgpBaseKeySpaceDN.  Because
676                * we found this, we know we're talking to a regular-ish
677                * LDAP server and not an LDAP keyserver.  */
678               int i;
679               char *attr2[] =
680                 { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
681
682               *r_serverinfo |= SERVERINFO_REALLDAP;
683
684               for (i = 0; context[i] && ! basedn; i++)
685                 {
686                   char **vals;
687                   LDAPMessage *si_res;
688                   int is_gnupg = 0;
689
690                   {
691                     char *object = xasprintf ("cn=pgpServerInfo,%s",
692                                               context[i]);
693                     npth_unprotect ();
694                     err = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
695                                          "(objectClass=*)", attr2, 0, &si_res);
696                     npth_protect ();
697                     xfree (object);
698                   }
699
700                   if (err == LDAP_SUCCESS)
701                     {
702                       vals = ldap_get_values (ldap_conn, si_res,
703                                               "pgpBaseKeySpaceDN");
704                       if (vals)
705                         {
706                           basedn = xtrystrdup (vals[0]);
707                           ldap_value_free (vals);
708                         }
709
710                       vals = ldap_get_values (ldap_conn, si_res,
711                                               "pgpSoftware");
712                       if (vals)
713                         {
714                           if (opt.debug)
715                             log_debug ("Server: \t%s\n", vals[0]);
716                           if (!ascii_strcasecmp (vals[0], "GnuPG"))
717                             is_gnupg = 1;
718                           ldap_value_free (vals);
719                         }
720
721                       vals = ldap_get_values (ldap_conn, si_res,
722                                               "pgpVersion");
723                       if (vals)
724                         {
725                           if (opt.debug)
726                             log_debug ("Version:\t%s\n", vals[0]);
727                           if (is_gnupg)
728                             {
729                               char *fields[2];
730                               int nfields;
731                               nfields = split_fields (vals[0],
732                                                       fields, DIM(fields));
733                               if (nfields > 0 && atoi(fields[0]) > 1)
734                                 *r_serverinfo |= SERVERINFO_SCHEMAV2;
735                               if (nfields > 1
736                                   && !ascii_strcasecmp (fields[1], "ntds"))
737                                 *r_serverinfo |= SERVERINFO_NTDS;
738                             }
739                           ldap_value_free (vals);
740                         }
741                     }
742
743                   /* From man ldap_search_s: "res parameter of
744                      ldap_search_ext_s() and ldap_search_s() should be
745                      freed with ldap_msgfree() regardless of return
746                      value of these functions.  */
747                   ldap_msgfree (si_res);
748                 }
749
750               ldap_value_free (context);
751             }
752         }
753       else
754         {
755           /* We don't have an answer yet, which means the server might
756              be a PGP.com keyserver. */
757           char **vals;
758           LDAPMessage *si_res = NULL;
759
760           char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
761
762           npth_unprotect ();
763           err = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
764                                "(objectClass=*)", attr2, 0, &si_res);
765           npth_protect ();
766           if (err == LDAP_SUCCESS)
767             {
768               /* For the PGP LDAP keyserver, this is always
769                * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
770                * in the future. */
771
772               vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
773               if (vals)
774                 {
775                   basedn = xtrystrdup (vals[0]);
776                   ldap_value_free (vals);
777                 }
778
779               vals = ldap_get_values (ldap_conn, si_res, "software");
780               if (vals)
781                 {
782                   if (opt.debug)
783                     log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]);
784                   ldap_value_free (vals);
785                 }
786
787               vals = ldap_get_values (ldap_conn, si_res, "version");
788               if (vals)
789                 {
790                   if (opt.debug)
791                     log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]);
792
793                   /* If the version is high enough, use the new
794                      pgpKeyV2 attribute.  This design is iffy at best,
795                      but it matches how PGP does it.  I figure the NAI
796                      folks assumed that there would never be an LDAP
797                      keyserver vendor with a different numbering
798                      scheme. */
799                   if (atoi (vals[0]) > 1)
800                     *r_serverinfo |= SERVERINFO_PGPKEYV2;
801
802                   ldap_value_free (vals);
803                 }
804             }
805
806           ldap_msgfree (si_res);
807         }
808
809       /* From man ldap_search_s: "res parameter of ldap_search_ext_s()
810          and ldap_search_s() should be freed with ldap_msgfree()
811          regardless of return value of these functions.  */
812       ldap_msgfree (res);
813     }
814
815  out:
816   if (!err && opt.debug)
817     {
818       log_debug ("ldap_conn: %p\n", ldap_conn);
819       log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP)
820                                        ? "LDAP" : "PGP.com keyserver") );
821       log_debug ("basedn: %s\n", basedn);
822       log_debug ("pgpkeyattr: %s\n",
823                  (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey");
824     }
825
826   if (err)
827     xfree (basedn);
828   else
829     {
830       if (basednp)
831         *basednp = basedn;
832       else
833         xfree (basedn);
834     }
835
836   if (err)
837     {
838       if (ldap_conn)
839         ldap_unbind (ldap_conn);
840     }
841   else
842     *ldap_connp = ldap_conn;
843
844   return err;
845 }
846
847 /* Extract keys from an LDAP reply and write them out to the output
848    stream OUTPUT in a format GnuPG can import (either the OpenPGP
849    binary format or armored format).  */
850 static void
851 extract_keys (estream_t output,
852               LDAP *ldap_conn, const char *certid, LDAPMessage *message)
853 {
854   char **vals;
855
856   es_fprintf (output, "INFO %s BEGIN\n", certid);
857   es_fprintf (output, "pub:%s:", certid);
858
859   /* Note: ldap_get_values returns a NULL terminated array of
860      strings.  */
861   vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
862   if (vals && vals[0])
863     {
864       if (strcmp (vals[0], "RSA") == 0)
865         es_fprintf  (output, "1");
866       else if (strcmp (vals[0],"DSS/DH") == 0)
867         es_fprintf (output, "17");
868       ldap_value_free (vals);
869     }
870
871   es_fprintf (output, ":");
872
873   vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
874   if (vals && vals[0])
875     {
876       int v = atoi (vals[0]);
877       if (v > 0)
878         es_fprintf (output, "%d", v);
879       ldap_value_free (vals);
880     }
881
882   es_fprintf (output, ":");
883
884   vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
885   if (vals && vals[0])
886     {
887       if (strlen (vals[0]) == 15)
888         es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
889       ldap_value_free (vals);
890     }
891
892   es_fprintf (output, ":");
893
894   vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
895   if (vals && vals[0])
896     {
897       if (strlen (vals[0]) == 15)
898         es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
899       ldap_value_free (vals);
900     }
901
902   es_fprintf (output, ":");
903
904   vals = ldap_get_values (ldap_conn, message, "pgprevoked");
905   if (vals && vals[0])
906     {
907       if (atoi (vals[0]) == 1)
908         es_fprintf (output, "r");
909       ldap_value_free (vals);
910     }
911
912   es_fprintf (output, "\n");
913
914   vals = ldap_get_values (ldap_conn, message, "pgpuserid");
915   if (vals && vals[0])
916     {
917       int i;
918       for (i = 0; vals[i]; i++)
919         es_fprintf (output, "uid:%s\n", vals[i]);
920       ldap_value_free (vals);
921     }
922
923   es_fprintf (output, "INFO %s END\n", certid);
924 }
925
926 /* Get the key described key the KEYSPEC string from the keyserver
927    identified by URI.  On success R_FP has an open stream to read the
928    data.  */
929 gpg_error_t
930 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
931              estream_t *r_fp)
932 {
933   gpg_error_t err = 0;
934   int ldap_err;
935   unsigned int serverinfo;
936   char *filter = NULL;
937   LDAP *ldap_conn = NULL;
938   char *basedn = NULL;
939   estream_t fp = NULL;
940   LDAPMessage *message = NULL;
941
942   (void) ctrl;
943
944   if (dirmngr_use_tor ())
945     {
946       /* For now we do not support LDAP over Tor.  */
947       log_error (_("LDAP access not possible due to Tor mode\n"));
948       return gpg_error (GPG_ERR_NOT_SUPPORTED);
949     }
950
951   /* Make sure we are talking to an OpenPGP LDAP server.  */
952   ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
953   if (ldap_err || !basedn)
954     {
955       if (ldap_err)
956         err = ldap_err_to_gpg_err (ldap_err);
957       else
958         err = gpg_error (GPG_ERR_GENERAL);
959       goto out;
960     }
961
962   /* Now that we have information about the server we can construct a
963    * query best suited for the capabilities of the server.  */
964   err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo);
965   if (err)
966     goto out;
967
968   if (opt.debug)
969     log_debug ("ks-ldap: using filter: %s\n", filter);
970
971   {
972     /* The ordering is significant.  Specifically, "pgpcertid" needs
973        to be the second item in the list, since everything after it
974        may be discarded we aren't in verbose mode. */
975     char *attrs[] =
976       {
977         "dummy",
978         "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
979         "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
980         NULL
981       };
982     /* 1 if we want just attribute types; 0 if we want both attribute
983      * types and values.  */
984     int attrsonly = 0;
985     int count;
986
987     /* Replace "dummy".  */
988     attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey";
989
990     npth_unprotect ();
991     ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
992                               filter, attrs, attrsonly, &message);
993     npth_protect ();
994     if (ldap_err)
995       {
996         err = ldap_err_to_gpg_err (ldap_err);
997
998         log_error ("ks-ldap: LDAP search error: %s\n",
999                    ldap_err2string (ldap_err));
1000         goto out;
1001       }
1002
1003     count = ldap_count_entries (ldap_conn, message);
1004     if (count < 1)
1005       {
1006         log_info ("ks-ldap: key %s not found on keyserver\n", keyspec);
1007
1008         if (count == -1)
1009           err = ldap_to_gpg_err (ldap_conn);
1010         else
1011           err = gpg_error (GPG_ERR_NO_DATA);
1012
1013         goto out;
1014       }
1015
1016     {
1017       /* There may be more than one unique result for a given keyID,
1018          so we should fetch them all (test this by fetching short key
1019          id 0xDEADBEEF). */
1020
1021       /* The set of entries that we've seen.  */
1022       strlist_t seen = NULL;
1023       LDAPMessage *each;
1024
1025       for (npth_unprotect (),
1026              each = ldap_first_entry (ldap_conn, message),
1027              npth_protect ();
1028            each;
1029            npth_unprotect (),
1030              each = ldap_next_entry (ldap_conn, each),
1031              npth_protect ())
1032         {
1033           char **vals;
1034           char **certid;
1035
1036           /* Use the long keyid to remove duplicates.  The LDAP
1037              server returns the same keyid more than once if there
1038              are multiple user IDs on the key.  Note that this does
1039              NOT mean that a keyid that exists multiple times on the
1040              keyserver will not be fetched.  It means that each KEY,
1041              no matter how many user IDs share its keyid, will be
1042              fetched only once.  If a keyid that belongs to more
1043              than one key is fetched, the server quite properly
1044              responds with all matching keys. -ds */
1045
1046           certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1047           if (certid && certid[0])
1048             {
1049               if (! strlist_find (seen, certid[0]))
1050                 {
1051                   /* It's not a duplicate, add it */
1052
1053                   add_to_strlist (&seen, certid[0]);
1054
1055                   if (! fp)
1056                     fp = es_fopenmem(0, "rw");
1057
1058                   extract_keys (fp, ldap_conn, certid[0], each);
1059
1060                   vals = ldap_get_values (ldap_conn, each, attrs[0]);
1061                   if (! vals)
1062                     {
1063                       err = ldap_to_gpg_err (ldap_conn);
1064                       log_error("ks-ldap: unable to retrieve key %s "
1065                                 "from keyserver\n", certid[0]);
1066                       goto out;
1067                     }
1068                   else
1069                     {
1070                       /* We should strip the new lines.  */
1071                       es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]);
1072                       es_fputs (vals[0], fp);
1073                       es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]);
1074
1075                       ldap_value_free (vals);
1076                     }
1077                 }
1078             }
1079
1080           ldap_value_free (certid);
1081         }
1082
1083       free_strlist (seen);
1084
1085       if (! fp)
1086         err = gpg_error (GPG_ERR_NO_DATA);
1087     }
1088   }
1089
1090  out:
1091   if (message)
1092     ldap_msgfree (message);
1093
1094   if (err)
1095     {
1096       if (fp)
1097         es_fclose (fp);
1098     }
1099   else
1100     {
1101       if (fp)
1102         es_fseek (fp, 0, SEEK_SET);
1103
1104       *r_fp = fp;
1105     }
1106
1107   xfree (basedn);
1108
1109   if (ldap_conn)
1110     ldap_unbind (ldap_conn);
1111
1112   xfree (filter);
1113
1114   return err;
1115 }
1116
1117
1118 /* Search the keyserver identified by URI for keys matching PATTERN.
1119    On success R_FP has an open stream to read the data.  */
1120 gpg_error_t
1121 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1122                 estream_t *r_fp)
1123 {
1124   gpg_error_t err;
1125   int ldap_err;
1126   unsigned int serverinfo;
1127   char *filter = NULL;
1128   LDAP *ldap_conn = NULL;
1129   char *basedn = NULL;
1130   estream_t fp = NULL;
1131
1132   (void) ctrl;
1133
1134   if (dirmngr_use_tor ())
1135     {
1136       /* For now we do not support LDAP over Tor.  */
1137       log_error (_("LDAP access not possible due to Tor mode\n"));
1138       return gpg_error (GPG_ERR_NOT_SUPPORTED);
1139     }
1140
1141   /* Make sure we are talking to an OpenPGP LDAP server.  */
1142   ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
1143   if (ldap_err || !basedn)
1144     {
1145       if (ldap_err)
1146         err = ldap_err_to_gpg_err (ldap_err);
1147       else
1148         err = GPG_ERR_GENERAL;
1149       goto out;
1150     }
1151
1152   /* Now that we have information about the server we can construct a
1153    * query best suited for the capabilities of the server.  */
1154   err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo);
1155   if (err)
1156     {
1157       log_error ("Bad search pattern: '%s'\n", pattern);
1158       goto out;
1159     }
1160
1161   /* Even if we have no results, we want to return a stream.  */
1162   fp = es_fopenmem(0, "rw");
1163   if (!fp)
1164     {
1165       err = gpg_error_from_syserror ();
1166       goto out;
1167     }
1168
1169   {
1170     char **vals;
1171     LDAPMessage *res, *each;
1172     int count = 0;
1173     strlist_t dupelist = NULL;
1174
1175     /* The maximum size of the search, including the optional stuff
1176        and the trailing \0 */
1177     char *attrs[] =
1178       {
1179         "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1180         "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1181         "pgpkeysize", "pgpkeytype", NULL
1182       };
1183
1184     if (opt.debug)
1185       log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1186
1187     npth_unprotect ();
1188     ldap_err = ldap_search_s (ldap_conn, basedn,
1189                               LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1190     npth_protect ();
1191
1192     xfree (filter);
1193     filter = NULL;
1194
1195     if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1196       {
1197         err = ldap_err_to_gpg_err (ldap_err);
1198
1199         log_error ("SEARCH %s FAILED %d\n", pattern, err);
1200         log_error ("ks-ldap: LDAP search error: %s\n",
1201                    ldap_err2string (err));
1202         goto out;
1203     }
1204
1205     /* The LDAP server doesn't return a real count of unique keys, so we
1206        can't use ldap_count_entries here. */
1207     for (npth_unprotect (),
1208            each = ldap_first_entry (ldap_conn, res),
1209            npth_protect ();
1210          each;
1211          npth_unprotect (),
1212            each = ldap_next_entry (ldap_conn, each),
1213            npth_protect ())
1214       {
1215         char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1216         if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1217           {
1218             add_to_strlist (&dupelist, certid[0]);
1219             count++;
1220           }
1221       }
1222
1223     if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1224       {
1225         if (count == 1)
1226           log_error ("ks-ldap: search results exceeded server limit."
1227                      "  First 1 result shown.\n");
1228         else
1229           log_error ("ks-ldap: search results exceeded server limit."
1230                      "  First %d results shown.\n", count);
1231       }
1232
1233     free_strlist (dupelist);
1234     dupelist = NULL;
1235
1236     if (count < 1)
1237       es_fputs ("info:1:0\n", fp);
1238     else
1239       {
1240         es_fprintf (fp, "info:1:%d\n", count);
1241
1242         for (each = ldap_first_entry (ldap_conn, res);
1243              each;
1244              each = ldap_next_entry (ldap_conn, each))
1245           {
1246             char **certid;
1247             LDAPMessage *uids;
1248
1249             certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1250             if (! certid || ! certid[0])
1251               continue;
1252
1253             /* Have we seen this certid before? */
1254             if (! strlist_find (dupelist, certid[0]))
1255               {
1256                 add_to_strlist (&dupelist, certid[0]);
1257
1258                 es_fprintf (fp, "pub:%s:",certid[0]);
1259
1260                 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1261                 if (vals)
1262                   {
1263                     /* The LDAP server doesn't exactly handle this
1264                        well. */
1265                     if (strcasecmp (vals[0], "RSA") == 0)
1266                       es_fputs ("1", fp);
1267                     else if (strcasecmp (vals[0], "DSS/DH") == 0)
1268                       es_fputs ("17", fp);
1269                     ldap_value_free (vals);
1270                   }
1271
1272                 es_fputc (':', fp);
1273
1274                 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1275                 if (vals)
1276                   {
1277                     /* Not sure why, but some keys are listed with a
1278                        key size of 0.  Treat that like an unknown. */
1279                     if (atoi (vals[0]) > 0)
1280                       es_fprintf (fp, "%d", atoi (vals[0]));
1281                     ldap_value_free (vals);
1282                   }
1283
1284                 es_fputc (':', fp);
1285
1286                 /* YYYYMMDDHHmmssZ */
1287
1288                 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1289                 if(vals && strlen (vals[0]) == 15)
1290                   {
1291                     es_fprintf (fp, "%u",
1292                                 (unsigned int) ldap2epochtime(vals[0]));
1293                     ldap_value_free (vals);
1294                   }
1295
1296                 es_fputc (':', fp);
1297
1298                 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1299                 if (vals && strlen (vals[0]) == 15)
1300                   {
1301                     es_fprintf (fp, "%u",
1302                                 (unsigned int) ldap2epochtime (vals[0]));
1303                     ldap_value_free (vals);
1304                   }
1305
1306                 es_fputc (':', fp);
1307
1308                 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1309                 if (vals)
1310                   {
1311                     if (atoi (vals[0]) == 1)
1312                       es_fprintf (fp, "r");
1313                     ldap_value_free (vals);
1314                   }
1315
1316                 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1317                 if (vals)
1318                   {
1319                     if (atoi (vals[0]) ==1)
1320                       es_fprintf (fp, "d");
1321                     ldap_value_free (vals);
1322                   }
1323
1324 #if 0
1325                 /* This is not yet specified in the keyserver
1326                    protocol, but may be someday. */
1327                 es_fputc (':', fp);
1328
1329                 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1330                 if(vals && strlen (vals[0]) == 15)
1331                   {
1332                     es_fprintf (fp, "%u",
1333                                 (unsigned int) ldap2epochtime (vals[0]));
1334                     ldap_value_free (vals);
1335                   }
1336 #endif
1337
1338                 es_fprintf (fp, "\n");
1339
1340                 /* Now print all the uids that have this certid */
1341                 for (uids = ldap_first_entry (ldap_conn, res);
1342                      uids;
1343                      uids = ldap_next_entry (ldap_conn, uids))
1344                   {
1345                     vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1346                     if (! vals)
1347                       continue;
1348
1349                     if (strcasecmp (certid[0], vals[0]) == 0)
1350                       {
1351                         char **uidvals;
1352
1353                         es_fprintf (fp, "uid:");
1354
1355                         uidvals = ldap_get_values (ldap_conn,
1356                                                    uids, "pgpuserid");
1357                         if (uidvals)
1358                           {
1359                             /* Need to escape any colons */
1360                             char *quoted = percent_escape (uidvals[0], NULL);
1361                             es_fputs (quoted, fp);
1362                             xfree (quoted);
1363                             ldap_value_free (uidvals);
1364                           }
1365
1366                         es_fprintf (fp, "\n");
1367                       }
1368
1369                     ldap_value_free(vals);
1370                   }
1371               }
1372
1373               ldap_value_free (certid);
1374           }
1375       }
1376
1377     ldap_msgfree (res);
1378     free_strlist (dupelist);
1379   }
1380
1381   if (opt.debug)
1382     log_debug ("SEARCH %s END\n", pattern);
1383
1384  out:
1385   if (err)
1386     {
1387       if (fp)
1388         es_fclose (fp);
1389     }
1390   else
1391     {
1392       /* Return the read stream.  */
1393       if (fp)
1394         es_fseek (fp, 0, SEEK_SET);
1395
1396       *r_fp = fp;
1397     }
1398
1399   xfree (basedn);
1400
1401   if (ldap_conn)
1402     ldap_unbind (ldap_conn);
1403
1404   xfree (filter);
1405
1406   return err;
1407 }
1408
1409
1410 \f
1411 /* A modlist describes a set of changes to an LDAP entry.  (An entry
1412    consists of 1 or more attributes.  Attributes are <name, value>
1413    pairs.  Note: an attribute may be multi-valued in which case
1414    multiple values are associated with a single name.)
1415
1416    A modlist is a NULL terminated array of struct LDAPMod's.
1417
1418    Thus, if we have:
1419
1420      LDAPMod **modlist;
1421
1422    Then:
1423
1424      modlist[i]
1425
1426    Is the ith modification.
1427
1428    Each LDAPMod describes a change to a single attribute.  Further,
1429    there is one modification for each attribute that we want to
1430    change.  The attribute's new value is stored in LDAPMod.mod_values.
1431    If the attribute is multi-valued, we still only use a single
1432    LDAPMod structure: mod_values is a NULL-terminated array of
1433    strings.  To delete an attribute from an entry, we set mod_values
1434    to NULL.
1435
1436    Thus, if:
1437
1438      modlist[i]->mod_values == NULL
1439
1440    then we remove the attribute.
1441
1442    (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1443    attribute in question exists or not.)
1444
1445    Note: this function does NOT copy or free ATTR.  It does copy
1446    VALUE.  */
1447 static void
1448 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1449 {
1450   LDAPMod **modlist = *modlistp;
1451
1452   LDAPMod **m;
1453   int nummods = 0;
1454
1455   /* Search modlist for the attribute we're playing with.  If modlist
1456      is NULL, then the list is empty.  Recall: modlist is a NULL
1457      terminated array.  */
1458   for (m = modlist; m && *m; m++, nummods ++)
1459     {
1460       /* The attribute is already on the list.  */
1461       char **ptr;
1462       int numvalues = 0;
1463
1464       if (strcasecmp ((*m)->mod_type, attr) != 0)
1465         continue;
1466
1467       /* We have this attribute already, so when the REPLACE happens,
1468          the server attributes will be replaced anyway. */
1469       if (! value)
1470         return;
1471
1472       /* Attributes can be multi-valued.  See if the value is already
1473          present.  mod_values is a NULL terminated array of pointers.
1474          Note: mod_values can be NULL.  */
1475       for (ptr = (*m)->mod_values; ptr && *ptr; ptr++)
1476         {
1477           if (strcmp (*ptr, value) == 0)
1478             /* Duplicate value, we're done.  */
1479             return;
1480           numvalues ++;
1481         }
1482
1483       /* Append the value.  */
1484       ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1485
1486       (*m)->mod_values = ptr;
1487       ptr[numvalues] = xstrdup (value);
1488
1489       ptr[numvalues + 1] = NULL;
1490
1491       return;
1492     }
1493
1494   /* We didn't find the attr, so make one and add it to the end */
1495
1496   /* Like attribute values, the list of attributes is NULL terminated
1497      array of pointers.  */
1498   modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1499
1500   *modlistp = modlist;
1501   modlist[nummods] = xmalloc (sizeof (LDAPMod));
1502
1503   modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1504   modlist[nummods]->mod_type = attr;
1505   if (value)
1506     {
1507       modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1508
1509       modlist[nummods]->mod_values[0] = xstrdup (value);
1510       modlist[nummods]->mod_values[1] = NULL;
1511     }
1512   else
1513     modlist[nummods]->mod_values = NULL;
1514
1515   modlist[nummods + 1] = NULL;
1516
1517   return;
1518 }
1519
1520 /* Look up the value of an attribute in the specified modlist.  If the
1521    attribute is not on the mod list, returns NULL.  The result is a
1522    NULL-terminated array of strings.  Don't change it.  */
1523 static char **
1524 modlist_lookup (LDAPMod **modlist, const char *attr)
1525 {
1526   LDAPMod **m;
1527   for (m = modlist; m && *m; m++)
1528     {
1529       if (strcasecmp ((*m)->mod_type, attr) != 0)
1530         continue;
1531
1532       return (*m)->mod_values;
1533     }
1534
1535   return NULL;
1536 }
1537
1538 /* Dump a modlist to a file.  This is useful for debugging.  */
1539 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1540   GPGRT_ATTR_USED;
1541
1542 static estream_t
1543 modlist_dump (LDAPMod **modlist, estream_t output)
1544 {
1545   LDAPMod **m;
1546
1547   int opened = 0;
1548
1549   if (! output)
1550     {
1551       output = es_fopenmem (0, "rw");
1552       if (!output)
1553         return NULL;
1554       opened = 1;
1555     }
1556
1557   for (m = modlist; m && *m; m++)
1558     {
1559       es_fprintf (output, "  %s:", (*m)->mod_type);
1560
1561       if (! (*m)->mod_values)
1562         es_fprintf(output, " delete.\n");
1563       else
1564         {
1565           char **ptr;
1566           int i;
1567
1568           int multi = 0;
1569           if ((*m)->mod_values[0] && (*m)->mod_values[1])
1570             /* Have at least 2.  */
1571             multi = 1;
1572
1573           if (multi)
1574             es_fprintf (output, "\n");
1575
1576           for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1577             {
1578               /* Assuming terminals are about 80 characters wide,
1579                  display at most about 10 lines of debugging
1580                  output.  If we do trim the buffer, append '...' to
1581                  the end.  */
1582               const int max_len = 10 * 70;
1583               size_t value_len = strlen (*ptr);
1584               int elide = value_len > max_len;
1585
1586               if (multi)
1587                 es_fprintf (output, "    %d. ", i);
1588               es_fprintf (output, "`%.*s", max_len, *ptr);
1589               if (elide)
1590                 es_fprintf (output, "...' (%zd bytes elided)",
1591                             value_len - max_len);
1592               else
1593                 es_fprintf (output, "'");
1594               es_fprintf (output, "\n");
1595             }
1596         }
1597     }
1598
1599   if (opened)
1600     es_fseek (output, 0, SEEK_SET);
1601
1602   return output;
1603 }
1604
1605 /* Free all of the memory allocated by the mod list.  This assumes
1606    that the attribute names don't have to be freed, but the attributes
1607    values do.  (Which is what modlist_add does.)  */
1608 static void
1609 modlist_free (LDAPMod **modlist)
1610 {
1611   LDAPMod **ml;
1612
1613   if (! modlist)
1614     return;
1615
1616   /* Unwind and free the whole modlist structure */
1617
1618   /* The modlist is a NULL terminated array of pointers.  */
1619   for (ml = modlist; *ml; ml++)
1620     {
1621       LDAPMod *mod = *ml;
1622       char **ptr;
1623
1624       /* The list of values is a NULL termianted array of pointers.
1625          If the list is NULL, there are no values.  */
1626
1627       if (mod->mod_values)
1628         {
1629           for (ptr = mod->mod_values; *ptr; ptr++)
1630             xfree (*ptr);
1631
1632           xfree (mod->mod_values);
1633         }
1634
1635       xfree (mod);
1636     }
1637   xfree (modlist);
1638 }
1639
1640 /* Append two onto the end of one.  Two is not freed, but its pointers
1641    are now part of one.  Make sure you don't free them both!
1642
1643    As long as you don't add anything to ONE, TWO is still valid.
1644    After that all bets are off.  */
1645 static void
1646 modlists_join (LDAPMod ***one, LDAPMod **two)
1647 {
1648   int i, one_count = 0, two_count = 0;
1649   LDAPMod **grow;
1650
1651   if (!*two)
1652     /* two is empty.  Nothing to do.  */
1653     return;
1654
1655   if (!*one)
1656     /* one is empty.  Just set it equal to *two.  */
1657     {
1658       *one = two;
1659       return;
1660     }
1661
1662   for (grow = *one; *grow; grow++)
1663     one_count ++;
1664
1665   for (grow = two; *grow; grow++)
1666     two_count ++;
1667
1668   grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1669
1670   for (i = 0; i < two_count; i++)
1671     grow[one_count + i] = two[i];
1672
1673   grow[one_count + i] = NULL;
1674
1675   *one = grow;
1676 }
1677
1678 /* Given a string, unescape C escapes.  In particular, \xXX.  This
1679    modifies the string in place.  */
1680 static void
1681 uncescape (char *str)
1682 {
1683   size_t r = 0;
1684   size_t w = 0;
1685
1686   char *first = strchr (str, '\\');
1687   if (! first)
1688     /* No backslashes => no escaping.  We're done.  */
1689     return;
1690
1691   /* Start at the first '\\'.  */
1692   r = w = (uintptr_t) first - (uintptr_t) str;
1693
1694   while (str[r])
1695     {
1696       /* XXX: What to do about bad escapes?
1697          XXX: hextobyte already checks the string thus the hexdigitp
1698          could be removed. */
1699       if (str[r] == '\\' && str[r + 1] == 'x'
1700           && str[r+2] && str[r+3]
1701           && hexdigitp (str + r + 2)
1702           && hexdigitp (str + r + 3))
1703         {
1704           int x = hextobyte (&str[r + 2]);
1705           assert (0 <= x && x <= 0xff);
1706
1707           str[w] = x;
1708
1709           /* We consumed 4 characters and wrote 1.  */
1710           r += 4;
1711           w ++;
1712         }
1713       else
1714         str[w ++] = str[r ++];
1715     }
1716
1717   str[w] = '\0';
1718 }
1719
1720 /* Given one line from an info block (`gpg --list-{keys,sigs}
1721    --with-colons KEYID'), pull it apart and fill in the modlist with
1722    the relevant (for the LDAP schema) attributes.  EXTRACT_STATE
1723    should initally be set to 0 by the caller.  SCHEMAV2 is set if the
1724    server supports the version 2 schema.  */
1725 static void
1726 extract_attributes (LDAPMod ***modlist, int *extract_state,
1727                     char *line, int schemav2)
1728 {
1729   int field_count;
1730   char **fields;
1731   char *keyid;
1732   int is_pub, is_sub, is_uid, is_sig;
1733
1734   /* Remove trailing whitespace */
1735   trim_trailing_spaces (line);
1736
1737   fields = strsplit (line, ':', '\0', &field_count);
1738   if (field_count == 1)
1739     /* We only have a single field.  There is definitely nothing to
1740        do.  */
1741     goto out;
1742
1743   if (field_count < 7)
1744     goto out;
1745
1746   is_pub = !ascii_strcasecmp ("pub", fields[0]);
1747   is_sub = !ascii_strcasecmp ("sub", fields[0]);
1748   is_uid = !ascii_strcasecmp ("uid", fields[0]);
1749   is_sig = !ascii_strcasecmp ("sig", fields[0]);
1750   if (!ascii_strcasecmp ("fpr", fields[0]))
1751     {
1752       /* Special treatment for a fingerprint.  */
1753       if (!(*extract_state & 1))
1754         goto out;  /* Stray fingerprint line - ignore.  */
1755       *extract_state &= ~1;
1756       if (field_count >= 10 && schemav2)
1757         {
1758           if ((*extract_state & 2))
1759             modlist_add (modlist, "gpgFingerprint", fields[9]);
1760           else
1761             modlist_add (modlist, "gpgSubFingerprint", fields[9]);
1762         }
1763       goto out;
1764     }
1765
1766   *extract_state &= ~(1|2);
1767   if (is_pub)
1768     *extract_state |= (1|2);
1769   else if (is_sub)
1770     *extract_state |= 1;
1771
1772   if (!is_pub && !is_sub && !is_uid && !is_sig)
1773     goto out; /* Not a relevant line.  */
1774
1775   keyid = fields[4];
1776
1777   if (is_uid && strlen (keyid) == 0)
1778     ; /* The uid record type can have an empty keyid.  */
1779   else if (strlen (keyid) == 16
1780            && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16)
1781     ; /* Otherwise, we expect exactly 16 hex characters.  */
1782   else
1783     {
1784       log_error ("malformed record!\n");
1785       goto out;
1786     }
1787
1788   if (is_pub)
1789     {
1790       int disabled = 0;
1791       int revoked = 0;
1792       char *flags;
1793       for (flags = fields[1]; *flags; flags ++)
1794         switch (*flags)
1795           {
1796           case 'r':
1797           case 'R':
1798             revoked = 1;
1799             break;
1800
1801           case 'd':
1802           case 'D':
1803             disabled = 1;
1804             break;
1805           }
1806
1807       /* Note: we always create the pgpDisabled and pgpRevoked
1808         attributes, regardless of whether the key is disabled/revoked
1809         or not.  This is because a very common search is like
1810         "(&(pgpUserID=*isabella*)(pgpDisabled=0))"  */
1811
1812       if (is_pub)
1813         {
1814           modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
1815           modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
1816         }
1817     }
1818
1819   if (is_pub || is_sub)
1820     {
1821       char padded[6];
1822       int val;
1823
1824       val = atoi (fields[2]);
1825       if (val < 99999 && val > 0)
1826         {
1827           /* We zero pad this on the left to make PGP happy. */
1828           snprintf (padded, sizeof padded, "%05u", val);
1829           modlist_add (modlist, "pgpKeySize", padded);
1830         }
1831     }
1832
1833   if (is_pub)
1834     {
1835       char *algo = fields[3];
1836       int val = atoi (algo);
1837       switch (val)
1838         {
1839         case 1:
1840           algo = "RSA";
1841           break;
1842
1843         case 17:
1844           algo = "DSS/DH";
1845           break;
1846
1847         default:
1848           algo = NULL;
1849           break;
1850         }
1851
1852       if (algo)
1853         modlist_add (modlist, "pgpKeyType", algo);
1854     }
1855
1856   if (is_pub || is_sub || is_sig)
1857     {
1858       if (is_pub)
1859         {
1860           modlist_add (modlist, "pgpCertID", keyid);    /* Long keyid(!) */
1861           modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid   */
1862         }
1863
1864       if (is_sub)
1865         modlist_add (modlist, "pgpSubKeyID", keyid);    /* Long keyid(!)  */
1866     }
1867
1868   if (is_pub)
1869     {
1870       char *create_time = fields[5];
1871
1872       if (strlen (create_time) == 0)
1873         create_time = NULL;
1874       else
1875         {
1876           char *create_time_orig = create_time;
1877           struct tm tm;
1878           time_t t;
1879           char *end;
1880
1881           memset (&tm, 0, sizeof (tm));
1882
1883           /* parse_timestamp handles both seconds fromt he epoch and
1884              ISO 8601 format.  We also need to handle YYYY-MM-DD
1885              format (as generated by gpg1 --with-colons --list-key).
1886              Check that first and then if it fails, then try
1887              parse_timestamp.  */
1888
1889           if (!isodate_human_to_tm (create_time, &tm))
1890             create_time = tm2ldaptime (&tm);
1891           else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1
1892                    && *end == '\0')
1893             {
1894
1895               if (!gnupg_gmtime (&t, &tm))
1896                 create_time = NULL;
1897               else
1898                 create_time = tm2ldaptime (&tm);
1899             }
1900           else
1901             create_time = NULL;
1902
1903           if (! create_time)
1904             /* Failed to parse string.  */
1905             log_error ("Failed to parse creation time ('%s')",
1906                        create_time_orig);
1907         }
1908
1909       if (create_time)
1910         {
1911           modlist_add (modlist, "pgpKeyCreateTime", create_time);
1912           xfree (create_time);
1913         }
1914     }
1915
1916   if (is_pub)
1917     {
1918       char *expire_time = fields[6];
1919
1920       if (strlen (expire_time) == 0)
1921         expire_time = NULL;
1922       else
1923         {
1924           char *expire_time_orig = expire_time;
1925           struct tm tm;
1926           time_t t;
1927           char *end;
1928
1929           memset (&tm, 0, sizeof (tm));
1930
1931           /* parse_timestamp handles both seconds fromt he epoch and
1932              ISO 8601 format.  We also need to handle YYYY-MM-DD
1933              format (as generated by gpg1 --with-colons --list-key).
1934              Check that first and then if it fails, then try
1935              parse_timestamp.  */
1936
1937           if (!isodate_human_to_tm (expire_time, &tm))
1938             expire_time = tm2ldaptime (&tm);
1939           else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1
1940                    && *end == '\0')
1941             {
1942               if (!gnupg_gmtime (&t, &tm))
1943                 expire_time = NULL;
1944               else
1945                 expire_time = tm2ldaptime (&tm);
1946             }
1947           else
1948             expire_time = NULL;
1949
1950           if (! expire_time)
1951             /* Failed to parse string.  */
1952             log_error ("Failed to parse creation time ('%s')",
1953                        expire_time_orig);
1954         }
1955
1956       if (expire_time)
1957         {
1958           modlist_add (modlist, "pgpKeyExpireTime", expire_time);
1959           xfree (expire_time);
1960         }
1961     }
1962
1963   if (is_uid && field_count >= 10)
1964     {
1965       char *uid = fields[9];
1966       char *mbox;
1967
1968       uncescape (uid);
1969       modlist_add (modlist, "pgpUserID", uid);
1970       if (schemav2 && (mbox = mailbox_from_userid (uid)))
1971         {
1972           modlist_add (modlist, "gpgMailbox", mbox);
1973           xfree (mbox);
1974         }
1975     }
1976
1977  out:
1978   xfree (fields);
1979 }
1980
1981 /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to
1982    the keyserver identified by URI.  See server.c:cmd_ks_put for the
1983    format of the data and metadata.  */
1984 gpg_error_t
1985 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
1986              void *data, size_t datalen,
1987              void *info, size_t infolen)
1988 {
1989   gpg_error_t err = 0;
1990   int ldap_err;
1991   unsigned int serverinfo;
1992   LDAP *ldap_conn = NULL;
1993   char *basedn = NULL;
1994   LDAPMod **modlist = NULL;
1995   LDAPMod **addlist = NULL;
1996   char *data_armored = NULL;
1997   int extract_state;
1998
1999   /* The last byte of the info block.  */
2000   const char *infoend = (const char *) info + infolen - 1;
2001
2002   /* Enable this code to dump the modlist to /tmp/modlist.txt.  */
2003 #if 0
2004 # warning Disable debug code before checking in.
2005   const int dump_modlist = 1;
2006 #else
2007   const int dump_modlist = 0;
2008 #endif
2009   estream_t dump = NULL;
2010
2011   /* Elide a warning.  */
2012   (void) ctrl;
2013
2014   if (dirmngr_use_tor ())
2015     {
2016       /* For now we do not support LDAP over Tor.  */
2017       log_error (_("LDAP access not possible due to Tor mode\n"));
2018       return gpg_error (GPG_ERR_NOT_SUPPORTED);
2019     }
2020
2021   ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
2022   if (ldap_err || !basedn)
2023     {
2024       if (ldap_err)
2025         err = ldap_err_to_gpg_err (ldap_err);
2026       else
2027         err = GPG_ERR_GENERAL;
2028       goto out;
2029     }
2030
2031   if (!(serverinfo & SERVERINFO_REALLDAP))
2032     {
2033       /* We appear to have a PGP.com Keyserver, which can unpack the
2034        * key on its own (not just a dump LDAP server).  This will
2035        * rarely be the case these days.  */
2036       LDAPMod mod;
2037       LDAPMod *attrs[2];
2038       char *key[2];
2039       char *dn;
2040
2041       key[0] = data;
2042       key[1] = NULL;
2043       memset (&mod, 0, sizeof (mod));
2044       mod.mod_op = LDAP_MOD_ADD;
2045       mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey";
2046       mod.mod_values = key;
2047       attrs[0] = &mod;
2048       attrs[1] = NULL;
2049
2050       dn = xtryasprintf ("pgpCertid=virtual,%s", basedn);
2051       if (!dn)
2052         {
2053           err = gpg_error_from_syserror ();
2054           goto out;
2055         }
2056       ldap_err = ldap_add_s (ldap_conn, dn, attrs);
2057       xfree (dn);
2058
2059       if (ldap_err != LDAP_SUCCESS)
2060         {
2061           err = ldap_err_to_gpg_err (err);
2062           goto out;
2063         }
2064
2065       goto out;
2066     }
2067
2068   modlist = xtrymalloc (sizeof (LDAPMod *));
2069   if (!modlist)
2070     {
2071       err = gpg_error_from_syserror ();
2072       goto out;
2073     }
2074   *modlist = NULL;
2075
2076   if (dump_modlist)
2077     {
2078       dump = es_fopen("/tmp/modlist.txt", "w");
2079       if (! dump)
2080         log_error ("Failed to open /tmp/modlist.txt: %s\n",
2081                    strerror (errno));
2082
2083       if (dump)
2084         {
2085           es_fprintf(dump, "data (%zd bytes)\n", datalen);
2086           es_fprintf(dump, "info (%zd bytes): '\n", infolen);
2087           es_fwrite(info, infolen, 1, dump);
2088           es_fprintf(dump, "'\n");
2089         }
2090     }
2091
2092   /* Start by nulling out all attributes.  We try and do a modify
2093      operation first, so this ensures that we don't leave old
2094      attributes lying around. */
2095   modlist_add (&modlist, "pgpDisabled", NULL);
2096   modlist_add (&modlist, "pgpKeyID", NULL);
2097   modlist_add (&modlist, "pgpKeyType", NULL);
2098   modlist_add (&modlist, "pgpUserID", NULL);
2099   modlist_add (&modlist, "pgpKeyCreateTime", NULL);
2100   modlist_add (&modlist, "pgpRevoked", NULL);
2101   modlist_add (&modlist, "pgpSubKeyID", NULL);
2102   modlist_add (&modlist, "pgpKeySize", NULL);
2103   modlist_add (&modlist, "pgpKeyExpireTime", NULL);
2104   modlist_add (&modlist, "pgpCertID", NULL);
2105   if ((serverinfo & SERVERINFO_SCHEMAV2))
2106     {
2107       modlist_add (&modlist, "gpgFingerprint", NULL);
2108       modlist_add (&modlist, "gpgSubFingerprint", NULL);
2109       modlist_add (&modlist, "gpgMailbox", NULL);
2110     }
2111
2112   /* Assemble the INFO stuff into LDAP attributes */
2113   extract_state = 0;
2114   while (infolen > 0)
2115     {
2116       char *temp = NULL;
2117
2118       char *newline = memchr (info, '\n', infolen);
2119       if (! newline)
2120         /* The last line is not \n terminated!  Make a copy so we can
2121            add a NUL terminator.  */
2122         {
2123           temp = xmalloc (infolen + 1);
2124           memcpy (temp, info, infolen);
2125           info = temp;
2126           newline = (char *) info + infolen;
2127         }
2128
2129       *newline = '\0';
2130
2131       extract_attributes (&addlist, &extract_state, info,
2132                           (serverinfo & SERVERINFO_SCHEMAV2));
2133
2134       infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2135       info = newline + 1;
2136
2137       /* Sanity check.  */
2138       if (! temp)
2139         log_assert ((char *) info + infolen - 1 == infoend);
2140       else
2141         {
2142           log_assert (infolen == -1);
2143           xfree (temp);
2144         }
2145     }
2146
2147   modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2148
2149   err = armor_data (&data_armored, data, datalen);
2150   if (err)
2151     goto out;
2152
2153   modlist_add (&addlist,
2154                (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey",
2155                data_armored);
2156
2157   /* Now append addlist onto modlist.  */
2158   modlists_join (&modlist, addlist);
2159
2160   if (dump)
2161     {
2162       estream_t input = modlist_dump (modlist, NULL);
2163       if (input)
2164         {
2165           copy_stream (input, dump);
2166           es_fclose (input);
2167         }
2168     }
2169
2170   /* Going on the assumption that modify operations are more frequent
2171      than adds, we try a modify first.  If it's not there, we just
2172      turn around and send an add command for the same key.  Otherwise,
2173      the modify brings the server copy into compliance with our copy.
2174      Note that unlike the LDAP keyserver (and really, any other
2175      keyserver) this does NOT merge signatures, but replaces the whole
2176      key.  This should make some people very happy. */
2177   {
2178     char **attrval;
2179     char *dn;
2180
2181     if ((serverinfo & SERVERINFO_NTDS))
2182       {
2183         /* The modern way using a CN RDN with the fingerprint.  This
2184          * has the advantage that we won't have duplicate 64 bit
2185          * keyids in the store.  In particular NTDS requires the
2186          * DN to be unique.  */
2187         attrval = modlist_lookup (addlist, "gpgFingerprint");
2188         /* We should have exactly one value.  */
2189         if (!attrval || !(attrval[0] && !attrval[1]))
2190           {
2191             log_error ("ks-ldap: bad gpgFingerprint provided\n");
2192             err = GPG_ERR_GENERAL;
2193             goto out;
2194           }
2195         dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn);
2196       }
2197     else  /* The old style way.  */
2198       {
2199         attrval = modlist_lookup (addlist, "pgpCertID");
2200         /* We should have exactly one value.  */
2201         if (!attrval || !(attrval[0] && !attrval[1]))
2202           {
2203             log_error ("ks-ldap: bad pgpCertID provided\n");
2204             err = GPG_ERR_GENERAL;
2205             goto out;
2206           }
2207         dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn);
2208       }
2209     if (!dn)
2210       {
2211         err = gpg_error_from_syserror ();
2212         goto out;
2213       }
2214     if (opt.debug)
2215       log_debug ("ks-ldap: using DN: %s\n", dn);
2216
2217     npth_unprotect ();
2218     err = ldap_modify_s (ldap_conn, dn, modlist);
2219     if (err == LDAP_NO_SUCH_OBJECT)
2220       err = ldap_add_s (ldap_conn, dn, addlist);
2221     npth_protect ();
2222
2223     xfree (dn);
2224
2225     if (err != LDAP_SUCCESS)
2226       {
2227         log_error ("ks-ldap: error adding key to keyserver: %s\n",
2228                    ldap_err2string (err));
2229         err = ldap_err_to_gpg_err (err);
2230       }
2231   }
2232
2233  out:
2234   if (dump)
2235     es_fclose (dump);
2236
2237   if (ldap_conn)
2238     ldap_unbind (ldap_conn);
2239
2240   xfree (basedn);
2241
2242   modlist_free (modlist);
2243   xfree (addlist);
2244
2245   xfree (data_armored);
2246
2247   return err;
2248 }