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