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