Bump to 2.4.3
[platform/upstream/gpg2.git] / dirmngr / dirmngr_ldap.c
1 /* dirmngr-ldap.c  -  The LDAP helper for dirmngr.
2  * Copyright (C) 2004, 2021 g10 Code GmbH
3  * Copyright (C) 2010 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  * SPDX-License-Identifier: GPL-3.0-or-later
20  */
21
22 #include <config.h>
23
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stddef.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #ifdef HAVE_SIGNAL_H
31 # include <signal.h>
32 #endif
33 #include <errno.h>
34 #include <sys/time.h>
35 #include <unistd.h>
36
37 #ifdef HAVE_W32_SYSTEM
38 # include <winsock2.h>
39 # include <winldap.h>
40 # include <winber.h>
41 # include <fcntl.h>
42 # include "ldap-url.h"
43 #else
44   /* For OpenLDAP, to enable the API that we're using. */
45 # define LDAP_DEPRECATED 1
46 # include <ldap.h>
47 #endif
48
49
50 #include <gpg-error.h>
51 #include "../common/logging.h"
52 #include "../common/stringhelp.h"
53 #include "../common/mischelp.h"
54 #include "../common/strlist.h"
55 #include "../common/util.h"
56 #include "../common/init.h"
57 #include "ldap-misc.h"
58
59
60 /* There is no need for the npth_unprotect and leave functions here;
61  * thus we redefine them to nops.  We keep them in the code just for
62  * the case we ever want to reuse parts of the code in npth programs. */
63 static void npth_unprotect (void) { }
64 static void npth_protect (void) { }
65
66
67 #ifdef HAVE_W32_SYSTEM
68  typedef LDAP_TIMEVAL  my_ldap_timeval_t;
69 #else
70  typedef struct timeval my_ldap_timeval_t;
71 #endif
72
73 #define DEFAULT_LDAP_TIMEOUT 15 /* Arbitrary long timeout. */
74
75
76 /* Constants for the options.  */
77 enum
78   {
79     oQuiet        = 'q',
80     oVerbose      = 'v',
81
82     oTimeout      = 500,
83     oMulti,
84     oProxy,
85     oHost,
86     oPort,
87     oUser,
88     oPass,
89     oEnvPass,
90     oBase,
91     oAttr,
92     oStartTLS,
93     oLdapTLS,
94     oNtds,
95     oARecOnly,
96     oOnlySearchTimeout,
97     oLogWithPID
98   };
99
100
101 /* The list of options as used by the argparse.c code.  */
102 static gpgrt_opt_t opts[] = {
103   { oVerbose,  "verbose",   0, "verbose" },
104   { oQuiet,    "quiet",     0, "be somewhat more quiet" },
105   { oTimeout,  "timeout",   1, "|N|set LDAP timeout to N seconds"},
106   { oMulti,    "multi",     0, "return all values in"
107                                " a record oriented format"},
108   { oProxy,    "proxy",     2,
109                 "|NAME|ignore host part and connect through NAME"},
110   { oStartTLS, "starttls",  0, "use STARTLS for the conenction"},
111   { oLdapTLS,  "ldaptls",   0, "use a TLS for the connection"},
112   { oNtds,     "ntds",      0, "authenticate using AD"},
113   { oARecOnly, "areconly",  0, "do only an A record lookup"},
114   { oHost,     "host",      2, "|NAME|connect to host NAME"},
115   { oPort,     "port",      1, "|N|connect to port N"},
116   { oUser,     "user",      2, "|NAME|use NAME for authentication"},
117   { oPass,     "pass",      2, "|PASS|use password PASS"
118                                " for authentication"},
119   { oEnvPass,  "env-pass",  0, "take password from $DIRMNGR_LDAP_PASS"},
120   { oBase,     "base",      2, "|DN|Start query at DN"},
121   { oAttr,     "attr",      2, "|STRING|return the attribute STRING"},
122   { oOnlySearchTimeout, "only-search-timeout", 0, "@"},
123   { oLogWithPID,"log-with-pid", 0, "@"},
124   ARGPARSE_end ()
125 };
126
127
128 /* A structure with module options.  */
129 static struct
130 {
131   int quiet;
132   int verbose;
133   my_ldap_timeval_t timeout;/* Timeout for the LDAP search functions.  */
134   unsigned int alarm_timeout; /* And for the alarm based timeout.  */
135   int multi;
136   int starttls;
137   int ldaptls;
138   int ntds;
139   int areconly;
140
141   estream_t outstream;    /* Send output to this stream.  */
142
143   /* Note that we can't use const for the strings because ldap_* are
144      not defined that way.  */
145   char *proxy; /* Host and Port override.  */
146   char *user;  /* Authentication user.  */
147   char *pass;  /* Authentication password.  */
148   char *host;  /* Override host.  */
149   int  port;   /* Override port.  */
150   char *base;  /* Override DN.  */
151   char *attr;  /* Override attribute.  */
152 } opt;
153
154
155 /* Prototypes.  */
156 #ifndef HAVE_W32_SYSTEM
157 static void catch_alarm (int dummy);
158 #endif
159 static gpg_error_t connect_ldap (LDAP **r_ld);
160 static gpg_error_t process_filter (LDAP *ld, const char *string);
161
162
163
164 /* Function called by argparse.c to display information.  */
165 static const char *
166 my_strusage (int level)
167 {
168   const char *p;
169
170   switch (level)
171     {
172     case  9: p = "GPL-3.0-or-later"; break;
173     case 11: p = "dirmngr_ldap (@GNUPG@)";
174       break;
175     case 13: p = VERSION; break;
176     case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
177     case 17: p = PRINTABLE_OS_NAME; break;
178     case 19: p = "Please report bugs to <@EMAIL@>.\n"; break;
179     case 49: p = PACKAGE_BUGREPORT; break;
180     case 1:
181     case 40: p =
182                "Usage: dirmngr_ldap [options] filters (-h for help)\n";
183       break;
184     case 41: p =
185            ("Syntax: dirmngr_ldap [options] filters\n"
186             "Internal LDAP helper for Dirmngr\n"
187             "Interface and options may change without notice\n");
188       break;
189
190     default: p = NULL;
191     }
192   return p;
193 }
194
195
196 int
197 main (int argc, char **argv)
198 {
199   gpgrt_argparse_t pargs;
200   int any_err = 0;
201   char *p;
202   int only_search_timeout = 0;
203   char *malloced_buffer1 = NULL;
204   LDAP *ld;
205
206   early_system_init ();
207
208   gpgrt_set_strusage (my_strusage);
209   log_set_prefix ("dirmngr_ldap", GPGRT_LOG_WITH_PREFIX);
210
211   init_common_subsystems (&argc, &argv);
212
213   es_set_binary (es_stdout);
214   opt.outstream = es_stdout;
215
216   /* LDAP defaults */
217   opt.timeout.tv_sec = DEFAULT_LDAP_TIMEOUT;
218   opt.timeout.tv_usec = 0;
219   opt.alarm_timeout = 0;
220
221   /* Parse the command line.  */
222   pargs.argc = &argc;
223   pargs.argv = &argv;
224   pargs.flags= ARGPARSE_FLAG_KEEP;
225   while (gpgrt_argparse (NULL, &pargs, opts))
226     {
227       switch (pargs.r_opt)
228         {
229         case oVerbose: opt.verbose++; break;
230         case oQuiet: opt.quiet++; break;
231         case oTimeout:
232           opt.timeout.tv_sec = pargs.r.ret_int;
233           opt.timeout.tv_usec = 0;
234           opt.alarm_timeout = pargs.r.ret_int;
235           break;
236         case oOnlySearchTimeout: only_search_timeout = 1; break;
237         case oStartTLS: opt.starttls = 1; opt.ldaptls = 0; break;
238         case oLdapTLS:  opt.starttls = 0; opt.ldaptls = 1; break;
239         case oNtds:     opt.ntds = 1; break;
240         case oARecOnly: opt.areconly = 1; break;
241         case oMulti: opt.multi = 1; break;
242         case oUser: opt.user = pargs.r.ret_str; break;
243         case oPass: opt.pass = pargs.r.ret_str; break;
244         case oEnvPass:
245           opt.pass = getenv ("DIRMNGR_LDAP_PASS");
246           break;
247         case oProxy: opt.proxy = pargs.r.ret_str; break;
248         case oHost: opt.host = pargs.r.ret_str; break;
249         case oPort: opt.port = pargs.r.ret_int; break;
250         case oBase: opt.base = pargs.r.ret_str; break;
251         case oAttr: opt.attr = pargs.r.ret_str; break;
252         case oLogWithPID:
253           {
254             unsigned int oldflags;
255             log_get_prefix (&oldflags);
256             log_set_prefix (NULL, oldflags | GPGRT_LOG_WITH_PID);
257           }
258           break;
259
260         default :
261           pargs.err = ARGPARSE_PRINT_ERROR;
262           break;
263         }
264     }
265   gpgrt_argparse (NULL, &pargs, NULL);
266
267   if (only_search_timeout)
268     opt.alarm_timeout = 0;
269
270   if (opt.proxy)
271     {
272       malloced_buffer1 = xtrystrdup (opt.proxy);
273       if (!malloced_buffer1)
274         {
275           log_error ("error copying string: %s\n", strerror (errno));
276           return 1;
277         }
278       opt.host = malloced_buffer1;
279       p = strchr (opt.host, ':');
280       if (p)
281         {
282           *p++ = 0;
283           opt.port = atoi (p);
284         }
285       if (!opt.port)
286         opt.port = 389;  /* make sure ports gets overridden.  */
287     }
288
289   if (opt.port < 0 || opt.port > 65535)
290     log_error ("invalid port number %d\n", opt.port);
291
292   if (!opt.port)
293     opt.port = opt.ldaptls? 636 : 389;
294
295 #ifndef HAVE_W32_SYSTEM
296   if (!opt.host)
297     opt.host = "localhost";
298 #endif
299
300
301   if (log_get_errorcount (0))
302     exit (2);
303
304   if (opt.alarm_timeout)
305     {
306 #ifndef HAVE_W32_SYSTEM
307 # if defined(HAVE_SIGACTION) && defined(HAVE_STRUCT_SIGACTION)
308       struct sigaction act;
309
310       act.sa_handler = catch_alarm;
311       sigemptyset (&act.sa_mask);
312       act.sa_flags = 0;
313       if (sigaction (SIGALRM,&act,NULL))
314 # else
315       if (signal (SIGALRM, catch_alarm) == SIG_ERR)
316 # endif
317           log_fatal ("unable to register timeout handler\n");
318 #endif
319     }
320
321   if (connect_ldap (&ld))
322     any_err = 1;
323   else
324     {
325       if (!argc)
326         {
327           if (process_filter (ld, "(objectClass=*)"))
328             any_err = 1;
329         }
330       else
331         {
332           for (; argc; argc--, argv++)
333             if (process_filter (ld, *argv))
334               any_err = 1;
335         }
336       ldap_unbind (ld);
337     }
338
339   xfree (malloced_buffer1);
340   return any_err;
341 }
342
343 #ifndef HAVE_W32_SYSTEM
344 static void
345 catch_alarm (int dummy)
346 {
347   (void)dummy;
348   _exit (10);
349 }
350 #endif
351
352
353 #ifdef HAVE_W32_SYSTEM
354 static DWORD CALLBACK
355 alarm_thread (void *arg)
356 {
357   HANDLE timer = arg;
358
359   WaitForSingleObject (timer, INFINITE);
360   _exit (10);
361
362   return 0;
363 }
364 #endif
365
366
367 static void
368 set_timeout (void)
369 {
370   if (opt.alarm_timeout)
371     {
372 #ifdef HAVE_W32_SYSTEM
373       static HANDLE timer;
374       LARGE_INTEGER due_time;
375
376       /* A negative value is a relative time.  */
377       due_time.QuadPart = (unsigned long long)-10000000 * opt.alarm_timeout;
378
379       if (!timer)
380         {
381           SECURITY_ATTRIBUTES sec_attr;
382           DWORD tid;
383
384           memset (&sec_attr, 0, sizeof sec_attr);
385           sec_attr.nLength = sizeof sec_attr;
386           sec_attr.bInheritHandle = FALSE;
387
388           /* Create a manual resettable timer.  */
389           timer = CreateWaitableTimer (NULL, TRUE, NULL);
390           /* Initially set the timer.  */
391           SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0);
392
393           if (CreateThread (&sec_attr, 0, alarm_thread, timer, 0, &tid))
394             log_error ("failed to create alarm thread\n");
395         }
396       else /* Retrigger the timer.  */
397         SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0);
398 #else
399       alarm (opt.alarm_timeout);
400 #endif
401     }
402 }
403
404
405
406 /* Connect to the ldap server.  On success the connection handle is
407  * stored at R_LD. */
408 static gpg_error_t
409 connect_ldap (LDAP **r_ld)
410 {
411   gpg_error_t err = 0;
412   int lerr;
413   LDAP *ld = NULL;
414 #ifndef HAVE_W32_SYSTEM
415   char *tmpstr;
416 #endif
417
418   *r_ld = NULL;
419
420   if (opt.starttls || opt.ldaptls)
421     {
422 #ifndef HAVE_LDAP_START_TLS_S
423       log_error ("ldap: can't connect to the server: no TLS support.");
424       err = GPG_ERR_LDAP_NOT_SUPPORTED;
425       goto leave;
426 #endif
427     }
428
429
430   set_timeout ();
431 #ifdef HAVE_W32_SYSTEM
432   npth_unprotect ();
433   ld = ldap_sslinit (opt.host, opt.port, opt.ldaptls);
434   npth_protect ();
435   if (!ld)
436     {
437       lerr = LdapGetLastError ();
438       err = ldap_err_to_gpg_err (lerr);
439       log_error ("error initializing LDAP '%s:%d': %s\n",
440                  opt.host, opt.port, ldap_err2string (lerr));
441       goto leave;
442     }
443   if (opt.areconly)
444     {
445       lerr = ldap_set_option (ld, LDAP_OPT_AREC_EXCLUSIVE, LDAP_OPT_ON);
446       if (lerr != LDAP_SUCCESS)
447         {
448           log_error ("ldap: unable to set AREC_EXLUSIVE: %s\n",
449                      ldap_err2string (lerr));
450           err = ldap_err_to_gpg_err (lerr);
451           goto leave;
452         }
453     }
454 #else /* Unix */
455   tmpstr = xtryasprintf ("%s://%s:%d",
456                          opt.ldaptls? "ldaps" : "ldap",
457                          opt.host, opt.port);
458   if (!tmpstr)
459     {
460       err = gpg_error_from_syserror ();
461       goto leave;
462     }
463   npth_unprotect ();
464   lerr = ldap_initialize (&ld, tmpstr);
465   npth_protect ();
466   if (lerr || !ld)
467     {
468       err = ldap_err_to_gpg_err (lerr);
469       log_error ("error initializing LDAP '%s': %s\n",
470                  tmpstr, ldap_err2string (lerr));
471       xfree (tmpstr);
472       goto leave;
473     }
474   xfree (tmpstr);
475 #endif /* Unix */
476
477   if (opt.verbose)
478     log_info ("LDAP connected to '%s:%d'%s\n",
479               opt.host, opt.port,
480               opt.starttls? " using STARTTLS" :
481               opt.ldaptls?  " using LDAP-over-TLS" : "");
482
483
484 #ifdef HAVE_LDAP_SET_OPTION
485   {
486     int ver = LDAP_VERSION3;
487
488     lerr = ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &ver);
489     if (lerr != LDAP_SUCCESS)
490       {
491         log_error ("unable to go to LDAP 3: %s\n", ldap_err2string (lerr));
492         err = ldap_err_to_gpg_err (lerr);
493         goto leave;
494       }
495   }
496 #endif
497
498
499 #ifdef HAVE_LDAP_START_TLS_S
500   if (opt.starttls)
501     {
502 #ifndef HAVE_W32_SYSTEM
503       int check_cert = LDAP_OPT_X_TLS_HARD; /* LDAP_OPT_X_TLS_NEVER */
504
505       lerr = ldap_set_option (ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &check_cert);
506       if (lerr)
507         {
508           log_error ("ldap: error setting an TLS option: %s\n",
509                      ldap_err2string (lerr));
510           err = ldap_err_to_gpg_err (lerr);
511           goto leave;
512         }
513 #else
514       /* On Windows, the certificates are checked by default.  If the
515          option to disable checking mentioned above is ever
516          implemented, the way to do that on Windows is to install a
517          callback routine using ldap_set_option (..,
518          LDAP_OPT_SERVER_CERTIFICATE, ..); */
519 #endif
520
521       npth_unprotect ();
522       lerr = ldap_start_tls_s (ld,
523 #ifdef HAVE_W32_SYSTEM
524                               /* ServerReturnValue, result */
525                               NULL, NULL,
526 #endif
527                               /* ServerControls, ClientControls */
528                               NULL, NULL);
529       npth_protect ();
530       if (lerr)
531         {
532           log_error ("ldap: error switching to STARTTLS mode: %s\n",
533                      ldap_err2string (lerr));
534           err = ldap_err_to_gpg_err (lerr);
535           goto leave;
536         }
537     }
538 #endif
539
540   if (opt.ntds)
541     {
542       if (opt.verbose)
543         log_info ("binding to current user via AD\n");
544 #ifdef HAVE_W32_SYSTEM
545       npth_unprotect ();
546       lerr = ldap_bind_s (ld, NULL, NULL, LDAP_AUTH_NEGOTIATE);
547       npth_protect ();
548       if (lerr != LDAP_SUCCESS)
549         {
550           log_error ("error binding to LDAP via AD: %s\n",
551                      ldap_err2string (lerr));
552           err = ldap_err_to_gpg_err (lerr);
553           goto leave;
554         }
555 #else /* Unix */
556       err = gpg_error (GPG_ERR_NOT_SUPPORTED);
557       goto leave;
558 #endif /* Unix */
559     }
560   else if (opt.user)
561     {
562       if (opt.verbose)
563         log_info ("LDAP bind to '%s', password '%s'\n",
564                    opt.user, opt.pass ? ">not_shown<" : ">none<");
565
566       npth_unprotect ();
567       lerr = ldap_simple_bind_s (ld, opt.user, opt.pass);
568       npth_protect ();
569       if (lerr != LDAP_SUCCESS)
570         {
571           log_error ("error binding to LDAP: %s\n", ldap_err2string (lerr));
572           err = ldap_err_to_gpg_err (lerr);
573           goto leave;
574         }
575     }
576   else
577     {
578       /* By default we don't bind as there is usually no need to.  */
579     }
580
581  leave:
582   if (err)
583     {
584       if (ld)
585         ldap_unbind (ld);
586     }
587   else
588     *r_ld = ld;
589   return err;
590 }
591
592
593 /* Helper for fetch_ldap().  */
594 static int
595 print_ldap_entries (LDAP *ld, LDAPMessage *msg, char *want_attr)
596 {
597   LDAPMessage *item;
598   int any = 0;
599
600   for (npth_unprotect (), item = ldap_first_entry (ld, msg), npth_protect ();
601        item;
602        npth_unprotect (), item = ldap_next_entry (ld, item), npth_protect ())
603     {
604       BerElement *berctx;
605       char *attr;
606
607       if (opt.verbose > 1)
608         log_info ("scanning result for attribute '%s'\n",
609                   want_attr? want_attr : "[all]");
610
611       if (opt.multi)
612         { /*  Write item marker. */
613           if (es_fwrite ("I\0\0\0\0", 5, 1, opt.outstream) != 1)
614             {
615               log_error ("error writing to stdout: %s\n",
616                          strerror (errno));
617               return -1;
618             }
619         }
620
621
622       for (npth_unprotect (), attr = ldap_first_attribute (ld, item, &berctx),
623              npth_protect ();
624            attr;
625            npth_unprotect (), attr = ldap_next_attribute (ld, item, berctx),
626              npth_protect ())
627         {
628           struct berval **values;
629           int idx;
630
631           if (opt.verbose > 1)
632             log_info ("          available attribute '%s'\n", attr);
633
634           set_timeout ();
635
636           /* I case we want only one attribute we do a case
637              insensitive compare without the optional extension
638              (i.e. ";binary").  Case insensitive is not really correct
639              but the best we can do.  */
640           if (want_attr)
641             {
642               char *cp1, *cp2;
643               int cmpres;
644
645               cp1 = strchr (want_attr, ';');
646               if (cp1)
647                 *cp1 = 0;
648               cp2 = strchr (attr, ';');
649               if (cp2)
650                 *cp2 = 0;
651               cmpres = ascii_strcasecmp (want_attr, attr);
652               if (cp1)
653                 *cp1 = ';';
654               if (cp2)
655                 *cp2 = ';';
656               if (cmpres)
657                 {
658                   ldap_memfree (attr);
659                   continue; /* Not found:  Try next attribute.  */
660                 }
661             }
662
663           npth_unprotect ();
664           values = ldap_get_values_len (ld, item, attr);
665           npth_protect ();
666
667           if (!values)
668             {
669               if (opt.verbose)
670                 log_info ("attribute '%s' not found\n", attr);
671               ldap_memfree (attr);
672               continue;
673             }
674
675           if (opt.verbose)
676             {
677               log_info ("found attribute '%s'\n", attr);
678               if (opt.verbose > 1)
679                 for (idx=0; values[idx]; idx++)
680                   log_info ("         length[%d]=%d\n",
681                             idx, (int)values[0]->bv_len);
682
683             }
684
685           if (opt.multi)
686             { /*  Write attribute marker. */
687               unsigned char tmp[5];
688               size_t n = strlen (attr);
689
690               tmp[0] = 'A';
691               tmp[1] = (n >> 24);
692               tmp[2] = (n >> 16);
693               tmp[3] = (n >> 8);
694               tmp[4] = (n);
695               if (es_fwrite (tmp, 5, 1, opt.outstream) != 1
696                   || es_fwrite (attr, n, 1, opt.outstream) != 1)
697                 {
698                   log_error ("error writing to stdout: %s\n",
699                              strerror (errno));
700                   ldap_value_free_len (values);
701                   ldap_memfree (attr);
702                   ber_free (berctx, 0);
703                   return -1;
704                 }
705             }
706
707           for (idx=0; values[idx]; idx++)
708             {
709               if (opt.multi)
710                 { /* Write value marker.  */
711                   unsigned char tmp[5];
712                   size_t n = values[0]->bv_len;
713
714                   tmp[0] = 'V';
715                   tmp[1] = (n >> 24);
716                   tmp[2] = (n >> 16);
717                   tmp[3] = (n >> 8);
718                   tmp[4] = (n);
719
720                   if (es_fwrite (tmp, 5, 1, opt.outstream) != 1)
721                     {
722                       log_error ("error writing to stdout: %s\n",
723                                  strerror (errno));
724                       ldap_value_free_len (values);
725                       ldap_memfree (attr);
726                       ber_free (berctx, 0);
727                       return -1;
728                     }
729                 }
730
731               if (es_fwrite (values[0]->bv_val, values[0]->bv_len,
732                              1, opt.outstream) != 1)
733                 {
734                   log_error ("error writing to stdout: %s\n",
735                              strerror (errno));
736                   ldap_value_free_len (values);
737                   ldap_memfree (attr);
738                   ber_free (berctx, 0);
739                   return -1;
740                 }
741
742               any = 1;
743               if (!opt.multi)
744                 break; /* Print only the first value.  */
745             }
746           ldap_value_free_len (values);
747           ldap_memfree (attr);
748           if (want_attr || !opt.multi)
749             break; /* We only want to return the first attribute.  */
750         }
751       ber_free (berctx, 0);
752     }
753
754   if (opt.verbose > 1 && any)
755     log_info ("result has been printed\n");
756
757   return any?0:-1;
758 }
759
760
761
762 /* Fetch data from the server at LD using FILTER.  */
763 static int
764 fetch_ldap (LDAP *ld, const char *base, int scope, const char *filter)
765 {
766   gpg_error_t err;
767   int lerr;
768   LDAPMessage *msg;
769   char *attrs[2];
770
771   if (filter && !*filter)
772     filter = NULL;
773
774   if (opt.verbose)
775     {
776       log_info ("fetching using");
777       if (base)
778         log_printf (" base '%s'", base);
779       if (filter)
780         log_printf (" filter '%s'", filter);
781       log_printf ("\n");
782     }
783
784   attrs[0] = opt.attr;
785   attrs[1] = NULL;
786
787   set_timeout ();
788   npth_unprotect ();
789   lerr = ldap_search_st (ld, base, scope, filter,
790                          attrs,
791                          0,
792                          &opt.timeout, &msg);
793   npth_protect ();
794   if (lerr == LDAP_SIZELIMIT_EXCEEDED && opt.multi)
795     {
796       if (es_fwrite ("E\0\0\0\x09truncated", 14, 1, opt.outstream) != 1)
797         {
798           log_error ("error writing to stdout: %s\n", strerror (errno));
799           return -1;
800         }
801     }
802   else if (lerr)
803     {
804       log_error ("searching '%s' failed: %s\n",
805                  filter, ldap_err2string (lerr));
806       if (lerr != LDAP_NO_SUCH_OBJECT)
807         {
808           /* FIXME: Need deinit (ld)?  */
809           /* Hmmm: Do we need to released MSG in case of an error? */
810           return -1;
811         }
812     }
813
814   err = print_ldap_entries (ld, msg, opt.multi? NULL:opt.attr);
815
816   ldap_msgfree (msg);
817   return err;
818 }
819
820
821
822
823 /* Main processing.  Take the filter and run the LDAP query. The
824  * result is printed to stdout, errors are logged to the log stream.
825  * To allow searching with a different base it is possible to extend
826  * the filter.  For example:
827  *
828  *   ^CN=foo, OU=My Users&(objectClasses=*)
829  *
830  * Uses "CN=foo, OU=My Users" as base DN and "(objectClasses=*)" as
831  * filter.  If the base prefix includes an ampersand, it needs to be
832  * doubled.  The usual escaping rules for DNs (for the base) and
833  * filters apply.  If no scope is given (see ldap_parse_extfilter for
834  * the syntax) subtree scope is used.
835  */
836 static gpg_error_t
837 process_filter (LDAP *ld, const char *string)
838 {
839   gpg_error_t err;
840   char *base, *filter;
841   int scope = -1;
842
843   err = ldap_parse_extfilter (string, 0, &base, &scope, &filter);
844   if (!err)
845     err = fetch_ldap (ld,
846                       base? base : opt.base,
847                       scope == -1? LDAP_SCOPE_SUBTREE : scope,
848                       filter);
849
850   xfree (base);
851   xfree (filter);
852   return err;
853 }