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