1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2005 The OpenLDAP Foundation.
6 * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7 * Portions Copyright 1998-2001 Net Boolean Incorporated.
8 * Portions Copyright 2001-2003 IBM Corporation.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20 * All rights reserved.
22 * Redistribution and use in source and binary forms are permitted
23 * provided that this notice is preserved and that due credit is given
24 * to the University of Michigan at Ann Arbor. The name of the
25 * University may not be used to endorse or promote products derived
26 * from this software without specific prior written permission. This
27 * software is provided ``as is'' without express or implied warranty.
30 * This work was originally developed by the University of Michigan
31 * (as part of U-MICH LDAP). Additional significant contributors
43 #include <ac/stdlib.h>
46 #include <ac/string.h>
47 #include <ac/unistd.h>
51 #if defined(TEST_ABANDON) || defined(TEST_CANCEL)
52 #include <ac/signal.h>
58 #ifdef HAVE_SYS_TYPES_H
59 #include <sys/types.h>
69 #include "lutil_ldap.h"
70 #include "ldap_defaults.h"
77 static int scope = LDAP_SCOPE_SUBTREE;
78 static int deref = -1;
80 static int timelimit = -1;
81 static int sizelimit = -1;
83 static char *def_tmpdir;
84 static char *def_urlpre;
86 #if defined(__CYGWIN__) || defined(__MINGW32__)
87 /* Turn off commandline globbing, otherwise you cannot search for
96 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
97 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
98 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
99 fprintf( stderr, _(" which may include:\n"));
100 fprintf( stderr, _(" 1.1 no attributes\n"));
101 fprintf( stderr, _(" * all user attributes\n"));
102 fprintf( stderr, _(" + all operational attributes\n"));
105 fprintf( stderr, _("Search options:\n"));
106 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
107 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
108 fprintf( stderr, _(" -b basedn base dn for search\n"));
109 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
110 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
111 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
113 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
114 #ifdef LDAP_CONTROL_PAGEDRESULTS
115 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
117 #ifdef LDAP_CONTROL_SUBENTRIES
118 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
120 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
121 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
122 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
123 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
124 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
125 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
126 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
127 fprintf( stderr, _(" and version\n"));
128 #ifdef LDAP_SCOPE_SUBORDINATE
129 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
130 #else /* ! LDAP_SCOPE_SUBORDINATE */
131 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
132 #endif /* ! LDAP_SCOPE_SUBORDINATE */
133 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
134 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
135 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
136 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
137 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
138 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
140 exit( EXIT_FAILURE );
143 static void print_entry LDAP_P((
148 static void print_reference(
150 LDAPMessage *reference );
152 static void print_extended(
154 LDAPMessage *extended );
156 static void print_partial(
158 LDAPMessage *partial );
160 static int print_result(
165 static void print_ctrls(
166 LDAPControl **ctrls );
168 static int write_ldif LDAP_P((
174 static int dosearch LDAP_P((
182 LDAPControl **sctrls,
183 LDAPControl **cctrls,
184 struct timeval *timeout,
187 static char *tmpdir = NULL;
188 static char *urlpre = NULL;
189 static char *base = NULL;
190 static char *sortattr = NULL;
191 static int includeufn, vals2tmp = 0, ldif = 0;
193 static int subentries = 0, valuesReturnFilter = 0;
194 static char *vrFilter = NULL;
196 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
197 static int domainScope = 0;
200 static int ldapsync = 0;
201 static struct berval sync_cookie = { 0, NULL };
202 static int sync_slimit = -1;
204 #ifdef LDAP_CONTROL_PAGEDRESULTS
205 static int pagedResults = 0;
206 static int pagePrompt = 1;
207 static ber_int_t pageSize = 0;
208 static ber_int_t entriesLeft = 0;
209 static ber_int_t morePagedResults = 1;
210 static struct berval page_cookie = { 0, NULL };
211 static int npagedresponses;
212 static int npagedentries;
213 static int npagedreferences;
214 static int npagedextended;
215 static int npagedpartial;
217 static int parse_page_control(
220 struct berval *cookie );
228 if (*LDAP_DIRSEP != '/') {
229 for (p = url; *p; p++) {
230 if (*p == *LDAP_DIRSEP)
237 const char options[] = "a:Ab:E:F:l:Ls:S:tT:uz:"
238 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
241 handle_private_option( int i )
244 char *control, *cvalue, *next;
246 case 'a': /* set alias deref option */
247 if ( strcasecmp( optarg, "never" ) == 0 ) {
248 deref = LDAP_DEREF_NEVER;
249 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
250 deref = LDAP_DEREF_SEARCHING;
251 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
252 deref = LDAP_DEREF_FINDING;
253 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
254 deref = LDAP_DEREF_ALWAYS;
257 _("alias deref should be never, search, find, or always\n") );
261 case 'A': /* retrieve attribute names only -- no values */
264 case 'b': /* search base */
265 base = ber_strdup( optarg );
267 case 'E': /* search extensions */
268 if( protocol == LDAP_VERSION2 ) {
269 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
271 exit( EXIT_FAILURE );
274 /* should be extended to support comma separated list of
275 * [!]key[=value] parameters, e.g. -E !foo,bar=567
280 if( optarg[0] == '!' ) {
285 control = ber_strdup( optarg );
286 if ( (cvalue = strchr( control, '=' )) != NULL ) {
290 if ( strcasecmp( control, "mv" ) == 0 ) {
291 /* ValuesReturnFilter control */
292 if( valuesReturnFilter ) {
294 _("ValuesReturnFilter previously specified\n"));
295 exit( EXIT_FAILURE );
297 valuesReturnFilter= 1 + crit;
299 if ( cvalue == NULL ) {
301 _("missing filter in ValuesReturnFilter control\n"));
302 exit( EXIT_FAILURE );
306 protocol = LDAP_VERSION3;
308 #ifdef LDAP_CONTROL_PAGEDRESULTS
309 } else if ( strcasecmp( control, "pr" ) == 0 ) {
311 /* PagedResults control */
312 if ( pagedResults != 0 ) {
314 _("PagedResultsControl previously specified\n") );
315 exit( EXIT_FAILURE );
318 if( cvalue != NULL ) {
321 promptp = strchr( cvalue, '/' );
322 if ( promptp != NULL ) {
324 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
326 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
330 _("Invalid value for PagedResultsControl,"
331 " %s/%s.\n"), cvalue, promptp );
332 exit( EXIT_FAILURE );
335 num = sscanf( cvalue, "%d", &tmp );
338 _("Invalid value for PagedResultsControl, %s.\n"),
340 exit( EXIT_FAILURE );
343 fprintf( stderr, _("Invalid value for PagedResultsControl.\n"),
345 exit( EXIT_FAILURE );
347 pageSize = (ber_int_t) tmp;
348 pagedResults = 1 + crit;
351 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
352 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
355 _("domainScope control previously specified\n"));
356 exit( EXIT_FAILURE );
358 if( cvalue != NULL ) {
360 _("domainScope: no control value expected\n") );
364 domainScope = 1 + crit;
366 #ifdef LDAP_CONTROL_SUBENTRIES
367 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
370 _("subentries control previously specified\n"));
371 exit( EXIT_FAILURE );
373 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
375 } else if ( strcasecmp( cvalue, "false") == 0 ) {
379 _("subentries control value \"%s\" invalid\n"),
381 exit( EXIT_FAILURE );
383 if( crit ) subentries *= -1;
386 } else if ( strcasecmp( control, "sync" ) == 0 ) {
390 fprintf( stderr, _("sync control previously specified\n") );
391 exit( EXIT_FAILURE );
393 if ( cvalue == NULL ) {
394 fprintf( stderr, _("missing specification of sync control\n"));
395 exit( EXIT_FAILURE );
397 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
398 ldapsync = LDAP_SYNC_REFRESH_ONLY;
399 cookiep = strchr( cvalue, '/' );
400 if ( cookiep != NULL ) {
402 if ( *cookiep != '\0' ) {
403 ber_str2bv( cookiep, 0, 0, &sync_cookie );
406 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
407 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
408 cookiep = strchr( cvalue, '/' );
409 if ( cookiep != NULL ) {
413 slimitp = strchr( cvalue, '/' );
414 if ( slimitp != NULL ) {
417 if ( cookiep != NULL && *cookiep != '\0' )
418 ber_str2bv( cookiep, 0, 0, &sync_cookie );
419 if ( slimitp != NULL && *slimitp != '\0' ) {
420 ival = strtol( slimitp, &next, 10 );
421 if ( next == NULL || next[0] != '\0' ) {
422 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
423 exit( EXIT_FAILURE );
428 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
430 exit( EXIT_FAILURE );
432 if ( crit ) ldapsync *= -1;
435 fprintf( stderr, _("Invalid search extension name: %s\n"),
440 case 'F': /* uri prefix */
441 if( urlpre ) free( urlpre );
442 urlpre = strdup( optarg );
444 case 'l': /* time limit */
445 if ( strcasecmp( optarg, "none" ) == 0 ) {
448 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
449 timelimit = LDAP_MAXINT;
452 ival = strtol( optarg, &next, 10 );
453 if ( next == NULL || next[0] != '\0' ) {
455 _("Unable to parse time limit \"%s\"\n"), optarg );
456 exit( EXIT_FAILURE );
460 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
461 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
463 exit( EXIT_FAILURE );
466 case 'L': /* print entries in LDIF format */
469 case 's': /* search scope */
470 if ( strncasecmp( optarg, "base", sizeof("base"-1) ) == 0 ) {
471 scope = LDAP_SCOPE_BASE;
472 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
473 scope = LDAP_SCOPE_ONELEVEL;
474 #ifdef LDAP_SCOPE_SUBORDINATE
475 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
476 || ( strcasecmp( optarg, "children" ) == 0 ))
478 scope = LDAP_SCOPE_SUBORDINATE;
480 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
481 scope = LDAP_SCOPE_SUBTREE;
483 fprintf( stderr, _("scope should be base, one, or sub\n") );
487 case 'S': /* sort attribute */
488 sortattr = strdup( optarg );
490 case 't': /* write attribute values to TMPDIR files */
493 case 'T': /* tmpdir */
494 if( tmpdir ) free( tmpdir );
495 tmpdir = strdup( optarg );
497 case 'u': /* include UFN */
500 case 'z': /* size limit */
501 if ( strcasecmp( optarg, "none" ) == 0 ) {
504 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
505 sizelimit = LDAP_MAXINT;
508 ival = strtol( optarg, &next, 10 );
509 if ( next == NULL || next[0] != '\0' ) {
511 _("Unable to parse size limit \"%s\"\n"), optarg );
512 exit( EXIT_FAILURE );
516 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
517 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
519 exit( EXIT_FAILURE );
530 private_conn_setup( LDAP *ld )
533 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
534 != LDAP_OPT_SUCCESS )
536 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
537 exit( EXIT_FAILURE );
540 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
541 != LDAP_OPT_SUCCESS )
544 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
545 exit( EXIT_FAILURE );
548 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
549 != LDAP_OPT_SUCCESS )
552 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
553 exit( EXIT_FAILURE );
557 #if defined(TEST_ABANDON) || defined(TEST_CANCEL)
568 main( int argc, char **argv )
570 char *filtpattern, **attrs = NULL, line[BUFSIZ];
574 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
576 BerElement *syncber = NULL;
577 struct berval *syncbvalp = NULL;
581 #ifdef LDAP_CONTROL_PAGEDRESULTS
582 npagedresponses = npagedentries = npagedreferences =
583 npagedextended = npagedpartial = 0;
586 prog = lutil_progname( "ldapsearch", argc, argv );
588 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
589 (def_tmpdir = getenv("TMP")) == NULL &&
590 (def_tmpdir = getenv("TEMP")) == NULL )
592 def_tmpdir = LDAP_TMPDIR;
596 def_tmpdir = LDAP_TMPDIR;
598 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
600 if( def_urlpre == NULL ) {
605 sprintf( def_urlpre, "file:///%s/",
606 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
608 urlize( def_urlpre );
610 tool_args( argc, argv );
612 if (( argc - optind < 1 ) ||
613 ( *argv[optind] != '(' /*')'*/ &&
614 ( strchr( argv[optind], '=' ) == NULL ) ) )
616 filtpattern = "(objectclass=*)";
618 filtpattern = strdup( argv[optind++] );
621 if ( argv[optind] != NULL ) {
622 attrs = &argv[optind];
625 #if defined(TEST_ABANDON) || defined(TEST_CANCEL)
626 SIGNAL( SIGINT, do_sig );
629 if ( infile != NULL ) {
630 if ( infile[0] == '-' && infile[1] == '\0' ) {
632 } else if (( fp = fopen( infile, "r" )) == NULL ) {
638 if ( tmpdir == NULL ) {
641 if ( urlpre == NULL )
645 if( urlpre == NULL ) {
646 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
648 if( urlpre == NULL ) {
653 sprintf( urlpre, "file:///%s/",
654 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
662 ld = tool_conn_setup( 0, &private_conn_setup );
664 if ( pw_file || want_bindpw ) {
666 rc = lutil_get_filed_password( pw_file, &passwd );
667 if( rc ) return EXIT_FAILURE;
669 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
670 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
677 if ( assertion || authzid || manageDSAit || noop
678 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
681 #ifdef LDAP_CONTROL_PAGEDRESULTS
684 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
686 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
688 || subentries || valuesReturnFilter )
694 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
696 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
697 c[i].ldctl_value.bv_val = NULL;
698 c[i].ldctl_value.bv_len = 0;
699 c[i].ldctl_iscritical = domainScope > 1;
704 #ifdef LDAP_CONTROL_SUBENTRIES
706 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
710 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
712 ber_free( seber, 1 );
713 fprintf( stderr, _("Subentries control encoding error!\n") );
717 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
721 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
722 c[i].ldctl_iscritical = subentries < 1;
728 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
732 if ( sync_cookie.bv_len == 0 ) {
733 err = ber_printf( syncber, "{e}", abs(ldapsync) );
735 err = ber_printf( syncber, "{eO}", abs(ldapsync),
739 if ( err == LBER_ERROR ) {
740 ber_free( syncber, 1 );
741 fprintf( stderr, _("ldap sync control encoding error!\n") );
745 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
749 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
750 c[i].ldctl_value = (*syncbvalp);
751 c[i].ldctl_iscritical = ldapsync < 0;
755 if ( valuesReturnFilter ) {
756 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
760 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
761 ber_free( vrber, 1 );
762 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
766 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
770 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
771 c[i].ldctl_iscritical = valuesReturnFilter > 1;
775 #ifdef LDAP_CONTROL_PAGEDRESULTS
776 if ( pagedResults ) {
777 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
781 ber_printf( prber, "{iO}", pageSize, &page_cookie );
782 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
785 if ( page_cookie.bv_val != NULL ) {
786 ber_memfree( page_cookie.bv_val );
787 page_cookie.bv_val = NULL;
790 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
791 c[i].ldctl_iscritical = pagedResults > 1;
796 tool_server_controls( ld, c, i );
798 #ifdef LDAP_CONTROL_SUBENTRIES
799 ber_free( seber, 1 );
801 ber_free( vrber, 1 );
802 #ifdef LDAP_CONTROL_PAGEDRESULTS
803 ber_free( prber, 1 );
808 fprintf( stderr, _("filter%s: %s\nrequesting: "),
809 infile != NULL ? _(" pattern") : "",
812 if ( attrs == NULL ) {
813 fprintf( stderr, _("ALL") );
815 for ( i = 0; attrs[ i ] != NULL; ++i ) {
816 fprintf( stderr, "%s ", attrs[ i ] );
819 fprintf( stderr, "\n" );
823 printf( _("# extended LDIF\n") );
824 } else if ( ldif < 3 ) {
825 printf( _("version: %d\n\n"), 1 );
830 printf(_("# LDAPv%d\n"), protocol);
831 printf(_("# base <%s> with scope %s\n"),
833 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
834 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
835 #ifdef LDAP_SCOPE_SUBORDINATE
836 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
839 #ifdef LDAP_SCOPE_SUBORDINATE
843 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
845 printf(_("# requesting: "));
847 if ( attrs == NULL ) {
850 for ( i = 0; attrs[ i ] != NULL; ++i ) {
851 printf( "%s ", attrs[ i ] );
856 printf(_("\n# with manageDSAit %scontrol"),
857 manageDSAit > 1 ? _("critical ") : "" );
860 printf(_("\n# with noop %scontrol"),
861 noop > 1 ? _("critical ") : "" );
864 printf(_("\n# with subentries %scontrol: %s"),
865 subentries < 0 ? _("critical ") : "",
866 abs(subentries) == 1 ? "false" : "true" );
868 if ( valuesReturnFilter ) {
869 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
870 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
872 #ifdef LDAP_CONTROL_PAGEDRESULTS
873 if ( pagedResults ) {
874 printf(_("\n# with pagedResults %scontrol: size=%d"),
875 (pagedResults > 1) ? _("critical ") : "",
880 printf( _("\n#\n\n") );
883 if ( infile == NULL ) {
884 rc = dosearch( ld, base, scope, NULL, filtpattern,
885 attrs, attrsonly, NULL, NULL, NULL, -1 );
890 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
891 line[ strlen( line ) - 1 ] = '\0';
897 rc = dosearch( ld, base, scope, filtpattern, line,
898 attrs, attrsonly, NULL, NULL, NULL, -1 );
905 #ifdef LDAP_CONTROL_PAGEDRESULTS
906 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
908 int i, moreEntries, tmpSize;
910 /* Loop to get the next pages when
911 * enter is pressed on the terminal.
913 if ( pagePrompt != 0 ) {
914 if ( entriesLeft > 0 ) {
915 printf( _("Estimate entries: %d\n"), entriesLeft );
917 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
920 moreEntries = getchar();
921 while ( moreEntries != EOF && moreEntries != '\n' ) {
922 if ( i < (int)sizeof(buf) - 1 ) {
923 buf[i] = moreEntries;
926 moreEntries = getchar();
930 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
931 int num = sscanf( buf, "%d", &tmpSize );
933 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
937 pageSize = (ber_int_t)tmpSize;
945 ldap_unbind_ext( ld, NULL, NULL );
946 #ifdef HAVE_CYRUS_SASL
950 ldap_pvt_tls_destroy();
964 LDAPControl **sctrls,
965 LDAPControl **cctrls,
966 struct timeval *timeout,
976 LDAPMessage *res, *msg;
979 struct berval *retdata = NULL;
980 int nresponses_psearch = -1;
981 int cancel_msgid = -1;
983 if( filtpatt != NULL ) {
984 filter = malloc( strlen( filtpatt ) + strlen( value ) );
985 if( filter == NULL ) {
990 sprintf( filter, filtpatt, value );
993 fprintf( stderr, _("filter: %s\n"), filter );
997 printf( _("#\n# filter: %s\n#\n"), filter );
1005 return LDAP_SUCCESS;
1008 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1009 sctrls, cctrls, timeout, sizelimit, &msgid );
1011 if ( filtpatt != NULL ) {
1015 if( rc != LDAP_SUCCESS ) {
1016 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1017 prog, ldap_err2string( rc ), rc );
1021 nresponses = nentries = nreferences = nextended = npartial = 0;
1025 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1026 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1030 (void) ldap_sort_entries( ld, &res,
1031 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1034 for ( msg = ldap_first_message( ld, res );
1036 msg = ldap_next_message( ld, msg ) )
1038 if ( nresponses++ ) putchar('\n');
1039 if ( nresponses_psearch >= 0 )
1040 nresponses_psearch++;
1042 switch( ldap_msgtype( msg ) ) {
1043 case LDAP_RES_SEARCH_ENTRY:
1045 print_entry( ld, msg, attrsonly );
1048 case LDAP_RES_SEARCH_REFERENCE:
1050 print_reference( ld, msg );
1053 case LDAP_RES_EXTENDED:
1055 print_extended( ld, msg );
1057 if( ldap_msgid( msg ) == 0 ) {
1058 /* unsolicited extended operation */
1062 if ( cancel_msgid != -1 &&
1063 cancel_msgid == ldap_msgid( msg ) ) {
1064 printf(_("Cancelled \n"));
1065 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1070 case LDAP_RES_SEARCH_RESULT:
1071 rc = print_result( ld, msg, 1 );
1072 #ifdef LDAP_CONTROL_PAGEDRESULTS
1073 if ( pageSize != 0 ) {
1074 if ( rc == LDAP_SUCCESS ) {
1075 rc = parse_page_control( ld, msg, &page_cookie );
1077 morePagedResults = 0;
1080 morePagedResults = 0;
1084 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1090 case LDAP_RES_INTERMEDIATE:
1092 ldap_parse_intermediate( ld, msg,
1093 &retoid, &retdata, NULL, 0 );
1095 nresponses_psearch = 0;
1097 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1098 printf(_("SyncInfo Received\n"));
1099 ldap_memfree( retoid );
1100 ber_bvfree( retdata );
1104 print_partial( ld, msg );
1105 ldap_memfree( retoid );
1106 ber_bvfree( retdata );
1110 if ( ldapsync && sync_slimit != -1 &&
1111 nresponses_psearch >= sync_slimit ) {
1112 BerElement *msgidber = NULL;
1113 struct berval *msgidvalp = NULL;
1114 msgidber = ber_alloc_t(LBER_USE_DER);
1115 ber_printf(msgidber, "{i}", msgid);
1116 ber_flatten(msgidber, &msgidvalp);
1117 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1118 msgidvalp, NULL, NULL, &cancel_msgid);
1119 nresponses_psearch = -1;
1123 ldap_msgfree( res );
1125 #if defined(TEST_ABANDON) || defined(TEST_CANCEL)
1128 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1129 fprintf( stderr, "got interrupt, cancel got %d\n", rc );
1133 rc = ldap_abandon( ld, msgid );
1134 fprintf( stderr, "got interrupt, abandon got %d\n", rc );
1141 ldap_perror( ld, "ldap_result" );
1146 ldap_msgfree( res );
1147 #ifdef LDAP_CONTROL_PAGEDRESULTS
1148 if ( pagedResults ) {
1149 npagedresponses += nresponses;
1150 npagedentries += nentries;
1151 npagedextended += nextended;
1152 npagedpartial += npartial;
1153 npagedreferences += nreferences;
1154 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1155 printf( _("\n# numResponses: %d\n"), npagedresponses );
1156 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1157 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1158 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1159 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1164 printf( _("\n# numResponses: %d\n"), nresponses );
1165 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1166 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1167 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1168 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1174 /* This is the proposed new way of doing things.
1175 * It is more efficient, but the API is non-standard.
1184 char tmpfname[ 256 ];
1187 BerElement *ber = NULL;
1188 struct berval bv, *bvals, **bvp = &bvals;
1189 LDAPControl **ctrls = NULL;
1192 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1195 ufn = ldap_dn2ufn( bv.bv_val );
1196 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1198 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1200 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1201 if( rc != LDAP_SUCCESS ) {
1202 fprintf(stderr, _("print_entry: %d\n"), rc );
1203 ldap_perror( ld, "ldap_get_entry_controls" );
1204 exit( EXIT_FAILURE );
1208 print_ctrls( ctrls );
1209 ldap_controls_free( ctrls );
1214 ufn = ldap_dn2ufn( bv.bv_val );
1216 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1219 if( ufn != NULL ) ldap_memfree( ufn );
1221 if ( attrsonly ) bvp = NULL;
1223 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1225 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1227 if (bv.bv_val == NULL) break;
1230 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1232 } else if ( bvals ) {
1233 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1234 if ( vals2tmp > 1 || ( vals2tmp &&
1235 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1238 /* write value to file */
1239 snprintf( tmpfname, sizeof tmpfname,
1240 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1241 tmpdir, bv.bv_val );
1244 tmpfd = mkstemp( tmpfname );
1251 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1256 if ( fwrite( bvals[ i ].bv_val,
1257 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1266 snprintf( url, sizeof url, "%s%s", urlpre,
1267 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1270 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1273 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1274 bvals[ i ].bv_val, bvals[ i ].bv_len );
1277 ber_memfree( bvals );
1286 static void print_reference(
1288 LDAPMessage *reference )
1292 LDAPControl **ctrls;
1295 printf(_("# search reference\n"));
1298 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1300 if( rc != LDAP_SUCCESS ) {
1301 ldap_perror(ld, "ldap_parse_reference");
1302 exit( EXIT_FAILURE );
1307 for( i=0; refs[i] != NULL; i++ ) {
1308 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1309 "ref", refs[i], strlen(refs[i]) );
1311 ber_memvfree( (void **) refs );
1315 print_ctrls( ctrls );
1316 ldap_controls_free( ctrls );
1320 static void print_extended(
1322 LDAPMessage *extended )
1325 char *retoid = NULL;
1326 struct berval *retdata = NULL;
1329 printf(_("# extended result response\n"));
1332 rc = ldap_parse_extended_result( ld, extended,
1333 &retoid, &retdata, 0 );
1335 if( rc != LDAP_SUCCESS ) {
1336 ldap_perror(ld, "ldap_parse_extended_result");
1337 exit( EXIT_FAILURE );
1341 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1342 "extended", retoid, retoid ? strlen(retoid) : 0 );
1344 ber_memfree( retoid );
1348 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1349 "data", retdata->bv_val, retdata->bv_len );
1351 ber_bvfree( retdata );
1354 print_result( ld, extended, 0 );
1357 static void print_partial(
1359 LDAPMessage *partial )
1362 char *retoid = NULL;
1363 struct berval *retdata = NULL;
1364 LDAPControl **ctrls = NULL;
1367 printf(_("# extended partial response\n"));
1370 rc = ldap_parse_intermediate( ld, partial,
1371 &retoid, &retdata, &ctrls, 0 );
1373 if( rc != LDAP_SUCCESS ) {
1374 ldap_perror(ld, "ldap_parse_intermediate");
1375 exit( EXIT_FAILURE );
1379 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1380 "partial", retoid, retoid ? strlen(retoid) : 0 );
1383 ber_memfree( retoid );
1387 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1388 "data", retdata->bv_val, retdata->bv_len );
1391 ber_bvfree( retdata );
1395 print_ctrls( ctrls );
1396 ldap_controls_free( ctrls );
1400 static int print_result(
1402 LDAPMessage *result, int search )
1406 char *matcheddn = NULL;
1409 LDAPControl **ctrls = NULL;
1413 printf(_("# search result\n"));
1416 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1420 rc = ldap_parse_result( ld, result,
1421 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1423 if( rc != LDAP_SUCCESS ) {
1424 ldap_perror(ld, "ldap_parse_result");
1425 exit( EXIT_FAILURE );
1430 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1432 } else if ( err != LDAP_SUCCESS ) {
1433 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1439 write_ldif( LDIF_PUT_VALUE,
1440 "matchedDN", matcheddn, strlen(matcheddn) );
1442 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1446 ber_memfree( matcheddn );
1452 write_ldif( LDIF_PUT_TEXT, "text",
1453 text, strlen(text) );
1455 fprintf( stderr, _("Additional information: %s\n"), text );
1459 ber_memfree( text );
1464 for( i=0; refs[i] != NULL; i++ ) {
1466 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1468 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1472 ber_memvfree( (void **) refs );
1476 print_ctrls( ctrls );
1477 ldap_controls_free( ctrls );
1483 static void print_ctrls(
1484 LDAPControl **ctrls )
1487 for(i=0; ctrls[i] != NULL; i++ ) {
1488 /* control: OID criticality base64value */
1489 struct berval *b64 = NULL;
1494 len += strlen( ctrls[i]->ldctl_oid );
1496 /* add enough for space after OID and the critical value itself */
1497 len += ctrls[i]->ldctl_iscritical
1498 ? sizeof("true") : sizeof("false");
1500 /* convert to base64 */
1501 if( ctrls[i]->ldctl_value.bv_len ) {
1502 b64 = ber_memalloc( sizeof(struct berval) );
1504 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1505 ctrls[i]->ldctl_value.bv_len ) + 1;
1506 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1508 b64->bv_len = lutil_b64_ntop(
1509 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1510 ctrls[i]->ldctl_value.bv_len,
1511 b64->bv_val, b64->bv_len );
1515 len += 1 + b64->bv_len;
1518 str = malloc( len + 1 );
1520 strcpy( str, ": " );
1524 strcat( str, ctrls[i]->ldctl_oid );
1525 strcat( str, ctrls[i]->ldctl_iscritical
1526 ? " true" : " false" );
1530 strcat(str, b64->bv_val );
1534 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1535 "control", str, len );
1544 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1548 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1552 fputs( ldif, stdout );
1553 ber_memfree( ldif );
1559 #ifdef LDAP_CONTROL_PAGEDRESULTS
1563 LDAPMessage *result,
1564 struct berval *cookie )
1568 LDAPControl **ctrl = NULL;
1569 LDAPControl *ctrlp = NULL;
1573 rc = ldap_parse_result( ld, result,
1574 &err, NULL, NULL, NULL, &ctrl, 0 );
1576 if( rc != LDAP_SUCCESS ) {
1577 ldap_perror(ld, "ldap_parse_result");
1578 exit( EXIT_FAILURE );
1581 if ( err != LDAP_SUCCESS ) {
1582 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1586 /* Parse the control value
1587 * searchResult ::= SEQUENCE {
1588 * size INTEGER (0..maxInt),
1589 * -- result set size estimate from server - unused
1590 * cookie OCTET STRING
1594 ber = ber_init( &ctrlp->ldctl_value );
1595 if ( ber == NULL ) {
1596 fprintf( stderr, _("Internal error.\n") );
1597 return EXIT_FAILURE;
1600 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1601 (void) ber_free( ber, 1 );
1603 if( tag == LBER_ERROR ) {
1605 _("Paged results response control could not be decoded.\n") );
1606 return EXIT_FAILURE;
1609 if( entriesLeft < 0 ) {
1611 _("Invalid entries estimate in paged results response.\n") );
1612 return EXIT_FAILURE;
1615 if ( cookie->bv_len == 0 ) {
1616 morePagedResults = 0;
1619 ldap_controls_free( ctrl );
1622 morePagedResults = 0;