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 #include <ac/signal.h>
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
67 #include "lutil_ldap.h"
68 #include "ldap_defaults.h"
75 static int scope = LDAP_SCOPE_SUBTREE;
76 static int deref = -1;
78 static int timelimit = -1;
79 static int sizelimit = -1;
81 static char *def_tmpdir;
82 static char *def_urlpre;
84 #if defined(__CYGWIN__) || defined(__MINGW32__)
85 /* Turn off commandline globbing, otherwise you cannot search for
94 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
95 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
96 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
97 fprintf( stderr, _(" which may include:\n"));
98 fprintf( stderr, _(" 1.1 no attributes\n"));
99 fprintf( stderr, _(" * all user attributes\n"));
100 fprintf( stderr, _(" + all operational attributes\n"));
103 fprintf( stderr, _("Search options:\n"));
104 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
105 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
106 fprintf( stderr, _(" -b basedn base dn for search\n"));
107 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
108 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
109 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
111 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
112 #ifdef LDAP_CONTROL_PAGEDRESULTS
113 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
115 #ifdef LDAP_CONTROL_SUBENTRIES
116 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
118 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
119 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
120 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
121 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
122 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
123 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
124 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
125 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
126 fprintf( stderr, _(" and version\n"));
127 #ifdef LDAP_SCOPE_SUBORDINATE
128 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
129 #else /* ! LDAP_SCOPE_SUBORDINATE */
130 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
131 #endif /* ! LDAP_SCOPE_SUBORDINATE */
132 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
133 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
134 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
135 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
136 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
137 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
139 exit( EXIT_FAILURE );
142 static void print_entry LDAP_P((
147 static void print_reference(
149 LDAPMessage *reference );
151 static void print_extended(
153 LDAPMessage *extended );
155 static void print_partial(
157 LDAPMessage *partial );
159 static int print_result(
164 static void print_ctrls(
165 LDAPControl **ctrls );
167 static int write_ldif LDAP_P((
173 static int dosearch LDAP_P((
181 LDAPControl **sctrls,
182 LDAPControl **cctrls,
183 struct timeval *timeout,
186 static char *tmpdir = NULL;
187 static char *urlpre = NULL;
188 static char *base = NULL;
189 static char *sortattr = NULL;
190 static int includeufn, vals2tmp = 0, ldif = 0;
192 static int subentries = 0, valuesReturnFilter = 0;
193 static char *vrFilter = NULL;
195 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
196 static int domainScope = 0;
199 static int ldapsync = 0;
200 static struct berval sync_cookie = { 0, NULL };
201 static int sync_slimit = -1;
203 #ifdef LDAP_CONTROL_PAGEDRESULTS
204 static int pagedResults = 0;
205 static int pagePrompt = 1;
206 static ber_int_t pageSize = 0;
207 static ber_int_t entriesLeft = 0;
208 static ber_int_t morePagedResults = 1;
209 static struct berval page_cookie = { 0, NULL };
210 static int npagedresponses;
211 static int npagedentries;
212 static int npagedreferences;
213 static int npagedextended;
214 static int npagedpartial;
216 static LDAPControl *c = NULL;
217 static int nctrls = 0;
225 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
226 if ( tmpc == NULL ) {
229 _("unable to make room for control; out of memory?\n"));
238 is_oid( const char *s )
242 if ( !isdigit( s[ 0 ] ) ) {
246 for ( ; s[ 0 ]; s++ ) {
247 if ( s[ 0 ] == '.' ) {
248 if ( s[ 1 ] == '\0' ) {
255 if ( !isdigit( s[ 0 ] ) ) {
259 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
268 static int parse_page_control(
271 struct berval *cookie );
279 if (*LDAP_DIRSEP != '/') {
280 for (p = url; *p; p++) {
281 if (*p == *LDAP_DIRSEP)
288 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
289 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
292 handle_private_option( int i )
295 char *control, *cvalue, *next;
297 case 'a': /* set alias deref option */
298 if ( strcasecmp( optarg, "never" ) == 0 ) {
299 deref = LDAP_DEREF_NEVER;
300 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
301 deref = LDAP_DEREF_SEARCHING;
302 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
303 deref = LDAP_DEREF_FINDING;
304 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
305 deref = LDAP_DEREF_ALWAYS;
308 _("alias deref should be never, search, find, or always\n") );
312 case 'A': /* retrieve attribute names only -- no values */
315 case 'b': /* search base */
316 base = ber_strdup( optarg );
318 case 'E': /* search extensions */
319 if( protocol == LDAP_VERSION2 ) {
320 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
322 exit( EXIT_FAILURE );
325 /* should be extended to support comma separated list of
326 * [!]key[=value] parameters, e.g. -E !foo,bar=567
331 if( optarg[0] == '!' ) {
336 control = ber_strdup( optarg );
337 if ( (cvalue = strchr( control, '=' )) != NULL ) {
341 if ( strcasecmp( control, "mv" ) == 0 ) {
342 /* ValuesReturnFilter control */
343 if( valuesReturnFilter ) {
345 _("ValuesReturnFilter previously specified\n"));
346 exit( EXIT_FAILURE );
348 valuesReturnFilter= 1 + crit;
350 if ( cvalue == NULL ) {
352 _("missing filter in ValuesReturnFilter control\n"));
353 exit( EXIT_FAILURE );
357 protocol = LDAP_VERSION3;
359 #ifdef LDAP_CONTROL_PAGEDRESULTS
360 } else if ( strcasecmp( control, "pr" ) == 0 ) {
362 /* PagedResults control */
363 if ( pagedResults != 0 ) {
365 _("PagedResultsControl previously specified\n") );
366 exit( EXIT_FAILURE );
369 if( cvalue != NULL ) {
372 promptp = strchr( cvalue, '/' );
373 if ( promptp != NULL ) {
375 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
377 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
381 _("Invalid value for PagedResultsControl,"
382 " %s/%s.\n"), cvalue, promptp );
383 exit( EXIT_FAILURE );
386 num = sscanf( cvalue, "%d", &tmp );
389 _("Invalid value for PagedResultsControl, %s.\n"),
391 exit( EXIT_FAILURE );
394 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
395 exit( EXIT_FAILURE );
397 pageSize = (ber_int_t) tmp;
398 pagedResults = 1 + crit;
401 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
402 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
405 _("domainScope control previously specified\n"));
406 exit( EXIT_FAILURE );
408 if( cvalue != NULL ) {
410 _("domainScope: no control value expected\n") );
414 domainScope = 1 + crit;
417 #ifdef LDAP_CONTROL_SUBENTRIES
418 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
421 _("subentries control previously specified\n"));
422 exit( EXIT_FAILURE );
424 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
426 } else if ( strcasecmp( cvalue, "false") == 0 ) {
430 _("subentries control value \"%s\" invalid\n"),
432 exit( EXIT_FAILURE );
434 if( crit ) subentries *= -1;
437 } else if ( strcasecmp( control, "sync" ) == 0 ) {
441 fprintf( stderr, _("sync control previously specified\n") );
442 exit( EXIT_FAILURE );
444 if ( cvalue == NULL ) {
445 fprintf( stderr, _("missing specification of sync control\n"));
446 exit( EXIT_FAILURE );
448 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
449 ldapsync = LDAP_SYNC_REFRESH_ONLY;
450 cookiep = strchr( cvalue, '/' );
451 if ( cookiep != NULL ) {
453 if ( *cookiep != '\0' ) {
454 ber_str2bv( cookiep, 0, 0, &sync_cookie );
457 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
458 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
459 cookiep = strchr( cvalue, '/' );
460 if ( cookiep != NULL ) {
464 slimitp = strchr( cvalue, '/' );
465 if ( slimitp != NULL ) {
468 if ( cookiep != NULL && *cookiep != '\0' )
469 ber_str2bv( cookiep, 0, 0, &sync_cookie );
470 if ( slimitp != NULL && *slimitp != '\0' ) {
471 ival = strtol( slimitp, &next, 10 );
472 if ( next == NULL || next[0] != '\0' ) {
473 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
474 exit( EXIT_FAILURE );
479 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
481 exit( EXIT_FAILURE );
483 if ( crit ) ldapsync *= -1;
485 } else if ( is_oid( control ) ) {
487 exit( EXIT_FAILURE );
491 c[ nctrls - 1 ].ldctl_oid = control;
494 if ( cvalue == NULL ) {
495 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
496 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
498 } else if ( cvalue[ 0 ] == ':' ) {
505 * to use ldif_parse_line2() */
507 ldif_parse_line2( &cvalue[ -2 ], &type,
508 &c[ nctrls - 1 ].ldctl_value, &freeval );
511 /* NOTE: if freeval == TRUE, leaks value */
515 c[ nctrls - 1 ].ldctl_iscritical = crit;
518 fprintf( stderr, _("Invalid search extension name: %s\n"),
523 case 'F': /* uri prefix */
524 if( urlpre ) free( urlpre );
525 urlpre = strdup( optarg );
527 case 'l': /* time limit */
528 if ( strcasecmp( optarg, "none" ) == 0 ) {
531 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
532 timelimit = LDAP_MAXINT;
535 ival = strtol( optarg, &next, 10 );
536 if ( next == NULL || next[0] != '\0' ) {
538 _("Unable to parse time limit \"%s\"\n"), optarg );
539 exit( EXIT_FAILURE );
543 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
544 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
546 exit( EXIT_FAILURE );
549 case 'L': /* print entries in LDIF format */
552 case 's': /* search scope */
553 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
554 scope = LDAP_SCOPE_BASE;
555 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
556 scope = LDAP_SCOPE_ONELEVEL;
557 #ifdef LDAP_SCOPE_SUBORDINATE
558 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
559 || ( strcasecmp( optarg, "children" ) == 0 ))
561 scope = LDAP_SCOPE_SUBORDINATE;
563 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
564 scope = LDAP_SCOPE_SUBTREE;
566 fprintf( stderr, _("scope should be base, one, or sub\n") );
570 case 'S': /* sort attribute */
571 sortattr = strdup( optarg );
573 case 't': /* write attribute values to TMPDIR files */
576 case 'T': /* tmpdir */
577 if( tmpdir ) free( tmpdir );
578 tmpdir = strdup( optarg );
580 case 'u': /* include UFN */
583 case 'z': /* size limit */
584 if ( strcasecmp( optarg, "none" ) == 0 ) {
587 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
588 sizelimit = LDAP_MAXINT;
591 ival = strtol( optarg, &next, 10 );
592 if ( next == NULL || next[0] != '\0' ) {
594 _("Unable to parse size limit \"%s\"\n"), optarg );
595 exit( EXIT_FAILURE );
599 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
600 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
602 exit( EXIT_FAILURE );
613 private_conn_setup( LDAP *ld )
616 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
617 != LDAP_OPT_SUCCESS )
619 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
620 exit( EXIT_FAILURE );
623 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
624 != LDAP_OPT_SUCCESS )
627 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
628 exit( EXIT_FAILURE );
631 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
632 != LDAP_OPT_SUCCESS )
635 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
636 exit( EXIT_FAILURE );
641 main( int argc, char **argv )
643 char *filtpattern, **attrs = NULL, line[BUFSIZ];
647 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
649 BerElement *syncber = NULL;
650 struct berval *syncbvalp = NULL;
654 #ifdef LDAP_CONTROL_PAGEDRESULTS
655 npagedresponses = npagedentries = npagedreferences =
656 npagedextended = npagedpartial = 0;
659 prog = lutil_progname( "ldapsearch", argc, argv );
661 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
662 (def_tmpdir = getenv("TMP")) == NULL &&
663 (def_tmpdir = getenv("TEMP")) == NULL )
665 def_tmpdir = LDAP_TMPDIR;
669 def_tmpdir = LDAP_TMPDIR;
671 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
673 if( def_urlpre == NULL ) {
678 sprintf( def_urlpre, "file:///%s/",
679 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
681 urlize( def_urlpre );
683 tool_args( argc, argv );
685 if (( argc - optind < 1 ) ||
686 ( *argv[optind] != '(' /*')'*/ &&
687 ( strchr( argv[optind], '=' ) == NULL ) ) )
689 filtpattern = "(objectclass=*)";
691 filtpattern = argv[optind++];
694 if ( argv[optind] != NULL ) {
695 attrs = &argv[optind];
698 if ( infile != NULL ) {
699 if ( infile[0] == '-' && infile[1] == '\0' ) {
701 } else if (( fp = fopen( infile, "r" )) == NULL ) {
707 if ( tmpdir == NULL ) {
710 if ( urlpre == NULL )
714 if( urlpre == NULL ) {
715 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
717 if( urlpre == NULL ) {
722 sprintf( urlpre, "file:///%s/",
723 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
731 ld = tool_conn_setup( 0, &private_conn_setup );
733 if ( pw_file || want_bindpw ) {
735 rc = lutil_get_filed_password( pw_file, &passwd );
736 if( rc ) return EXIT_FAILURE;
738 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
739 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
746 if ( nctrls > 0 || assertion || authzid || manageDSAit || noop
747 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
750 #ifdef LDAP_CONTROL_PAGEDRESULTS
753 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
755 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
757 || subentries || valuesReturnFilter )
761 int save_nctrls = nctrls;
763 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
769 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
770 c[i].ldctl_value.bv_val = NULL;
771 c[i].ldctl_value.bv_len = 0;
772 c[i].ldctl_iscritical = domainScope > 1;
777 #ifdef LDAP_CONTROL_SUBENTRIES
783 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
787 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
789 ber_free( seber, 1 );
790 fprintf( stderr, _("Subentries control encoding error!\n") );
794 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
798 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
799 c[i].ldctl_iscritical = subentries < 1;
809 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
813 if ( sync_cookie.bv_len == 0 ) {
814 err = ber_printf( syncber, "{e}", abs(ldapsync) );
816 err = ber_printf( syncber, "{eO}", abs(ldapsync),
820 if ( err == LBER_ERROR ) {
821 ber_free( syncber, 1 );
822 fprintf( stderr, _("ldap sync control encoding error!\n") );
826 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
830 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
831 c[i].ldctl_value = (*syncbvalp);
832 c[i].ldctl_iscritical = ldapsync < 0;
836 if ( valuesReturnFilter ) {
841 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
845 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
846 ber_free( vrber, 1 );
847 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
851 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
855 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
856 c[i].ldctl_iscritical = valuesReturnFilter > 1;
860 #ifdef LDAP_CONTROL_PAGEDRESULTS
861 if ( pagedResults ) {
866 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
870 ber_printf( prber, "{iO}", pageSize, &page_cookie );
871 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
874 if ( page_cookie.bv_val != NULL ) {
875 ber_memfree( page_cookie.bv_val );
876 page_cookie.bv_val = NULL;
879 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
880 c[i].ldctl_iscritical = pagedResults > 1;
885 tool_server_controls( ld, c, i );
887 /* step back to the original number of controls, so that
888 * those set while parsing args are preserved */
889 nctrls = save_nctrls;
891 #ifdef LDAP_CONTROL_SUBENTRIES
892 ber_free( seber, 1 );
894 ber_free( vrber, 1 );
895 #ifdef LDAP_CONTROL_PAGEDRESULTS
896 ber_free( prber, 1 );
901 fprintf( stderr, _("filter%s: %s\nrequesting: "),
902 infile != NULL ? _(" pattern") : "",
905 if ( attrs == NULL ) {
906 fprintf( stderr, _("ALL") );
908 for ( i = 0; attrs[ i ] != NULL; ++i ) {
909 fprintf( stderr, "%s ", attrs[ i ] );
912 fprintf( stderr, "\n" );
916 printf( _("# extended LDIF\n") );
917 } else if ( ldif < 3 ) {
918 printf( _("version: %d\n\n"), 1 );
923 printf(_("# LDAPv%d\n"), protocol);
924 printf(_("# base <%s> with scope %s\n"),
926 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
927 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
928 #ifdef LDAP_SCOPE_SUBORDINATE
929 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
932 #ifdef LDAP_SCOPE_SUBORDINATE
936 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
938 printf(_("# requesting: "));
940 if ( attrs == NULL ) {
943 for ( i = 0; attrs[ i ] != NULL; ++i ) {
944 printf( "%s ", attrs[ i ] );
949 printf(_("\n# with manageDSAit %scontrol"),
950 manageDSAit > 1 ? _("critical ") : "" );
953 printf(_("\n# with noop %scontrol"),
954 noop > 1 ? _("critical ") : "" );
957 printf(_("\n# with subentries %scontrol: %s"),
958 subentries < 0 ? _("critical ") : "",
959 abs(subentries) == 1 ? "false" : "true" );
961 if ( valuesReturnFilter ) {
962 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
963 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
965 #ifdef LDAP_CONTROL_PAGEDRESULTS
966 if ( pagedResults ) {
967 printf(_("\n# with pagedResults %scontrol: size=%d"),
968 (pagedResults > 1) ? _("critical ") : "",
973 printf( _("\n#\n\n") );
976 if ( infile == NULL ) {
977 rc = dosearch( ld, base, scope, NULL, filtpattern,
978 attrs, attrsonly, NULL, NULL, NULL, -1 );
983 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
984 line[ strlen( line ) - 1 ] = '\0';
990 rc = dosearch( ld, base, scope, filtpattern, line,
991 attrs, attrsonly, NULL, NULL, NULL, -1 );
998 #ifdef LDAP_CONTROL_PAGEDRESULTS
999 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
1001 int i, moreEntries, tmpSize;
1003 /* Loop to get the next pages when
1004 * enter is pressed on the terminal.
1006 if ( pagePrompt != 0 ) {
1007 if ( entriesLeft > 0 ) {
1008 printf( _("Estimate entries: %d\n"), entriesLeft );
1010 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1013 moreEntries = getchar();
1014 while ( moreEntries != EOF && moreEntries != '\n' ) {
1015 if ( i < (int)sizeof(buf) - 1 ) {
1016 buf[i] = moreEntries;
1019 moreEntries = getchar();
1023 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1024 int num = sscanf( buf, "%d", &tmpSize );
1026 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
1027 return EXIT_FAILURE;
1030 pageSize = (ber_int_t)tmpSize;
1050 static int dosearch(
1058 LDAPControl **sctrls,
1059 LDAPControl **cctrls,
1060 struct timeval *timeout,
1070 LDAPMessage *res, *msg;
1072 char *retoid = NULL;
1073 struct berval *retdata = NULL;
1074 int nresponses_psearch = -1;
1075 int cancel_msgid = -1;
1077 if( filtpatt != NULL ) {
1078 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1079 if( filter == NULL ) {
1081 return EXIT_FAILURE;
1084 sprintf( filter, filtpatt, value );
1087 fprintf( stderr, _("filter: %s\n"), filter );
1091 printf( _("#\n# filter: %s\n#\n"), filter );
1099 return LDAP_SUCCESS;
1102 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1103 sctrls, cctrls, timeout, sizelimit, &msgid );
1105 if ( filtpatt != NULL ) {
1109 if( rc != LDAP_SUCCESS ) {
1110 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1111 prog, ldap_err2string( rc ), rc );
1115 nresponses = nentries = nreferences = nextended = npartial = 0;
1119 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1120 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1123 rc = tool_check_abandon( ld, msgid );
1129 (void) ldap_sort_entries( ld, &res,
1130 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1133 for ( msg = ldap_first_message( ld, res );
1135 msg = ldap_next_message( ld, msg ) )
1137 if ( nresponses++ ) putchar('\n');
1138 if ( nresponses_psearch >= 0 )
1139 nresponses_psearch++;
1141 switch( ldap_msgtype( msg ) ) {
1142 case LDAP_RES_SEARCH_ENTRY:
1144 print_entry( ld, msg, attrsonly );
1147 case LDAP_RES_SEARCH_REFERENCE:
1149 print_reference( ld, msg );
1152 case LDAP_RES_EXTENDED:
1154 print_extended( ld, msg );
1156 if( ldap_msgid( msg ) == 0 ) {
1157 /* unsolicited extended operation */
1161 if ( cancel_msgid != -1 &&
1162 cancel_msgid == ldap_msgid( msg ) ) {
1163 printf(_("Cancelled \n"));
1164 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1169 case LDAP_RES_SEARCH_RESULT:
1170 rc = print_result( ld, msg, 1 );
1171 #ifdef LDAP_CONTROL_PAGEDRESULTS
1172 if ( pageSize != 0 ) {
1173 if ( rc == LDAP_SUCCESS ) {
1174 rc = parse_page_control( ld, msg, &page_cookie );
1176 morePagedResults = 0;
1179 morePagedResults = 0;
1183 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1189 case LDAP_RES_INTERMEDIATE:
1191 ldap_parse_intermediate( ld, msg,
1192 &retoid, &retdata, NULL, 0 );
1194 nresponses_psearch = 0;
1196 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1197 printf(_("SyncInfo Received\n"));
1198 ldap_memfree( retoid );
1199 ber_bvfree( retdata );
1203 print_partial( ld, msg );
1204 ldap_memfree( retoid );
1205 ber_bvfree( retdata );
1209 if ( ldapsync && sync_slimit != -1 &&
1210 nresponses_psearch >= sync_slimit ) {
1211 BerElement *msgidber = NULL;
1212 struct berval *msgidvalp = NULL;
1213 msgidber = ber_alloc_t(LBER_USE_DER);
1214 ber_printf(msgidber, "{i}", msgid);
1215 ber_flatten(msgidber, &msgidvalp);
1216 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1217 msgidvalp, NULL, NULL, &cancel_msgid);
1218 nresponses_psearch = -1;
1222 ldap_msgfree( res );
1227 ldap_perror( ld, "ldap_result" );
1231 ldap_msgfree( res );
1232 #ifdef LDAP_CONTROL_PAGEDRESULTS
1233 if ( pagedResults ) {
1234 npagedresponses += nresponses;
1235 npagedentries += nentries;
1236 npagedextended += nextended;
1237 npagedpartial += npartial;
1238 npagedreferences += nreferences;
1239 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1240 printf( _("\n# numResponses: %d\n"), npagedresponses );
1241 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1242 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1243 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1244 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1249 printf( _("\n# numResponses: %d\n"), nresponses );
1250 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1251 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1252 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1253 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1259 /* This is the proposed new way of doing things.
1260 * It is more efficient, but the API is non-standard.
1269 char tmpfname[ 256 ];
1272 BerElement *ber = NULL;
1273 struct berval bv, *bvals, **bvp = &bvals;
1274 LDAPControl **ctrls = NULL;
1277 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1280 ufn = ldap_dn2ufn( bv.bv_val );
1281 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1283 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1285 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1286 if( rc != LDAP_SUCCESS ) {
1287 fprintf(stderr, _("print_entry: %d\n"), rc );
1288 ldap_perror( ld, "ldap_get_entry_controls" );
1289 exit( EXIT_FAILURE );
1293 print_ctrls( ctrls );
1294 ldap_controls_free( ctrls );
1299 ufn = ldap_dn2ufn( bv.bv_val );
1301 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1304 if( ufn != NULL ) ldap_memfree( ufn );
1306 if ( attrsonly ) bvp = NULL;
1308 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1310 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1312 if (bv.bv_val == NULL) break;
1315 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1317 } else if ( bvals ) {
1318 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1319 if ( vals2tmp > 1 || ( vals2tmp &&
1320 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1323 /* write value to file */
1324 snprintf( tmpfname, sizeof tmpfname,
1325 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1326 tmpdir, bv.bv_val );
1329 tmpfd = mkstemp( tmpfname );
1336 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1341 if ( fwrite( bvals[ i ].bv_val,
1342 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1351 snprintf( url, sizeof url, "%s%s", urlpre,
1352 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1355 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1358 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1359 bvals[ i ].bv_val, bvals[ i ].bv_len );
1362 ber_memfree( bvals );
1371 static void print_reference(
1373 LDAPMessage *reference )
1377 LDAPControl **ctrls;
1380 printf(_("# search reference\n"));
1383 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1385 if( rc != LDAP_SUCCESS ) {
1386 ldap_perror(ld, "ldap_parse_reference");
1387 exit( EXIT_FAILURE );
1392 for( i=0; refs[i] != NULL; i++ ) {
1393 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1394 "ref", refs[i], strlen(refs[i]) );
1396 ber_memvfree( (void **) refs );
1400 print_ctrls( ctrls );
1401 ldap_controls_free( ctrls );
1405 static void print_extended(
1407 LDAPMessage *extended )
1410 char *retoid = NULL;
1411 struct berval *retdata = NULL;
1414 printf(_("# extended result response\n"));
1417 rc = ldap_parse_extended_result( ld, extended,
1418 &retoid, &retdata, 0 );
1420 if( rc != LDAP_SUCCESS ) {
1421 ldap_perror(ld, "ldap_parse_extended_result");
1422 exit( EXIT_FAILURE );
1426 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1427 "extended", retoid, retoid ? strlen(retoid) : 0 );
1429 ber_memfree( retoid );
1433 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1434 "data", retdata->bv_val, retdata->bv_len );
1436 ber_bvfree( retdata );
1439 print_result( ld, extended, 0 );
1442 static void print_partial(
1444 LDAPMessage *partial )
1447 char *retoid = NULL;
1448 struct berval *retdata = NULL;
1449 LDAPControl **ctrls = NULL;
1452 printf(_("# extended partial response\n"));
1455 rc = ldap_parse_intermediate( ld, partial,
1456 &retoid, &retdata, &ctrls, 0 );
1458 if( rc != LDAP_SUCCESS ) {
1459 ldap_perror(ld, "ldap_parse_intermediate");
1460 exit( EXIT_FAILURE );
1464 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1465 "partial", retoid, retoid ? strlen(retoid) : 0 );
1468 ber_memfree( retoid );
1472 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1473 "data", retdata->bv_val, retdata->bv_len );
1476 ber_bvfree( retdata );
1480 print_ctrls( ctrls );
1481 ldap_controls_free( ctrls );
1485 static int print_result(
1487 LDAPMessage *result, int search )
1491 char *matcheddn = NULL;
1494 LDAPControl **ctrls = NULL;
1498 printf(_("# search result\n"));
1501 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1505 rc = ldap_parse_result( ld, result,
1506 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1508 if( rc != LDAP_SUCCESS ) {
1509 ldap_perror(ld, "ldap_parse_result");
1510 exit( EXIT_FAILURE );
1515 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1517 } else if ( err != LDAP_SUCCESS ) {
1518 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1524 write_ldif( LDIF_PUT_VALUE,
1525 "matchedDN", matcheddn, strlen(matcheddn) );
1527 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1531 ber_memfree( matcheddn );
1537 write_ldif( LDIF_PUT_TEXT, "text",
1538 text, strlen(text) );
1540 fprintf( stderr, _("Additional information: %s\n"), text );
1544 ber_memfree( text );
1549 for( i=0; refs[i] != NULL; i++ ) {
1551 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1553 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1557 ber_memvfree( (void **) refs );
1561 print_ctrls( ctrls );
1562 ldap_controls_free( ctrls );
1568 static void print_ctrls(
1569 LDAPControl **ctrls )
1572 for(i=0; ctrls[i] != NULL; i++ ) {
1573 /* control: OID criticality base64value */
1574 struct berval *b64 = NULL;
1579 len += strlen( ctrls[i]->ldctl_oid );
1581 /* add enough for space after OID and the critical value itself */
1582 len += ctrls[i]->ldctl_iscritical
1583 ? sizeof("true") : sizeof("false");
1585 /* convert to base64 */
1586 if( ctrls[i]->ldctl_value.bv_len ) {
1587 b64 = ber_memalloc( sizeof(struct berval) );
1589 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1590 ctrls[i]->ldctl_value.bv_len ) + 1;
1591 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1593 b64->bv_len = lutil_b64_ntop(
1594 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1595 ctrls[i]->ldctl_value.bv_len,
1596 b64->bv_val, b64->bv_len );
1600 len += 1 + b64->bv_len;
1603 str = malloc( len + 1 );
1605 strcpy( str, ": " );
1609 strcat( str, ctrls[i]->ldctl_oid );
1610 strcat( str, ctrls[i]->ldctl_iscritical
1611 ? " true" : " false" );
1615 strcat(str, b64->bv_val );
1619 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1620 "control", str, len );
1629 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1633 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1637 fputs( ldif, stdout );
1638 ber_memfree( ldif );
1644 #ifdef LDAP_CONTROL_PAGEDRESULTS
1648 LDAPMessage *result,
1649 struct berval *cookie )
1653 LDAPControl **ctrl = NULL;
1654 LDAPControl *ctrlp = NULL;
1658 rc = ldap_parse_result( ld, result,
1659 &err, NULL, NULL, NULL, &ctrl, 0 );
1661 if( rc != LDAP_SUCCESS ) {
1662 ldap_perror(ld, "ldap_parse_result");
1663 exit( EXIT_FAILURE );
1666 if ( err != LDAP_SUCCESS ) {
1667 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1671 /* Parse the control value
1672 * searchResult ::= SEQUENCE {
1673 * size INTEGER (0..maxInt),
1674 * -- result set size estimate from server - unused
1675 * cookie OCTET STRING
1679 ber = ber_init( &ctrlp->ldctl_value );
1680 if ( ber == NULL ) {
1681 fprintf( stderr, _("Internal error.\n") );
1682 return EXIT_FAILURE;
1685 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1686 (void) ber_free( ber, 1 );
1688 if( tag == LBER_ERROR ) {
1690 _("Paged results response control could not be decoded.\n") );
1691 return EXIT_FAILURE;
1694 if( entriesLeft < 0 ) {
1696 _("Invalid entries estimate in paged results response.\n") );
1697 return EXIT_FAILURE;
1700 if ( cookie->bv_len == 0 ) {
1701 morePagedResults = 0;
1704 ldap_controls_free( ctrl );
1707 morePagedResults = 0;