Imported Upstream version 2.3.0
[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 (uri->is_ldap)
323     err = ks_print_help (ctrl, data);
324   else
325     err = 0;
326
327   return err;
328 }
329
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_FPR:
408       if ((serverinfo & SERVERINFO_SCHEMAV2))
409         {
410           freeme = bin2hex (desc.u.fpr, desc.fprlen, NULL);
411           if (!freeme)
412             return gpg_error_from_syserror ();
413           f = xasprintf ("(|(gpgFingerprint=%s)(gpgSubFingerprint=%s))",
414                          freeme, freeme);
415           /* FIXME: For an exact search and in case of a match on
416            * gpgSubFingerprint we need to check that there is only one
417            * matching value.  */
418         }
419       break;
420
421     case KEYDB_SEARCH_MODE_ISSUER:
422     case KEYDB_SEARCH_MODE_ISSUER_SN:
423     case KEYDB_SEARCH_MODE_SN:
424     case KEYDB_SEARCH_MODE_SUBJECT:
425     case KEYDB_SEARCH_MODE_KEYGRIP:
426     case KEYDB_SEARCH_MODE_WORDS:
427     case KEYDB_SEARCH_MODE_FIRST:
428     case KEYDB_SEARCH_MODE_NEXT:
429     default:
430       break;
431     }
432
433   xfree (freeme);
434
435   if (! f)
436     {
437       log_error ("Unsupported search mode.\n");
438       return gpg_error (GPG_ERR_NOT_SUPPORTED);
439     }
440
441   *filter = f;
442
443   return 0;
444 }
445
446
447 \f
448 /* Connect to an LDAP server and interrogate it.
449
450      - uri describes the server to connect to and various options
451        including whether to use TLS and the username and password (see
452        ldap_parse_uri for a description of the various fields).
453
454    This function returns:
455
456      - The ldap connection handle in *LDAP_CONNP.
457
458      - The base DN for the PGP key space by querying the
459        pgpBaseKeySpaceDN attribute (This is normally
460        'ou=PGP Keys,dc=EXAMPLE,dc=ORG').
461
462      - The attribute to lookup to find the pgp key.  This is either
463        'pgpKey' or 'pgpKeyV2'.
464
465      - Whether this is a real ldap server.  (It's unclear what this
466        exactly means.)
467
468    The values are returned in the passed variables.  If you pass NULL,
469    then the value won't be returned.  It is the caller's
470    responsibility to release *LDAP_CONNP with ldap_unbind and xfree
471    *BASEDNP.
472
473    If this function successfully interrogated the server, it returns
474    0.  If there was an LDAP error, it returns the LDAP error code.  If
475    an error occurred, *basednp, etc., are undefined (and don't need to
476    be freed.)
477
478    R_SERVERINFO receives information about the server.
479
480    If no LDAP error occurred, you still need to check that *basednp is
481    valid.  If it is NULL, then the server does not appear to be an
482    OpenPGP Keyserver.  */
483 static int
484 my_ldap_connect (parsed_uri_t uri, LDAP **ldap_connp,
485                  char **basednp, unsigned int *r_serverinfo)
486 {
487   int err = 0;
488   LDAP *ldap_conn = NULL;
489   char *user = uri->auth;
490   struct uri_tuple_s *password_param;
491   char *password;
492   char *basedn = NULL;
493
494   *r_serverinfo = 0;
495
496   password_param = uri_query_lookup (uri, "password");
497   password = password_param ? password_param->value : NULL;
498
499   if (opt.debug)
500     log_debug ("my_ldap_connect(%s:%d/%s????%s%s%s%s%s%s)\n",
501                uri->host, uri->port,
502                uri->path ? uri->path : "",
503                uri->auth ? "bindname=" : "",
504                uri->auth ? uri->auth : "",
505                uri->auth && password ? "," : "",
506                password ? "password=" : "",
507                password ? ">not shown<": "",
508                uri->ad_current? " auth=>current_user<":"");
509
510   /* If the uri specifies a secure connection and we don't support
511      TLS, then fail; don't silently revert to an insecure
512      connection.  */
513   if (uri->use_tls)
514     {
515 #ifndef HAVE_LDAP_START_TLS_S
516       log_error ("Can't use LDAP to connect to the server: no TLS support.");
517       err = GPG_ERR_LDAP_NOT_SUPPORTED;
518       goto out;
519 #endif
520     }
521
522   ldap_conn = ldap_init (uri->host, uri->port);
523   if (!ldap_conn)
524     {
525       err = gpg_err_code_from_syserror ();
526       log_error ("error initializing LDAP for (%s://%s:%d)\n",
527                  uri->scheme, uri->host, uri->port);
528       goto out;
529     }
530
531 #ifdef HAVE_LDAP_SET_OPTION
532   {
533     int ver = LDAP_VERSION3;
534
535     err = ldap_set_option (ldap_conn, LDAP_OPT_PROTOCOL_VERSION, &ver);
536     if (err != LDAP_SUCCESS)
537       {
538         log_error ("ks-ldap: unable to go to LDAP 3: %s\n",
539                    ldap_err2string (err));
540         goto out;
541       }
542   }
543 #endif
544
545   /* XXX: It would be nice to have an option to provide the server's
546      certificate.  */
547 #if 0
548 #if defined(LDAP_OPT_X_TLS_CACERTFILE) && defined(HAVE_LDAP_SET_OPTION)
549   err = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, ca_cert_file);
550   if (err)
551     {
552       log_error ("unable to set ca-cert-file to '%s': %s\n",
553                  ca_cert_file, ldap_err2string (err));
554       goto out;
555     }
556 #endif /* LDAP_OPT_X_TLS_CACERTFILE && HAVE_LDAP_SET_OPTION */
557 #endif
558
559 #ifdef HAVE_LDAP_START_TLS_S
560   if (uri->use_tls)
561     {
562       /* XXX: We need an option to determine whether to abort if the
563          certificate is bad or not.  Right now we conservatively
564          default to checking the certificate and aborting.  */
565 #ifndef HAVE_W32_SYSTEM
566       int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
567
568       err = ldap_set_option (ldap_conn,
569                              LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
570       if (err)
571         {
572           log_error ("error setting TLS option on LDAP connection\n");
573           goto out;
574         }
575 #else
576       /* On Windows, the certificates are checked by default.  If the
577          option to disable checking mentioned above is ever
578          implemented, the way to do that on Windows is to install a
579          callback routine using ldap_set_option (..,
580          LDAP_OPT_SERVER_CERTIFICATE, ..); */
581 #endif
582
583       npth_unprotect ();
584       err = ldap_start_tls_s (ldap_conn,
585 #ifdef HAVE_W32_SYSTEM
586                               /* ServerReturnValue, result */
587                               NULL, NULL,
588 #endif
589                               /* ServerControls, ClientControls */
590                               NULL, NULL);
591       npth_protect ();
592       if (err)
593         {
594           log_error ("error connecting to LDAP server with TLS\n");
595           goto out;
596         }
597     }
598 #endif
599
600   if (uri->ad_current)
601     {
602       if (opt.debug)
603         log_debug ("LDAP bind to current user via AD\n");
604 #ifdef HAVE_W32_SYSTEM
605       npth_unprotect ();
606       err = ldap_bind_s (ldap_conn, NULL, NULL, LDAP_AUTH_NEGOTIATE);
607       npth_protect ();
608       if (err != LDAP_SUCCESS)
609         {
610           log_error ("error binding to LDAP via AD: %s\n",
611                      ldap_err2string (err));
612           goto out;
613         }
614 #else
615       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
616       goto out;
617 #endif
618     }
619   else if (uri->auth)
620     {
621       if (opt.debug)
622         log_debug ("LDAP bind to %s, password %s\n",
623                    user, password ? ">not shown<" : ">none<");
624
625       npth_unprotect ();
626       err = ldap_simple_bind_s (ldap_conn, user, password);
627       npth_protect ();
628       if (err != LDAP_SUCCESS)
629         {
630           log_error ("error binding to LDAP: %s\n", ldap_err2string (err));
631           goto out;
632         }
633     }
634   else
635     {
636       /* By default we don't bind as there is usually no need to.  */
637     }
638
639   if (uri->path && *uri->path)
640     {
641       /* User specified base DN.  */
642       basedn = xstrdup (uri->path);
643
644       /* If the user specifies a base DN, then we know the server is a
645        * real LDAP server.  */
646       *r_serverinfo |= SERVERINFO_REALLDAP;
647     }
648   else
649     { /* Look for namingContexts.  */
650       LDAPMessage *res = NULL;
651       char *attr[] = { "namingContexts", NULL };
652
653       npth_unprotect ();
654       err = ldap_search_s (ldap_conn, "", LDAP_SCOPE_BASE,
655                            "(objectClass=*)", attr, 0, &res);
656       npth_protect ();
657
658       if (err == LDAP_SUCCESS)
659         {
660           char **context;
661
662           npth_unprotect ();
663           context = ldap_get_values (ldap_conn, res, "namingContexts");
664           npth_protect ();
665           if (context)
666             {
667               /* We found some, so try each namingContext as the
668                * search base and look for pgpBaseKeySpaceDN.  Because
669                * we found this, we know we're talking to a regular-ish
670                * LDAP server and not an LDAP keyserver.  */
671               int i;
672               char *attr2[] =
673                 { "pgpBaseKeySpaceDN", "pgpVersion", "pgpSoftware", NULL };
674
675               *r_serverinfo |= SERVERINFO_REALLDAP;
676
677               for (i = 0; context[i] && ! basedn; i++)
678                 {
679                   char **vals;
680                   LDAPMessage *si_res;
681                   int is_gnupg = 0;
682
683                   {
684                     char *object = xasprintf ("cn=pgpServerInfo,%s",
685                                               context[i]);
686                     npth_unprotect ();
687                     err = ldap_search_s (ldap_conn, object, LDAP_SCOPE_BASE,
688                                          "(objectClass=*)", attr2, 0, &si_res);
689                     npth_protect ();
690                     xfree (object);
691                   }
692
693                   if (err == LDAP_SUCCESS)
694                     {
695                       vals = ldap_get_values (ldap_conn, si_res,
696                                               "pgpBaseKeySpaceDN");
697                       if (vals)
698                         {
699                           basedn = xtrystrdup (vals[0]);
700                           ldap_value_free (vals);
701                         }
702
703                       vals = ldap_get_values (ldap_conn, si_res,
704                                               "pgpSoftware");
705                       if (vals)
706                         {
707                           if (opt.debug)
708                             log_debug ("Server: \t%s\n", vals[0]);
709                           if (!ascii_strcasecmp (vals[0], "GnuPG"))
710                             is_gnupg = 1;
711                           ldap_value_free (vals);
712                         }
713
714                       vals = ldap_get_values (ldap_conn, si_res,
715                                               "pgpVersion");
716                       if (vals)
717                         {
718                           if (opt.debug)
719                             log_debug ("Version:\t%s\n", vals[0]);
720                           if (is_gnupg)
721                             {
722                               const char *fields[2];
723                               int nfields;
724                               nfields = split_fields (vals[0],
725                                                       fields, DIM(fields));
726                               if (nfields > 0 && atoi(fields[0]) > 1)
727                                 *r_serverinfo |= SERVERINFO_SCHEMAV2;
728                               if (nfields > 1
729                                   && !ascii_strcasecmp (fields[1], "ntds"))
730                                 *r_serverinfo |= SERVERINFO_NTDS;
731                             }
732                           ldap_value_free (vals);
733                         }
734                     }
735
736                   /* From man ldap_search_s: "res parameter of
737                      ldap_search_ext_s() and ldap_search_s() should be
738                      freed with ldap_msgfree() regardless of return
739                      value of these functions.  */
740                   ldap_msgfree (si_res);
741                 }
742
743               ldap_value_free (context);
744             }
745         }
746       else
747         {
748           /* We don't have an answer yet, which means the server might
749              be a PGP.com keyserver. */
750           char **vals;
751           LDAPMessage *si_res = NULL;
752
753           char *attr2[] = { "pgpBaseKeySpaceDN", "version", "software", NULL };
754
755           npth_unprotect ();
756           err = ldap_search_s (ldap_conn, "cn=pgpServerInfo", LDAP_SCOPE_BASE,
757                                "(objectClass=*)", attr2, 0, &si_res);
758           npth_protect ();
759           if (err == LDAP_SUCCESS)
760             {
761               /* For the PGP LDAP keyserver, this is always
762                * "OU=ACTIVE,O=PGP KEYSPACE,C=US", but it might not be
763                * in the future. */
764
765               vals = ldap_get_values (ldap_conn, si_res, "baseKeySpaceDN");
766               if (vals)
767                 {
768                   basedn = xtrystrdup (vals[0]);
769                   ldap_value_free (vals);
770                 }
771
772               vals = ldap_get_values (ldap_conn, si_res, "software");
773               if (vals)
774                 {
775                   if (opt.debug)
776                     log_debug ("ks-ldap: PGP Server: \t%s\n", vals[0]);
777                   ldap_value_free (vals);
778                 }
779
780               vals = ldap_get_values (ldap_conn, si_res, "version");
781               if (vals)
782                 {
783                   if (opt.debug)
784                     log_debug ("ks-ldap: PGP Server Version:\t%s\n", vals[0]);
785
786                   /* If the version is high enough, use the new
787                      pgpKeyV2 attribute.  This design is iffy at best,
788                      but it matches how PGP does it.  I figure the NAI
789                      folks assumed that there would never be an LDAP
790                      keyserver vendor with a different numbering
791                      scheme. */
792                   if (atoi (vals[0]) > 1)
793                     *r_serverinfo |= SERVERINFO_PGPKEYV2;
794
795                   ldap_value_free (vals);
796                 }
797             }
798
799           ldap_msgfree (si_res);
800         }
801
802       /* From man ldap_search_s: "res parameter of ldap_search_ext_s()
803          and ldap_search_s() should be freed with ldap_msgfree()
804          regardless of return value of these functions.  */
805       ldap_msgfree (res);
806     }
807
808  out:
809   if (!err && opt.debug)
810     {
811       log_debug ("ldap_conn: %p\n", ldap_conn);
812       log_debug ("server_type: %s\n", ((*r_serverinfo & SERVERINFO_REALLDAP)
813                                        ? "LDAP" : "PGP.com keyserver") );
814       log_debug ("basedn: %s\n", basedn);
815       log_debug ("pgpkeyattr: %s\n",
816                  (*r_serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey");
817     }
818
819   if (err)
820     xfree (basedn);
821   else
822     {
823       if (basednp)
824         *basednp = basedn;
825       else
826         xfree (basedn);
827     }
828
829   if (err)
830     {
831       if (ldap_conn)
832         ldap_unbind (ldap_conn);
833     }
834   else
835     *ldap_connp = ldap_conn;
836
837   return err;
838 }
839
840 /* Extract keys from an LDAP reply and write them out to the output
841    stream OUTPUT in a format GnuPG can import (either the OpenPGP
842    binary format or armored format).  */
843 static void
844 extract_keys (estream_t output,
845               LDAP *ldap_conn, const char *certid, LDAPMessage *message)
846 {
847   char **vals;
848
849   es_fprintf (output, "INFO %s BEGIN\n", certid);
850   es_fprintf (output, "pub:%s:", certid);
851
852   /* Note: ldap_get_values returns a NULL terminated array of
853      strings.  */
854   vals = ldap_get_values (ldap_conn, message, "pgpkeytype");
855   if (vals && vals[0])
856     {
857       if (strcmp (vals[0], "RSA") == 0)
858         es_fprintf  (output, "1");
859       else if (strcmp (vals[0],"DSS/DH") == 0)
860         es_fprintf (output, "17");
861       ldap_value_free (vals);
862     }
863
864   es_fprintf (output, ":");
865
866   vals = ldap_get_values (ldap_conn, message, "pgpkeysize");
867   if (vals && vals[0])
868     {
869       int v = atoi (vals[0]);
870       if (v > 0)
871         es_fprintf (output, "%d", v);
872       ldap_value_free (vals);
873     }
874
875   es_fprintf (output, ":");
876
877   vals = ldap_get_values (ldap_conn, message, "pgpkeycreatetime");
878   if (vals && vals[0])
879     {
880       if (strlen (vals[0]) == 15)
881         es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
882       ldap_value_free (vals);
883     }
884
885   es_fprintf (output, ":");
886
887   vals = ldap_get_values (ldap_conn, message, "pgpkeyexpiretime");
888   if (vals && vals[0])
889     {
890       if (strlen (vals[0]) == 15)
891         es_fprintf (output, "%u", (unsigned int) ldap2epochtime (vals[0]));
892       ldap_value_free (vals);
893     }
894
895   es_fprintf (output, ":");
896
897   vals = ldap_get_values (ldap_conn, message, "pgprevoked");
898   if (vals && vals[0])
899     {
900       if (atoi (vals[0]) == 1)
901         es_fprintf (output, "r");
902       ldap_value_free (vals);
903     }
904
905   es_fprintf (output, "\n");
906
907   vals = ldap_get_values (ldap_conn, message, "pgpuserid");
908   if (vals && vals[0])
909     {
910       int i;
911       for (i = 0; vals[i]; i++)
912         es_fprintf (output, "uid:%s\n", vals[i]);
913       ldap_value_free (vals);
914     }
915
916   es_fprintf (output, "INFO %s END\n", certid);
917 }
918
919 /* Get the key described key the KEYSPEC string from the keyserver
920    identified by URI.  On success R_FP has an open stream to read the
921    data.  */
922 gpg_error_t
923 ks_ldap_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec,
924              estream_t *r_fp)
925 {
926   gpg_error_t err = 0;
927   int ldap_err;
928   unsigned int serverinfo;
929   char *filter = NULL;
930   LDAP *ldap_conn = NULL;
931   char *basedn = NULL;
932   estream_t fp = NULL;
933   LDAPMessage *message = NULL;
934
935   (void) ctrl;
936
937   if (dirmngr_use_tor ())
938     {
939       /* For now we do not support LDAP over Tor.  */
940       log_error (_("LDAP access not possible due to Tor mode\n"));
941       return gpg_error (GPG_ERR_NOT_SUPPORTED);
942     }
943
944   /* Make sure we are talking to an OpenPGP LDAP server.  */
945   ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
946   if (ldap_err || !basedn)
947     {
948       if (ldap_err)
949         err = ldap_err_to_gpg_err (ldap_err);
950       else
951         err = gpg_error (GPG_ERR_GENERAL);
952       goto out;
953     }
954
955   /* Now that we have information about the server we can construct a
956    * query best suited for the capabilities of the server.  */
957   err = keyspec_to_ldap_filter (keyspec, &filter, 1, serverinfo);
958   if (err)
959     goto out;
960
961   if (opt.debug)
962     log_debug ("ks-ldap: using filter: %s\n", filter);
963
964   {
965     /* The ordering is significant.  Specifically, "pgpcertid" needs
966        to be the second item in the list, since everything after it
967        may be discarded we aren't in verbose mode. */
968     char *attrs[] =
969       {
970         "dummy",
971         "pgpcertid", "pgpuserid", "pgpkeyid", "pgprevoked", "pgpdisabled",
972         "pgpkeycreatetime", "modifytimestamp", "pgpkeysize", "pgpkeytype",
973         NULL
974       };
975     /* 1 if we want just attribute types; 0 if we want both attribute
976      * types and values.  */
977     int attrsonly = 0;
978     int count;
979
980     /* Replace "dummy".  */
981     attrs[0] = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2" : "pgpKey";
982
983     npth_unprotect ();
984     ldap_err = ldap_search_s (ldap_conn, basedn, LDAP_SCOPE_SUBTREE,
985                               filter, attrs, attrsonly, &message);
986     npth_protect ();
987     if (ldap_err)
988       {
989         err = ldap_err_to_gpg_err (ldap_err);
990
991         log_error ("ks-ldap: LDAP search error: %s\n",
992                    ldap_err2string (ldap_err));
993         goto out;
994       }
995
996     count = ldap_count_entries (ldap_conn, message);
997     if (count < 1)
998       {
999         log_info ("ks-ldap: key %s not found on keyserver\n", keyspec);
1000
1001         if (count == -1)
1002           err = ldap_to_gpg_err (ldap_conn);
1003         else
1004           err = gpg_error (GPG_ERR_NO_DATA);
1005
1006         goto out;
1007       }
1008
1009     {
1010       /* There may be more than one unique result for a given keyID,
1011          so we should fetch them all (test this by fetching short key
1012          id 0xDEADBEEF). */
1013
1014       /* The set of entries that we've seen.  */
1015       strlist_t seen = NULL;
1016       LDAPMessage *each;
1017
1018       for (npth_unprotect (),
1019              each = ldap_first_entry (ldap_conn, message),
1020              npth_protect ();
1021            each;
1022            npth_unprotect (),
1023              each = ldap_next_entry (ldap_conn, each),
1024              npth_protect ())
1025         {
1026           char **vals;
1027           char **certid;
1028
1029           /* Use the long keyid to remove duplicates.  The LDAP
1030              server returns the same keyid more than once if there
1031              are multiple user IDs on the key.  Note that this does
1032              NOT mean that a keyid that exists multiple times on the
1033              keyserver will not be fetched.  It means that each KEY,
1034              no matter how many user IDs share its keyid, will be
1035              fetched only once.  If a keyid that belongs to more
1036              than one key is fetched, the server quite properly
1037              responds with all matching keys. -ds */
1038
1039           certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1040           if (certid && certid[0])
1041             {
1042               if (! strlist_find (seen, certid[0]))
1043                 {
1044                   /* It's not a duplicate, add it */
1045
1046                   add_to_strlist (&seen, certid[0]);
1047
1048                   if (! fp)
1049                     fp = es_fopenmem(0, "rw");
1050
1051                   extract_keys (fp, ldap_conn, certid[0], each);
1052
1053                   vals = ldap_get_values (ldap_conn, each, attrs[0]);
1054                   if (! vals)
1055                     {
1056                       err = ldap_to_gpg_err (ldap_conn);
1057                       log_error("ks-ldap: unable to retrieve key %s "
1058                                 "from keyserver\n", certid[0]);
1059                       goto out;
1060                     }
1061                   else
1062                     {
1063                       /* We should strip the new lines.  */
1064                       es_fprintf (fp, "KEY 0x%s BEGIN\n", certid[0]);
1065                       es_fputs (vals[0], fp);
1066                       es_fprintf (fp, "\nKEY 0x%s END\n", certid[0]);
1067
1068                       ldap_value_free (vals);
1069                     }
1070                 }
1071             }
1072
1073           ldap_value_free (certid);
1074         }
1075
1076       free_strlist (seen);
1077
1078       if (! fp)
1079         err = gpg_error (GPG_ERR_NO_DATA);
1080     }
1081   }
1082
1083  out:
1084   if (message)
1085     ldap_msgfree (message);
1086
1087   if (err)
1088     {
1089       if (fp)
1090         es_fclose (fp);
1091     }
1092   else
1093     {
1094       if (fp)
1095         es_fseek (fp, 0, SEEK_SET);
1096
1097       *r_fp = fp;
1098     }
1099
1100   xfree (basedn);
1101
1102   if (ldap_conn)
1103     ldap_unbind (ldap_conn);
1104
1105   xfree (filter);
1106
1107   return err;
1108 }
1109
1110
1111 /* Search the keyserver identified by URI for keys matching PATTERN.
1112    On success R_FP has an open stream to read the data.  */
1113 gpg_error_t
1114 ks_ldap_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern,
1115                 estream_t *r_fp)
1116 {
1117   gpg_error_t err;
1118   int ldap_err;
1119   unsigned int serverinfo;
1120   char *filter = NULL;
1121   LDAP *ldap_conn = NULL;
1122   char *basedn = NULL;
1123   estream_t fp = NULL;
1124
1125   (void) ctrl;
1126
1127   if (dirmngr_use_tor ())
1128     {
1129       /* For now we do not support LDAP over Tor.  */
1130       log_error (_("LDAP access not possible due to Tor mode\n"));
1131       return gpg_error (GPG_ERR_NOT_SUPPORTED);
1132     }
1133
1134   /* Make sure we are talking to an OpenPGP LDAP server.  */
1135   ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
1136   if (ldap_err || !basedn)
1137     {
1138       if (ldap_err)
1139         err = ldap_err_to_gpg_err (ldap_err);
1140       else
1141         err = GPG_ERR_GENERAL;
1142       goto out;
1143     }
1144
1145   /* Now that we have information about the server we can construct a
1146    * query best suited for the capabilities of the server.  */
1147   err = keyspec_to_ldap_filter (pattern, &filter, 0, serverinfo);
1148   if (err)
1149     {
1150       log_error ("Bad search pattern: '%s'\n", pattern);
1151       goto out;
1152     }
1153
1154   /* Even if we have no results, we want to return a stream.  */
1155   fp = es_fopenmem(0, "rw");
1156   if (!fp)
1157     {
1158       err = gpg_error_from_syserror ();
1159       goto out;
1160     }
1161
1162   {
1163     char **vals;
1164     LDAPMessage *res, *each;
1165     int count = 0;
1166     strlist_t dupelist = NULL;
1167
1168     /* The maximum size of the search, including the optional stuff
1169        and the trailing \0 */
1170     char *attrs[] =
1171       {
1172         "pgpcertid", "pgpuserid", "pgprevoked", "pgpdisabled",
1173         "pgpkeycreatetime", "pgpkeyexpiretime", "modifytimestamp",
1174         "pgpkeysize", "pgpkeytype", NULL
1175       };
1176
1177     if (opt.debug)
1178       log_debug ("SEARCH '%s' => '%s' BEGIN\n", pattern, filter);
1179
1180     npth_unprotect ();
1181     ldap_err = ldap_search_s (ldap_conn, basedn,
1182                               LDAP_SCOPE_SUBTREE, filter, attrs, 0, &res);
1183     npth_protect ();
1184
1185     xfree (filter);
1186     filter = NULL;
1187
1188     if (ldap_err != LDAP_SUCCESS && ldap_err != LDAP_SIZELIMIT_EXCEEDED)
1189       {
1190         err = ldap_err_to_gpg_err (ldap_err);
1191
1192         log_error ("SEARCH %s FAILED %d\n", pattern, err);
1193         log_error ("ks-ldap: LDAP search error: %s\n",
1194                    ldap_err2string (err));
1195         goto out;
1196     }
1197
1198     /* The LDAP server doesn't return a real count of unique keys, so we
1199        can't use ldap_count_entries here. */
1200     for (npth_unprotect (),
1201            each = ldap_first_entry (ldap_conn, res),
1202            npth_protect ();
1203          each;
1204          npth_unprotect (),
1205            each = ldap_next_entry (ldap_conn, each),
1206            npth_protect ())
1207       {
1208         char **certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1209         if (certid && certid[0] && ! strlist_find (dupelist, certid[0]))
1210           {
1211             add_to_strlist (&dupelist, certid[0]);
1212             count++;
1213           }
1214       }
1215
1216     if (ldap_err == LDAP_SIZELIMIT_EXCEEDED)
1217       {
1218         if (count == 1)
1219           log_error ("ks-ldap: search results exceeded server limit."
1220                      "  First 1 result shown.\n");
1221         else
1222           log_error ("ks-ldap: search results exceeded server limit."
1223                      "  First %d results shown.\n", count);
1224       }
1225
1226     free_strlist (dupelist);
1227     dupelist = NULL;
1228
1229     if (count < 1)
1230       es_fputs ("info:1:0\n", fp);
1231     else
1232       {
1233         es_fprintf (fp, "info:1:%d\n", count);
1234
1235         for (each = ldap_first_entry (ldap_conn, res);
1236              each;
1237              each = ldap_next_entry (ldap_conn, each))
1238           {
1239             char **certid;
1240             LDAPMessage *uids;
1241
1242             certid = ldap_get_values (ldap_conn, each, "pgpcertid");
1243             if (! certid || ! certid[0])
1244               continue;
1245
1246             /* Have we seen this certid before? */
1247             if (! strlist_find (dupelist, certid[0]))
1248               {
1249                 add_to_strlist (&dupelist, certid[0]);
1250
1251                 es_fprintf (fp, "pub:%s:",certid[0]);
1252
1253                 vals = ldap_get_values (ldap_conn, each, "pgpkeytype");
1254                 if (vals)
1255                   {
1256                     /* The LDAP server doesn't exactly handle this
1257                        well. */
1258                     if (strcasecmp (vals[0], "RSA") == 0)
1259                       es_fputs ("1", fp);
1260                     else if (strcasecmp (vals[0], "DSS/DH") == 0)
1261                       es_fputs ("17", fp);
1262                     ldap_value_free (vals);
1263                   }
1264
1265                 es_fputc (':', fp);
1266
1267                 vals = ldap_get_values (ldap_conn, each, "pgpkeysize");
1268                 if (vals)
1269                   {
1270                     /* Not sure why, but some keys are listed with a
1271                        key size of 0.  Treat that like an unknown. */
1272                     if (atoi (vals[0]) > 0)
1273                       es_fprintf (fp, "%d", atoi (vals[0]));
1274                     ldap_value_free (vals);
1275                   }
1276
1277                 es_fputc (':', fp);
1278
1279                 /* YYYYMMDDHHmmssZ */
1280
1281                 vals = ldap_get_values (ldap_conn, each, "pgpkeycreatetime");
1282                 if(vals && strlen (vals[0]) == 15)
1283                   {
1284                     es_fprintf (fp, "%u",
1285                                 (unsigned int) ldap2epochtime(vals[0]));
1286                     ldap_value_free (vals);
1287                   }
1288
1289                 es_fputc (':', fp);
1290
1291                 vals = ldap_get_values (ldap_conn, each, "pgpkeyexpiretime");
1292                 if (vals && strlen (vals[0]) == 15)
1293                   {
1294                     es_fprintf (fp, "%u",
1295                                 (unsigned int) ldap2epochtime (vals[0]));
1296                     ldap_value_free (vals);
1297                   }
1298
1299                 es_fputc (':', fp);
1300
1301                 vals = ldap_get_values (ldap_conn, each, "pgprevoked");
1302                 if (vals)
1303                   {
1304                     if (atoi (vals[0]) == 1)
1305                       es_fprintf (fp, "r");
1306                     ldap_value_free (vals);
1307                   }
1308
1309                 vals = ldap_get_values (ldap_conn, each, "pgpdisabled");
1310                 if (vals)
1311                   {
1312                     if (atoi (vals[0]) ==1)
1313                       es_fprintf (fp, "d");
1314                     ldap_value_free (vals);
1315                   }
1316
1317 #if 0
1318                 /* This is not yet specified in the keyserver
1319                    protocol, but may be someday. */
1320                 es_fputc (':', fp);
1321
1322                 vals = ldap_get_values (ldap_conn, each, "modifytimestamp");
1323                 if(vals && strlen (vals[0]) == 15)
1324                   {
1325                     es_fprintf (fp, "%u",
1326                                 (unsigned int) ldap2epochtime (vals[0]));
1327                     ldap_value_free (vals);
1328                   }
1329 #endif
1330
1331                 es_fprintf (fp, "\n");
1332
1333                 /* Now print all the uids that have this certid */
1334                 for (uids = ldap_first_entry (ldap_conn, res);
1335                      uids;
1336                      uids = ldap_next_entry (ldap_conn, uids))
1337                   {
1338                     vals = ldap_get_values (ldap_conn, uids, "pgpcertid");
1339                     if (! vals)
1340                       continue;
1341
1342                     if (strcasecmp (certid[0], vals[0]) == 0)
1343                       {
1344                         char **uidvals;
1345
1346                         es_fprintf (fp, "uid:");
1347
1348                         uidvals = ldap_get_values (ldap_conn,
1349                                                    uids, "pgpuserid");
1350                         if (uidvals)
1351                           {
1352                             /* Need to escape any colons */
1353                             char *quoted = percent_escape (uidvals[0], NULL);
1354                             es_fputs (quoted, fp);
1355                             xfree (quoted);
1356                             ldap_value_free (uidvals);
1357                           }
1358
1359                         es_fprintf (fp, "\n");
1360                       }
1361
1362                     ldap_value_free(vals);
1363                   }
1364               }
1365
1366               ldap_value_free (certid);
1367           }
1368       }
1369
1370     ldap_msgfree (res);
1371     free_strlist (dupelist);
1372   }
1373
1374   if (opt.debug)
1375     log_debug ("SEARCH %s END\n", pattern);
1376
1377  out:
1378   if (err)
1379     {
1380       if (fp)
1381         es_fclose (fp);
1382     }
1383   else
1384     {
1385       /* Return the read stream.  */
1386       if (fp)
1387         es_fseek (fp, 0, SEEK_SET);
1388
1389       *r_fp = fp;
1390     }
1391
1392   xfree (basedn);
1393
1394   if (ldap_conn)
1395     ldap_unbind (ldap_conn);
1396
1397   xfree (filter);
1398
1399   return err;
1400 }
1401
1402
1403 \f
1404 /* A modlist describes a set of changes to an LDAP entry.  (An entry
1405    consists of 1 or more attributes.  Attributes are <name, value>
1406    pairs.  Note: an attribute may be multi-valued in which case
1407    multiple values are associated with a single name.)
1408
1409    A modlist is a NULL terminated array of struct LDAPMod's.
1410
1411    Thus, if we have:
1412
1413      LDAPMod **modlist;
1414
1415    Then:
1416
1417      modlist[i]
1418
1419    Is the ith modification.
1420
1421    Each LDAPMod describes a change to a single attribute.  Further,
1422    there is one modification for each attribute that we want to
1423    change.  The attribute's new value is stored in LDAPMod.mod_values.
1424    If the attribute is multi-valued, we still only use a single
1425    LDAPMod structure: mod_values is a NULL-terminated array of
1426    strings.  To delete an attribute from an entry, we set mod_values
1427    to NULL.
1428
1429    Thus, if:
1430
1431      modlist[i]->mod_values == NULL
1432
1433    then we remove the attribute.
1434
1435    (Using LDAP_MOD_DELETE doesn't work here as we don't know if the
1436    attribute in question exists or not.)
1437
1438    Note: this function does NOT copy or free ATTR.  It does copy
1439    VALUE.  */
1440 static void
1441 modlist_add (LDAPMod ***modlistp, char *attr, const char *value)
1442 {
1443   LDAPMod **modlist = *modlistp;
1444
1445   LDAPMod **m;
1446   int nummods = 0;
1447
1448   /* Search modlist for the attribute we're playing with.  If modlist
1449      is NULL, then the list is empty.  Recall: modlist is a NULL
1450      terminated array.  */
1451   for (m = modlist; m && *m; m++, nummods ++)
1452     {
1453       /* The attribute is already on the list.  */
1454       char **ptr;
1455       int numvalues = 0;
1456
1457       if (strcasecmp ((*m)->mod_type, attr) != 0)
1458         continue;
1459
1460       /* We have this attribute already, so when the REPLACE happens,
1461          the server attributes will be replaced anyway. */
1462       if (! value)
1463         return;
1464
1465       /* Attributes can be multi-valued.  See if the value is already
1466          present.  mod_values is a NULL terminated array of pointers.
1467          Note: mod_values can be NULL.  */
1468       for (ptr = (*m)->mod_values; ptr && *ptr; ptr++)
1469         {
1470           if (strcmp (*ptr, value) == 0)
1471             /* Duplicate value, we're done.  */
1472             return;
1473           numvalues ++;
1474         }
1475
1476       /* Append the value.  */
1477       ptr = xrealloc ((*m)->mod_values, sizeof (char *) * (numvalues + 2));
1478
1479       (*m)->mod_values = ptr;
1480       ptr[numvalues] = xstrdup (value);
1481
1482       ptr[numvalues + 1] = NULL;
1483
1484       return;
1485     }
1486
1487   /* We didn't find the attr, so make one and add it to the end */
1488
1489   /* Like attribute values, the list of attributes is NULL terminated
1490      array of pointers.  */
1491   modlist = xrealloc (modlist, sizeof (LDAPMod *) * (nummods + 2));
1492
1493   *modlistp = modlist;
1494   modlist[nummods] = xmalloc (sizeof (LDAPMod));
1495
1496   modlist[nummods]->mod_op = LDAP_MOD_REPLACE;
1497   modlist[nummods]->mod_type = attr;
1498   if (value)
1499     {
1500       modlist[nummods]->mod_values = xmalloc (sizeof(char *) * 2);
1501
1502       modlist[nummods]->mod_values[0] = xstrdup (value);
1503       modlist[nummods]->mod_values[1] = NULL;
1504     }
1505   else
1506     modlist[nummods]->mod_values = NULL;
1507
1508   modlist[nummods + 1] = NULL;
1509
1510   return;
1511 }
1512
1513 /* Look up the value of an attribute in the specified modlist.  If the
1514    attribute is not on the mod list, returns NULL.  The result is a
1515    NULL-terminated array of strings.  Don't change it.  */
1516 static char **
1517 modlist_lookup (LDAPMod **modlist, const char *attr)
1518 {
1519   LDAPMod **m;
1520   for (m = modlist; m && *m; m++)
1521     {
1522       if (strcasecmp ((*m)->mod_type, attr) != 0)
1523         continue;
1524
1525       return (*m)->mod_values;
1526     }
1527
1528   return NULL;
1529 }
1530
1531 /* Dump a modlist to a file.  This is useful for debugging.  */
1532 static estream_t modlist_dump (LDAPMod **modlist, estream_t output)
1533   GPGRT_ATTR_USED;
1534
1535 static estream_t
1536 modlist_dump (LDAPMod **modlist, estream_t output)
1537 {
1538   LDAPMod **m;
1539
1540   int opened = 0;
1541
1542   if (! output)
1543     {
1544       output = es_fopenmem (0, "rw");
1545       if (!output)
1546         return NULL;
1547       opened = 1;
1548     }
1549
1550   for (m = modlist; m && *m; m++)
1551     {
1552       es_fprintf (output, "  %s:", (*m)->mod_type);
1553
1554       if (! (*m)->mod_values)
1555         es_fprintf(output, " delete.\n");
1556       else
1557         {
1558           char **ptr;
1559           int i;
1560
1561           int multi = 0;
1562           if ((*m)->mod_values[0] && (*m)->mod_values[1])
1563             /* Have at least 2.  */
1564             multi = 1;
1565
1566           if (multi)
1567             es_fprintf (output, "\n");
1568
1569           for ((ptr = (*m)->mod_values), (i = 1); ptr && *ptr; ptr++, i ++)
1570             {
1571               /* Assuming terminals are about 80 characters wide,
1572                  display at most about 10 lines of debugging
1573                  output.  If we do trim the buffer, append '...' to
1574                  the end.  */
1575               const int max_len = 10 * 70;
1576               size_t value_len = strlen (*ptr);
1577               int elide = value_len > max_len;
1578
1579               if (multi)
1580                 es_fprintf (output, "    %d. ", i);
1581               es_fprintf (output, "`%.*s", max_len, *ptr);
1582               if (elide)
1583                 es_fprintf (output, "...' (%zd bytes elided)",
1584                             value_len - max_len);
1585               else
1586                 es_fprintf (output, "'");
1587               es_fprintf (output, "\n");
1588             }
1589         }
1590     }
1591
1592   if (opened)
1593     es_fseek (output, 0, SEEK_SET);
1594
1595   return output;
1596 }
1597
1598 /* Free all of the memory allocated by the mod list.  This assumes
1599    that the attribute names don't have to be freed, but the attributes
1600    values do.  (Which is what modlist_add does.)  */
1601 static void
1602 modlist_free (LDAPMod **modlist)
1603 {
1604   LDAPMod **ml;
1605
1606   if (! modlist)
1607     return;
1608
1609   /* Unwind and free the whole modlist structure */
1610
1611   /* The modlist is a NULL terminated array of pointers.  */
1612   for (ml = modlist; *ml; ml++)
1613     {
1614       LDAPMod *mod = *ml;
1615       char **ptr;
1616
1617       /* The list of values is a NULL termianted array of pointers.
1618          If the list is NULL, there are no values.  */
1619
1620       if (mod->mod_values)
1621         {
1622           for (ptr = mod->mod_values; *ptr; ptr++)
1623             xfree (*ptr);
1624
1625           xfree (mod->mod_values);
1626         }
1627
1628       xfree (mod);
1629     }
1630   xfree (modlist);
1631 }
1632
1633 /* Append two onto the end of one.  Two is not freed, but its pointers
1634    are now part of one.  Make sure you don't free them both!
1635
1636    As long as you don't add anything to ONE, TWO is still valid.
1637    After that all bets are off.  */
1638 static void
1639 modlists_join (LDAPMod ***one, LDAPMod **two)
1640 {
1641   int i, one_count = 0, two_count = 0;
1642   LDAPMod **grow;
1643
1644   if (!*two)
1645     /* two is empty.  Nothing to do.  */
1646     return;
1647
1648   if (!*one)
1649     /* one is empty.  Just set it equal to *two.  */
1650     {
1651       *one = two;
1652       return;
1653     }
1654
1655   for (grow = *one; *grow; grow++)
1656     one_count ++;
1657
1658   for (grow = two; *grow; grow++)
1659     two_count ++;
1660
1661   grow = xrealloc (*one, sizeof(LDAPMod *) * (one_count + two_count + 1));
1662
1663   for (i = 0; i < two_count; i++)
1664     grow[one_count + i] = two[i];
1665
1666   grow[one_count + i] = NULL;
1667
1668   *one = grow;
1669 }
1670
1671 /* Given a string, unescape C escapes.  In particular, \xXX.  This
1672    modifies the string in place.  */
1673 static void
1674 uncescape (char *str)
1675 {
1676   size_t r = 0;
1677   size_t w = 0;
1678
1679   char *first = strchr (str, '\\');
1680   if (! first)
1681     /* No backslashes => no escaping.  We're done.  */
1682     return;
1683
1684   /* Start at the first '\\'.  */
1685   r = w = (uintptr_t) first - (uintptr_t) str;
1686
1687   while (str[r])
1688     {
1689       /* XXX: What to do about bad escapes?
1690          XXX: hextobyte already checks the string thus the hexdigitp
1691          could be removed. */
1692       if (str[r] == '\\' && str[r + 1] == 'x'
1693           && str[r+2] && str[r+3]
1694           && hexdigitp (str + r + 2)
1695           && hexdigitp (str + r + 3))
1696         {
1697           int x = hextobyte (&str[r + 2]);
1698           assert (0 <= x && x <= 0xff);
1699
1700           str[w] = x;
1701
1702           /* We consumed 4 characters and wrote 1.  */
1703           r += 4;
1704           w ++;
1705         }
1706       else
1707         str[w ++] = str[r ++];
1708     }
1709
1710   str[w] = '\0';
1711 }
1712
1713 /* Given one line from an info block (`gpg --list-{keys,sigs}
1714    --with-colons KEYID'), pull it apart and fill in the modlist with
1715    the relevant (for the LDAP schema) attributes.  EXTRACT_STATE
1716    should initally be set to 0 by the caller.  SCHEMAV2 is set if the
1717    server supports the version 2 schema.  */
1718 static void
1719 extract_attributes (LDAPMod ***modlist, int *extract_state,
1720                     char *line, int schemav2)
1721 {
1722   int field_count;
1723   char **fields;
1724   char *keyid;
1725   int is_pub, is_sub, is_uid, is_sig;
1726
1727   /* Remove trailing whitespace */
1728   trim_trailing_spaces (line);
1729
1730   fields = strsplit (line, ':', '\0', &field_count);
1731   if (field_count == 1)
1732     /* We only have a single field.  There is definitely nothing to
1733        do.  */
1734     goto out;
1735
1736   if (field_count < 7)
1737     goto out;
1738
1739   is_pub = !ascii_strcasecmp ("pub", fields[0]);
1740   is_sub = !ascii_strcasecmp ("sub", fields[0]);
1741   is_uid = !ascii_strcasecmp ("uid", fields[0]);
1742   is_sig = !ascii_strcasecmp ("sig", fields[0]);
1743   if (!ascii_strcasecmp ("fpr", fields[0]))
1744     {
1745       /* Special treatment for a fingerprint.  */
1746       if (!(*extract_state & 1))
1747         goto out;  /* Stray fingerprint line - ignore.  */
1748       *extract_state &= ~1;
1749       if (field_count >= 10 && schemav2)
1750         {
1751           if ((*extract_state & 2))
1752             modlist_add (modlist, "gpgFingerprint", fields[9]);
1753           else
1754             modlist_add (modlist, "gpgSubFingerprint", fields[9]);
1755         }
1756       goto out;
1757     }
1758
1759   *extract_state &= ~(1|2);
1760   if (is_pub)
1761     *extract_state |= (1|2);
1762   else if (is_sub)
1763     *extract_state |= 1;
1764
1765   if (!is_pub && !is_sub && !is_uid && !is_sig)
1766     goto out; /* Not a relevant line.  */
1767
1768   keyid = fields[4];
1769
1770   if (is_uid && strlen (keyid) == 0)
1771     ; /* The uid record type can have an empty keyid.  */
1772   else if (strlen (keyid) == 16
1773            && strspn (keyid, "0123456789aAbBcCdDeEfF") == 16)
1774     ; /* Otherwise, we expect exactly 16 hex characters.  */
1775   else
1776     {
1777       log_error ("malformed record!\n");
1778       goto out;
1779     }
1780
1781   if (is_pub)
1782     {
1783       int disabled = 0;
1784       int revoked = 0;
1785       char *flags;
1786       for (flags = fields[1]; *flags; flags ++)
1787         switch (*flags)
1788           {
1789           case 'r':
1790           case 'R':
1791             revoked = 1;
1792             break;
1793
1794           case 'd':
1795           case 'D':
1796             disabled = 1;
1797             break;
1798           }
1799
1800       /* Note: we always create the pgpDisabled and pgpRevoked
1801         attributes, regardless of whether the key is disabled/revoked
1802         or not.  This is because a very common search is like
1803         "(&(pgpUserID=*isabella*)(pgpDisabled=0))"  */
1804
1805       if (is_pub)
1806         {
1807           modlist_add (modlist,"pgpDisabled", disabled ? "1" : "0");
1808           modlist_add (modlist,"pgpRevoked", revoked ? "1" : "0");
1809         }
1810     }
1811
1812   if (is_pub || is_sub)
1813     {
1814       char padded[6];
1815       int val;
1816
1817       val = atoi (fields[2]);
1818       if (val < 99999 && val > 0)
1819         {
1820           /* We zero pad this on the left to make PGP happy. */
1821           snprintf (padded, sizeof padded, "%05u", val);
1822           modlist_add (modlist, "pgpKeySize", padded);
1823         }
1824     }
1825
1826   if (is_pub)
1827     {
1828       char *algo = fields[3];
1829       int val = atoi (algo);
1830       switch (val)
1831         {
1832         case 1:
1833           algo = "RSA";
1834           break;
1835
1836         case 17:
1837           algo = "DSS/DH";
1838           break;
1839
1840         default:
1841           algo = NULL;
1842           break;
1843         }
1844
1845       if (algo)
1846         modlist_add (modlist, "pgpKeyType", algo);
1847     }
1848
1849   if (is_pub || is_sub || is_sig)
1850     {
1851       if (is_pub)
1852         {
1853           modlist_add (modlist, "pgpCertID", keyid);    /* Long keyid(!) */
1854           modlist_add (modlist, "pgpKeyID", &keyid[8]); /* Short keyid   */
1855         }
1856
1857       if (is_sub)
1858         modlist_add (modlist, "pgpSubKeyID", keyid);    /* Long keyid(!)  */
1859     }
1860
1861   if (is_pub)
1862     {
1863       char *create_time = fields[5];
1864
1865       if (strlen (create_time) == 0)
1866         create_time = NULL;
1867       else
1868         {
1869           char *create_time_orig = create_time;
1870           struct tm tm;
1871           time_t t;
1872           char *end;
1873
1874           memset (&tm, 0, sizeof (tm));
1875
1876           /* parse_timestamp handles both seconds fromt he epoch and
1877              ISO 8601 format.  We also need to handle YYYY-MM-DD
1878              format (as generated by gpg1 --with-colons --list-key).
1879              Check that first and then if it fails, then try
1880              parse_timestamp.  */
1881
1882           if (!isodate_human_to_tm (create_time, &tm))
1883             create_time = tm2ldaptime (&tm);
1884           else if ((t = parse_timestamp (create_time, &end)) != (time_t) -1
1885                    && *end == '\0')
1886             {
1887
1888               if (!gnupg_gmtime (&t, &tm))
1889                 create_time = NULL;
1890               else
1891                 create_time = tm2ldaptime (&tm);
1892             }
1893           else
1894             create_time = NULL;
1895
1896           if (! create_time)
1897             /* Failed to parse string.  */
1898             log_error ("Failed to parse creation time ('%s')",
1899                        create_time_orig);
1900         }
1901
1902       if (create_time)
1903         {
1904           modlist_add (modlist, "pgpKeyCreateTime", create_time);
1905           xfree (create_time);
1906         }
1907     }
1908
1909   if (is_pub)
1910     {
1911       char *expire_time = fields[6];
1912
1913       if (strlen (expire_time) == 0)
1914         expire_time = NULL;
1915       else
1916         {
1917           char *expire_time_orig = expire_time;
1918           struct tm tm;
1919           time_t t;
1920           char *end;
1921
1922           memset (&tm, 0, sizeof (tm));
1923
1924           /* parse_timestamp handles both seconds fromt he epoch and
1925              ISO 8601 format.  We also need to handle YYYY-MM-DD
1926              format (as generated by gpg1 --with-colons --list-key).
1927              Check that first and then if it fails, then try
1928              parse_timestamp.  */
1929
1930           if (!isodate_human_to_tm (expire_time, &tm))
1931             expire_time = tm2ldaptime (&tm);
1932           else if ((t = parse_timestamp (expire_time, &end)) != (time_t) -1
1933                    && *end == '\0')
1934             {
1935               if (!gnupg_gmtime (&t, &tm))
1936                 expire_time = NULL;
1937               else
1938                 expire_time = tm2ldaptime (&tm);
1939             }
1940           else
1941             expire_time = NULL;
1942
1943           if (! expire_time)
1944             /* Failed to parse string.  */
1945             log_error ("Failed to parse creation time ('%s')",
1946                        expire_time_orig);
1947         }
1948
1949       if (expire_time)
1950         {
1951           modlist_add (modlist, "pgpKeyExpireTime", expire_time);
1952           xfree (expire_time);
1953         }
1954     }
1955
1956   if (is_uid && field_count >= 10)
1957     {
1958       char *uid = fields[9];
1959       char *mbox;
1960
1961       uncescape (uid);
1962       modlist_add (modlist, "pgpUserID", uid);
1963       if (schemav2 && (mbox = mailbox_from_userid (uid, 0)))
1964         {
1965           modlist_add (modlist, "gpgMailbox", mbox);
1966           xfree (mbox);
1967         }
1968     }
1969
1970  out:
1971   xfree (fields);
1972 }
1973
1974 /* Send the key in {KEY,KEYLEN} with the metadata {INFO,INFOLEN} to
1975    the keyserver identified by URI.  See server.c:cmd_ks_put for the
1976    format of the data and metadata.  */
1977 gpg_error_t
1978 ks_ldap_put (ctrl_t ctrl, parsed_uri_t uri,
1979              void *data, size_t datalen,
1980              void *info, size_t infolen)
1981 {
1982   gpg_error_t err = 0;
1983   int ldap_err;
1984   unsigned int serverinfo;
1985   LDAP *ldap_conn = NULL;
1986   char *basedn = NULL;
1987   LDAPMod **modlist = NULL;
1988   LDAPMod **addlist = NULL;
1989   char *data_armored = NULL;
1990   int extract_state;
1991
1992   /* The last byte of the info block.  */
1993   const char *infoend = (const char *) info + infolen - 1;
1994
1995   /* Enable this code to dump the modlist to /tmp/modlist.txt.  */
1996 #if 0
1997 # warning Disable debug code before checking in.
1998   const int dump_modlist = 1;
1999 #else
2000   const int dump_modlist = 0;
2001 #endif
2002   estream_t dump = NULL;
2003
2004   /* Elide a warning.  */
2005   (void) ctrl;
2006
2007   if (dirmngr_use_tor ())
2008     {
2009       /* For now we do not support LDAP over Tor.  */
2010       log_error (_("LDAP access not possible due to Tor mode\n"));
2011       return gpg_error (GPG_ERR_NOT_SUPPORTED);
2012     }
2013
2014   ldap_err = my_ldap_connect (uri, &ldap_conn, &basedn, &serverinfo);
2015   if (ldap_err || !basedn)
2016     {
2017       if (ldap_err)
2018         err = ldap_err_to_gpg_err (ldap_err);
2019       else
2020         err = GPG_ERR_GENERAL;
2021       goto out;
2022     }
2023
2024   if (!(serverinfo & SERVERINFO_REALLDAP))
2025     {
2026       /* We appear to have a PGP.com Keyserver, which can unpack the
2027        * key on its own (not just a dump LDAP server).  This will
2028        * rarely be the case these days.  */
2029       LDAPMod mod;
2030       LDAPMod *attrs[2];
2031       char *key[2];
2032       char *dn;
2033
2034       key[0] = data;
2035       key[1] = NULL;
2036       memset (&mod, 0, sizeof (mod));
2037       mod.mod_op = LDAP_MOD_ADD;
2038       mod.mod_type = (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey";
2039       mod.mod_values = key;
2040       attrs[0] = &mod;
2041       attrs[1] = NULL;
2042
2043       dn = xtryasprintf ("pgpCertid=virtual,%s", basedn);
2044       if (!dn)
2045         {
2046           err = gpg_error_from_syserror ();
2047           goto out;
2048         }
2049       ldap_err = ldap_add_s (ldap_conn, dn, attrs);
2050       xfree (dn);
2051
2052       if (ldap_err != LDAP_SUCCESS)
2053         {
2054           err = ldap_err_to_gpg_err (err);
2055           goto out;
2056         }
2057
2058       goto out;
2059     }
2060
2061   modlist = xtrymalloc (sizeof (LDAPMod *));
2062   if (!modlist)
2063     {
2064       err = gpg_error_from_syserror ();
2065       goto out;
2066     }
2067   *modlist = NULL;
2068
2069   if (dump_modlist)
2070     {
2071       dump = es_fopen("/tmp/modlist.txt", "w");
2072       if (! dump)
2073         log_error ("Failed to open /tmp/modlist.txt: %s\n",
2074                    strerror (errno));
2075
2076       if (dump)
2077         {
2078           es_fprintf(dump, "data (%zd bytes)\n", datalen);
2079           es_fprintf(dump, "info (%zd bytes): '\n", infolen);
2080           es_fwrite(info, infolen, 1, dump);
2081           es_fprintf(dump, "'\n");
2082         }
2083     }
2084
2085   /* Start by nulling out all attributes.  We try and do a modify
2086      operation first, so this ensures that we don't leave old
2087      attributes lying around. */
2088   modlist_add (&modlist, "pgpDisabled", NULL);
2089   modlist_add (&modlist, "pgpKeyID", NULL);
2090   modlist_add (&modlist, "pgpKeyType", NULL);
2091   modlist_add (&modlist, "pgpUserID", NULL);
2092   modlist_add (&modlist, "pgpKeyCreateTime", NULL);
2093   modlist_add (&modlist, "pgpRevoked", NULL);
2094   modlist_add (&modlist, "pgpSubKeyID", NULL);
2095   modlist_add (&modlist, "pgpKeySize", NULL);
2096   modlist_add (&modlist, "pgpKeyExpireTime", NULL);
2097   modlist_add (&modlist, "pgpCertID", NULL);
2098   if ((serverinfo & SERVERINFO_SCHEMAV2))
2099     {
2100       modlist_add (&modlist, "gpgFingerprint", NULL);
2101       modlist_add (&modlist, "gpgSubFingerprint", NULL);
2102       modlist_add (&modlist, "gpgMailbox", NULL);
2103     }
2104
2105   /* Assemble the INFO stuff into LDAP attributes */
2106   extract_state = 0;
2107   while (infolen > 0)
2108     {
2109       char *temp = NULL;
2110
2111       char *newline = memchr (info, '\n', infolen);
2112       if (! newline)
2113         /* The last line is not \n terminated!  Make a copy so we can
2114            add a NUL terminator.  */
2115         {
2116           temp = xmalloc (infolen + 1);
2117           memcpy (temp, info, infolen);
2118           info = temp;
2119           newline = (char *) info + infolen;
2120         }
2121
2122       *newline = '\0';
2123
2124       extract_attributes (&addlist, &extract_state, info,
2125                           (serverinfo & SERVERINFO_SCHEMAV2));
2126
2127       infolen = infolen - ((uintptr_t) newline - (uintptr_t) info + 1);
2128       info = newline + 1;
2129
2130       /* Sanity check.  */
2131       if (! temp)
2132         log_assert ((char *) info + infolen - 1 == infoend);
2133       else
2134         {
2135           log_assert (infolen == -1);
2136           xfree (temp);
2137         }
2138     }
2139
2140   modlist_add (&addlist, "objectClass", "pgpKeyInfo");
2141
2142   err = armor_data (&data_armored, data, datalen);
2143   if (err)
2144     goto out;
2145
2146   modlist_add (&addlist,
2147                (serverinfo & SERVERINFO_PGPKEYV2)? "pgpKeyV2":"pgpKey",
2148                data_armored);
2149
2150   /* Now append addlist onto modlist.  */
2151   modlists_join (&modlist, addlist);
2152
2153   if (dump)
2154     {
2155       estream_t input = modlist_dump (modlist, NULL);
2156       if (input)
2157         {
2158           copy_stream (input, dump);
2159           es_fclose (input);
2160         }
2161     }
2162
2163   /* Going on the assumption that modify operations are more frequent
2164      than adds, we try a modify first.  If it's not there, we just
2165      turn around and send an add command for the same key.  Otherwise,
2166      the modify brings the server copy into compliance with our copy.
2167      Note that unlike the LDAP keyserver (and really, any other
2168      keyserver) this does NOT merge signatures, but replaces the whole
2169      key.  This should make some people very happy. */
2170   {
2171     char **attrval;
2172     char *dn;
2173
2174     if ((serverinfo & SERVERINFO_NTDS))
2175       {
2176         /* The modern way using a CN RDN with the fingerprint.  This
2177          * has the advantage that we won't have duplicate 64 bit
2178          * keyids in the store.  In particular NTDS requires the
2179          * DN to be unique.  */
2180         attrval = modlist_lookup (addlist, "gpgFingerprint");
2181         /* We should have exactly one value.  */
2182         if (!attrval || !(attrval[0] && !attrval[1]))
2183           {
2184             log_error ("ks-ldap: bad gpgFingerprint provided\n");
2185             err = GPG_ERR_GENERAL;
2186             goto out;
2187           }
2188         dn = xtryasprintf ("CN=%s,%s", attrval[0], basedn);
2189       }
2190     else  /* The old style way.  */
2191       {
2192         attrval = modlist_lookup (addlist, "pgpCertID");
2193         /* We should have exactly one value.  */
2194         if (!attrval || !(attrval[0] && !attrval[1]))
2195           {
2196             log_error ("ks-ldap: bad pgpCertID provided\n");
2197             err = GPG_ERR_GENERAL;
2198             goto out;
2199           }
2200         dn = xtryasprintf ("pgpCertID=%s,%s", attrval[0], basedn);
2201       }
2202     if (!dn)
2203       {
2204         err = gpg_error_from_syserror ();
2205         goto out;
2206       }
2207     if (opt.debug)
2208       log_debug ("ks-ldap: using DN: %s\n", dn);
2209
2210     npth_unprotect ();
2211     err = ldap_modify_s (ldap_conn, dn, modlist);
2212     if (err == LDAP_NO_SUCH_OBJECT)
2213       err = ldap_add_s (ldap_conn, dn, addlist);
2214     npth_protect ();
2215
2216     xfree (dn);
2217
2218     if (err != LDAP_SUCCESS)
2219       {
2220         log_error ("ks-ldap: error adding key to keyserver: %s\n",
2221                    ldap_err2string (err));
2222         err = ldap_err_to_gpg_err (err);
2223       }
2224   }
2225
2226  out:
2227   if (dump)
2228     es_fclose (dump);
2229
2230   if (ldap_conn)
2231     ldap_unbind (ldap_conn);
2232
2233   xfree (basedn);
2234
2235   modlist_free (modlist);
2236   xfree (addlist);
2237
2238   xfree (data_armored);
2239
2240   return err;
2241 }