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;
218 static int save_nctrls = 0;
226 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
227 if ( tmpc == NULL ) {
230 _("unable to make room for control; out of memory?\n"));
239 is_oid( const char *s )
243 if ( !isdigit( s[ 0 ] ) ) {
247 for ( ; s[ 0 ]; s++ ) {
248 if ( s[ 0 ] == '.' ) {
249 if ( s[ 1 ] == '\0' ) {
256 if ( !isdigit( s[ 0 ] ) ) {
260 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
269 static int parse_page_control(
272 struct berval *cookie );
280 if (*LDAP_DIRSEP != '/') {
281 for (p = url; *p; p++) {
282 if (*p == *LDAP_DIRSEP)
289 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
290 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
293 handle_private_option( int i )
296 char *control, *cvalue, *next;
298 case 'a': /* set alias deref option */
299 if ( strcasecmp( optarg, "never" ) == 0 ) {
300 deref = LDAP_DEREF_NEVER;
301 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
302 deref = LDAP_DEREF_SEARCHING;
303 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
304 deref = LDAP_DEREF_FINDING;
305 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
306 deref = LDAP_DEREF_ALWAYS;
309 _("alias deref should be never, search, find, or always\n") );
313 case 'A': /* retrieve attribute names only -- no values */
316 case 'b': /* search base */
317 base = ber_strdup( optarg );
319 case 'E': /* search extensions */
320 if( protocol == LDAP_VERSION2 ) {
321 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
323 exit( EXIT_FAILURE );
326 /* should be extended to support comma separated list of
327 * [!]key[=value] parameters, e.g. -E !foo,bar=567
332 if( optarg[0] == '!' ) {
337 control = ber_strdup( optarg );
338 if ( (cvalue = strchr( control, '=' )) != NULL ) {
342 if ( strcasecmp( control, "mv" ) == 0 ) {
343 /* ValuesReturnFilter control */
344 if( valuesReturnFilter ) {
346 _("ValuesReturnFilter previously specified\n"));
347 exit( EXIT_FAILURE );
349 valuesReturnFilter= 1 + crit;
351 if ( cvalue == NULL ) {
353 _("missing filter in ValuesReturnFilter control\n"));
354 exit( EXIT_FAILURE );
358 protocol = LDAP_VERSION3;
360 #ifdef LDAP_CONTROL_PAGEDRESULTS
361 } else if ( strcasecmp( control, "pr" ) == 0 ) {
363 /* PagedResults control */
364 if ( pagedResults != 0 ) {
366 _("PagedResultsControl previously specified\n") );
367 exit( EXIT_FAILURE );
370 if( cvalue != NULL ) {
373 promptp = strchr( cvalue, '/' );
374 if ( promptp != NULL ) {
376 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
378 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
382 _("Invalid value for PagedResultsControl,"
383 " %s/%s.\n"), cvalue, promptp );
384 exit( EXIT_FAILURE );
387 num = sscanf( cvalue, "%d", &tmp );
390 _("Invalid value for PagedResultsControl, %s.\n"),
392 exit( EXIT_FAILURE );
395 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
396 exit( EXIT_FAILURE );
398 pageSize = (ber_int_t) tmp;
399 pagedResults = 1 + crit;
402 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
403 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
406 _("domainScope control previously specified\n"));
407 exit( EXIT_FAILURE );
409 if( cvalue != NULL ) {
411 _("domainScope: no control value expected\n") );
415 domainScope = 1 + crit;
418 #ifdef LDAP_CONTROL_SUBENTRIES
419 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
422 _("subentries control previously specified\n"));
423 exit( EXIT_FAILURE );
425 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
427 } else if ( strcasecmp( cvalue, "false") == 0 ) {
431 _("subentries control value \"%s\" invalid\n"),
433 exit( EXIT_FAILURE );
435 if( crit ) subentries *= -1;
438 } else if ( strcasecmp( control, "sync" ) == 0 ) {
442 fprintf( stderr, _("sync control previously specified\n") );
443 exit( EXIT_FAILURE );
445 if ( cvalue == NULL ) {
446 fprintf( stderr, _("missing specification of sync control\n"));
447 exit( EXIT_FAILURE );
449 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
450 ldapsync = LDAP_SYNC_REFRESH_ONLY;
451 cookiep = strchr( cvalue, '/' );
452 if ( cookiep != NULL ) {
454 if ( *cookiep != '\0' ) {
455 ber_str2bv( cookiep, 0, 0, &sync_cookie );
458 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
459 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
460 cookiep = strchr( cvalue, '/' );
461 if ( cookiep != NULL ) {
465 slimitp = strchr( cvalue, '/' );
466 if ( slimitp != NULL ) {
469 if ( cookiep != NULL && *cookiep != '\0' )
470 ber_str2bv( cookiep, 0, 0, &sync_cookie );
471 if ( slimitp != NULL && *slimitp != '\0' ) {
472 ival = strtol( slimitp, &next, 10 );
473 if ( next == NULL || next[0] != '\0' ) {
474 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
475 exit( EXIT_FAILURE );
480 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
482 exit( EXIT_FAILURE );
484 if ( crit ) ldapsync *= -1;
486 } else if ( is_oid( control ) ) {
488 exit( EXIT_FAILURE );
492 c[ nctrls - 1 ].ldctl_oid = control;
495 if ( cvalue == NULL ) {
496 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
497 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
499 } else if ( cvalue[ 0 ] == ':' ) {
507 * to use ldif_parse_line2() */
509 ldif_parse_line2( &cvalue[ -2 ], &type,
514 c[ nctrls - 1 ].ldctl_value = value;
517 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
522 c[ nctrls - 1 ].ldctl_iscritical = crit;
525 fprintf( stderr, _("Invalid search extension name: %s\n"),
530 case 'F': /* uri prefix */
531 if( urlpre ) free( urlpre );
532 urlpre = strdup( optarg );
534 case 'l': /* time limit */
535 if ( strcasecmp( optarg, "none" ) == 0 ) {
538 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
539 timelimit = LDAP_MAXINT;
542 ival = strtol( optarg, &next, 10 );
543 if ( next == NULL || next[0] != '\0' ) {
545 _("Unable to parse time limit \"%s\"\n"), optarg );
546 exit( EXIT_FAILURE );
550 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
551 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
553 exit( EXIT_FAILURE );
556 case 'L': /* print entries in LDIF format */
559 case 's': /* search scope */
560 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
561 scope = LDAP_SCOPE_BASE;
562 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
563 scope = LDAP_SCOPE_ONELEVEL;
564 #ifdef LDAP_SCOPE_SUBORDINATE
565 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
566 || ( strcasecmp( optarg, "children" ) == 0 ))
568 scope = LDAP_SCOPE_SUBORDINATE;
570 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
571 scope = LDAP_SCOPE_SUBTREE;
573 fprintf( stderr, _("scope should be base, one, or sub\n") );
577 case 'S': /* sort attribute */
578 sortattr = strdup( optarg );
580 case 't': /* write attribute values to TMPDIR files */
583 case 'T': /* tmpdir */
584 if( tmpdir ) free( tmpdir );
585 tmpdir = strdup( optarg );
587 case 'u': /* include UFN */
590 case 'z': /* size limit */
591 if ( strcasecmp( optarg, "none" ) == 0 ) {
594 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
595 sizelimit = LDAP_MAXINT;
598 ival = strtol( optarg, &next, 10 );
599 if ( next == NULL || next[0] != '\0' ) {
601 _("Unable to parse size limit \"%s\"\n"), optarg );
602 exit( EXIT_FAILURE );
606 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
607 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
609 exit( EXIT_FAILURE );
620 private_conn_setup( LDAP *ld )
623 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
624 != LDAP_OPT_SUCCESS )
626 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
627 exit( EXIT_FAILURE );
630 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
631 != LDAP_OPT_SUCCESS )
634 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
635 exit( EXIT_FAILURE );
638 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
639 != LDAP_OPT_SUCCESS )
642 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
643 exit( EXIT_FAILURE );
648 main( int argc, char **argv )
650 char *filtpattern, **attrs = NULL, line[BUFSIZ];
654 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
656 BerElement *syncber = NULL;
657 struct berval *syncbvalp = NULL;
661 #ifdef LDAP_CONTROL_PAGEDRESULTS
662 npagedresponses = npagedentries = npagedreferences =
663 npagedextended = npagedpartial = 0;
666 prog = lutil_progname( "ldapsearch", argc, argv );
668 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
669 (def_tmpdir = getenv("TMP")) == NULL &&
670 (def_tmpdir = getenv("TEMP")) == NULL )
672 def_tmpdir = LDAP_TMPDIR;
676 def_tmpdir = LDAP_TMPDIR;
678 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
680 if( def_urlpre == NULL ) {
685 sprintf( def_urlpre, "file:///%s/",
686 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
688 urlize( def_urlpre );
690 tool_args( argc, argv );
692 if (( argc - optind < 1 ) ||
693 ( *argv[optind] != '(' /*')'*/ &&
694 ( strchr( argv[optind], '=' ) == NULL ) ) )
696 filtpattern = "(objectclass=*)";
698 filtpattern = argv[optind++];
701 if ( argv[optind] != NULL ) {
702 attrs = &argv[optind];
705 if ( infile != NULL ) {
706 if ( infile[0] == '-' && infile[1] == '\0' ) {
708 } else if (( fp = fopen( infile, "r" )) == NULL ) {
714 if ( tmpdir == NULL ) {
717 if ( urlpre == NULL )
721 if( urlpre == NULL ) {
722 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
724 if( urlpre == NULL ) {
729 sprintf( urlpre, "file:///%s/",
730 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
738 ld = tool_conn_setup( 0, &private_conn_setup );
740 if ( pw_file || want_bindpw ) {
742 rc = lutil_get_filed_password( pw_file, &passwd );
743 if( rc ) return EXIT_FAILURE;
745 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
746 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
753 if ( nctrls > 0 || assertion || authzid || manageDSAit || noop
754 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
757 #ifdef LDAP_CONTROL_PAGEDRESULTS
760 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
762 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
764 || subentries || valuesReturnFilter )
768 save_nctrls = nctrls;
770 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
776 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
777 c[i].ldctl_value.bv_val = NULL;
778 c[i].ldctl_value.bv_len = 0;
779 c[i].ldctl_iscritical = domainScope > 1;
784 #ifdef LDAP_CONTROL_SUBENTRIES
790 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
794 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
796 ber_free( seber, 1 );
797 fprintf( stderr, _("Subentries control encoding error!\n") );
801 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
805 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
806 c[i].ldctl_iscritical = subentries < 1;
816 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
820 if ( sync_cookie.bv_len == 0 ) {
821 err = ber_printf( syncber, "{e}", abs(ldapsync) );
823 err = ber_printf( syncber, "{eO}", abs(ldapsync),
827 if ( err == LBER_ERROR ) {
828 ber_free( syncber, 1 );
829 fprintf( stderr, _("ldap sync control encoding error!\n") );
833 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
837 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
838 c[i].ldctl_value = (*syncbvalp);
839 c[i].ldctl_iscritical = ldapsync < 0;
843 if ( valuesReturnFilter ) {
848 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
852 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
853 ber_free( vrber, 1 );
854 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
858 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
862 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
863 c[i].ldctl_iscritical = valuesReturnFilter > 1;
867 #ifdef LDAP_CONTROL_PAGEDRESULTS
868 if ( pagedResults ) {
873 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
877 ber_printf( prber, "{iO}", pageSize, &page_cookie );
878 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
881 if ( page_cookie.bv_val != NULL ) {
882 ber_memfree( page_cookie.bv_val );
883 page_cookie.bv_val = NULL;
886 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
887 c[i].ldctl_iscritical = pagedResults > 1;
892 tool_server_controls( ld, c, i );
894 /* step back to the original number of controls, so that
895 * those set while parsing args are preserved */
896 nctrls = save_nctrls;
898 #ifdef LDAP_CONTROL_SUBENTRIES
899 ber_free( seber, 1 );
901 ber_free( vrber, 1 );
902 #ifdef LDAP_CONTROL_PAGEDRESULTS
903 ber_free( prber, 1 );
908 fprintf( stderr, _("filter%s: %s\nrequesting: "),
909 infile != NULL ? _(" pattern") : "",
912 if ( attrs == NULL ) {
913 fprintf( stderr, _("ALL") );
915 for ( i = 0; attrs[ i ] != NULL; ++i ) {
916 fprintf( stderr, "%s ", attrs[ i ] );
919 fprintf( stderr, "\n" );
923 printf( _("# extended LDIF\n") );
924 } else if ( ldif < 3 ) {
925 printf( _("version: %d\n\n"), 1 );
930 printf(_("# LDAPv%d\n"), protocol);
931 printf(_("# base <%s> with scope %s\n"),
933 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
934 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
935 #ifdef LDAP_SCOPE_SUBORDINATE
936 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
939 #ifdef LDAP_SCOPE_SUBORDINATE
943 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
945 printf(_("# requesting: "));
947 if ( attrs == NULL ) {
950 for ( i = 0; attrs[ i ] != NULL; ++i ) {
951 printf( "%s ", attrs[ i ] );
956 printf(_("\n# with manageDSAit %scontrol"),
957 manageDSAit > 1 ? _("critical ") : "" );
960 printf(_("\n# with noop %scontrol"),
961 noop > 1 ? _("critical ") : "" );
964 printf(_("\n# with subentries %scontrol: %s"),
965 subentries < 0 ? _("critical ") : "",
966 abs(subentries) == 1 ? "false" : "true" );
968 if ( valuesReturnFilter ) {
969 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
970 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
972 #ifdef LDAP_CONTROL_PAGEDRESULTS
973 if ( pagedResults ) {
974 printf(_("\n# with pagedResults %scontrol: size=%d"),
975 (pagedResults > 1) ? _("critical ") : "",
980 printf( _("\n#\n\n") );
983 if ( infile == NULL ) {
984 rc = dosearch( ld, base, scope, NULL, filtpattern,
985 attrs, attrsonly, NULL, NULL, NULL, -1 );
990 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
991 line[ strlen( line ) - 1 ] = '\0';
997 rc = dosearch( ld, base, scope, filtpattern, line,
998 attrs, attrsonly, NULL, NULL, NULL, -1 );
1000 if ( fp != stdin ) {
1005 #ifdef LDAP_CONTROL_PAGEDRESULTS
1006 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
1008 int i, moreEntries, tmpSize;
1010 /* Loop to get the next pages when
1011 * enter is pressed on the terminal.
1013 if ( pagePrompt != 0 ) {
1014 if ( entriesLeft > 0 ) {
1015 printf( _("Estimate entries: %d\n"), entriesLeft );
1017 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1020 moreEntries = getchar();
1021 while ( moreEntries != EOF && moreEntries != '\n' ) {
1022 if ( i < (int)sizeof(buf) - 1 ) {
1023 buf[i] = moreEntries;
1026 moreEntries = getchar();
1030 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1031 int num = sscanf( buf, "%d", &tmpSize );
1033 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
1034 return EXIT_FAILURE;
1037 pageSize = (ber_int_t)tmpSize;
1049 for ( ; save_nctrls-- > 0; ) {
1050 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1060 static int dosearch(
1068 LDAPControl **sctrls,
1069 LDAPControl **cctrls,
1070 struct timeval *timeout,
1080 LDAPMessage *res, *msg;
1082 char *retoid = NULL;
1083 struct berval *retdata = NULL;
1084 int nresponses_psearch = -1;
1085 int cancel_msgid = -1;
1087 if( filtpatt != NULL ) {
1088 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1089 if( filter == NULL ) {
1091 return EXIT_FAILURE;
1094 sprintf( filter, filtpatt, value );
1097 fprintf( stderr, _("filter: %s\n"), filter );
1101 printf( _("#\n# filter: %s\n#\n"), filter );
1109 return LDAP_SUCCESS;
1112 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1113 sctrls, cctrls, timeout, sizelimit, &msgid );
1115 if ( filtpatt != NULL ) {
1119 if( rc != LDAP_SUCCESS ) {
1120 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1121 prog, ldap_err2string( rc ), rc );
1125 nresponses = nentries = nreferences = nextended = npartial = 0;
1129 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1130 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1133 rc = tool_check_abandon( ld, msgid );
1139 (void) ldap_sort_entries( ld, &res,
1140 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1143 for ( msg = ldap_first_message( ld, res );
1145 msg = ldap_next_message( ld, msg ) )
1147 if ( nresponses++ ) putchar('\n');
1148 if ( nresponses_psearch >= 0 )
1149 nresponses_psearch++;
1151 switch( ldap_msgtype( msg ) ) {
1152 case LDAP_RES_SEARCH_ENTRY:
1154 print_entry( ld, msg, attrsonly );
1157 case LDAP_RES_SEARCH_REFERENCE:
1159 print_reference( ld, msg );
1162 case LDAP_RES_EXTENDED:
1164 print_extended( ld, msg );
1166 if( ldap_msgid( msg ) == 0 ) {
1167 /* unsolicited extended operation */
1171 if ( cancel_msgid != -1 &&
1172 cancel_msgid == ldap_msgid( msg ) ) {
1173 printf(_("Cancelled \n"));
1174 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1179 case LDAP_RES_SEARCH_RESULT:
1180 rc = print_result( ld, msg, 1 );
1181 #ifdef LDAP_CONTROL_PAGEDRESULTS
1182 if ( pageSize != 0 ) {
1183 if ( rc == LDAP_SUCCESS ) {
1184 rc = parse_page_control( ld, msg, &page_cookie );
1186 morePagedResults = 0;
1189 morePagedResults = 0;
1193 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1199 case LDAP_RES_INTERMEDIATE:
1201 ldap_parse_intermediate( ld, msg,
1202 &retoid, &retdata, NULL, 0 );
1204 nresponses_psearch = 0;
1206 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1207 printf(_("SyncInfo Received\n"));
1208 ldap_memfree( retoid );
1209 ber_bvfree( retdata );
1213 print_partial( ld, msg );
1214 ldap_memfree( retoid );
1215 ber_bvfree( retdata );
1219 if ( ldapsync && sync_slimit != -1 &&
1220 nresponses_psearch >= sync_slimit ) {
1221 BerElement *msgidber = NULL;
1222 struct berval *msgidvalp = NULL;
1223 msgidber = ber_alloc_t(LBER_USE_DER);
1224 ber_printf(msgidber, "{i}", msgid);
1225 ber_flatten(msgidber, &msgidvalp);
1226 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1227 msgidvalp, NULL, NULL, &cancel_msgid);
1228 nresponses_psearch = -1;
1232 ldap_msgfree( res );
1237 ldap_perror( ld, "ldap_result" );
1241 ldap_msgfree( res );
1242 #ifdef LDAP_CONTROL_PAGEDRESULTS
1243 if ( pagedResults ) {
1244 npagedresponses += nresponses;
1245 npagedentries += nentries;
1246 npagedextended += nextended;
1247 npagedpartial += npartial;
1248 npagedreferences += nreferences;
1249 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1250 printf( _("\n# numResponses: %d\n"), npagedresponses );
1251 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1252 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1253 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1254 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1259 printf( _("\n# numResponses: %d\n"), nresponses );
1260 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1261 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1262 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1263 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1269 /* This is the proposed new way of doing things.
1270 * It is more efficient, but the API is non-standard.
1279 char tmpfname[ 256 ];
1282 BerElement *ber = NULL;
1283 struct berval bv, *bvals, **bvp = &bvals;
1284 LDAPControl **ctrls = NULL;
1287 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1290 ufn = ldap_dn2ufn( bv.bv_val );
1291 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1293 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1295 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1296 if( rc != LDAP_SUCCESS ) {
1297 fprintf(stderr, _("print_entry: %d\n"), rc );
1298 ldap_perror( ld, "ldap_get_entry_controls" );
1299 exit( EXIT_FAILURE );
1303 print_ctrls( ctrls );
1304 ldap_controls_free( ctrls );
1309 ufn = ldap_dn2ufn( bv.bv_val );
1311 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1314 if( ufn != NULL ) ldap_memfree( ufn );
1316 if ( attrsonly ) bvp = NULL;
1318 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1320 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1322 if (bv.bv_val == NULL) break;
1325 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1327 } else if ( bvals ) {
1328 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1329 if ( vals2tmp > 1 || ( vals2tmp &&
1330 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1333 /* write value to file */
1334 snprintf( tmpfname, sizeof tmpfname,
1335 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1336 tmpdir, bv.bv_val );
1339 tmpfd = mkstemp( tmpfname );
1346 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1351 if ( fwrite( bvals[ i ].bv_val,
1352 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1361 snprintf( url, sizeof url, "%s%s", urlpre,
1362 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1365 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1368 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1369 bvals[ i ].bv_val, bvals[ i ].bv_len );
1372 ber_memfree( bvals );
1381 static void print_reference(
1383 LDAPMessage *reference )
1387 LDAPControl **ctrls;
1390 printf(_("# search reference\n"));
1393 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1395 if( rc != LDAP_SUCCESS ) {
1396 ldap_perror(ld, "ldap_parse_reference");
1397 exit( EXIT_FAILURE );
1402 for( i=0; refs[i] != NULL; i++ ) {
1403 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1404 "ref", refs[i], strlen(refs[i]) );
1406 ber_memvfree( (void **) refs );
1410 print_ctrls( ctrls );
1411 ldap_controls_free( ctrls );
1415 static void print_extended(
1417 LDAPMessage *extended )
1420 char *retoid = NULL;
1421 struct berval *retdata = NULL;
1424 printf(_("# extended result response\n"));
1427 rc = ldap_parse_extended_result( ld, extended,
1428 &retoid, &retdata, 0 );
1430 if( rc != LDAP_SUCCESS ) {
1431 ldap_perror(ld, "ldap_parse_extended_result");
1432 exit( EXIT_FAILURE );
1436 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1437 "extended", retoid, retoid ? strlen(retoid) : 0 );
1439 ber_memfree( retoid );
1443 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1444 "data", retdata->bv_val, retdata->bv_len );
1446 ber_bvfree( retdata );
1449 print_result( ld, extended, 0 );
1452 static void print_partial(
1454 LDAPMessage *partial )
1457 char *retoid = NULL;
1458 struct berval *retdata = NULL;
1459 LDAPControl **ctrls = NULL;
1462 printf(_("# extended partial response\n"));
1465 rc = ldap_parse_intermediate( ld, partial,
1466 &retoid, &retdata, &ctrls, 0 );
1468 if( rc != LDAP_SUCCESS ) {
1469 ldap_perror(ld, "ldap_parse_intermediate");
1470 exit( EXIT_FAILURE );
1474 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1475 "partial", retoid, retoid ? strlen(retoid) : 0 );
1478 ber_memfree( retoid );
1482 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1483 "data", retdata->bv_val, retdata->bv_len );
1486 ber_bvfree( retdata );
1490 print_ctrls( ctrls );
1491 ldap_controls_free( ctrls );
1495 static int print_result(
1497 LDAPMessage *result, int search )
1501 char *matcheddn = NULL;
1504 LDAPControl **ctrls = NULL;
1508 printf(_("# search result\n"));
1511 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1515 rc = ldap_parse_result( ld, result,
1516 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1518 if( rc != LDAP_SUCCESS ) {
1519 ldap_perror(ld, "ldap_parse_result");
1520 exit( EXIT_FAILURE );
1525 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1527 } else if ( err != LDAP_SUCCESS ) {
1528 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1534 write_ldif( LDIF_PUT_VALUE,
1535 "matchedDN", matcheddn, strlen(matcheddn) );
1537 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1541 ber_memfree( matcheddn );
1547 write_ldif( LDIF_PUT_TEXT, "text",
1548 text, strlen(text) );
1550 fprintf( stderr, _("Additional information: %s\n"), text );
1554 ber_memfree( text );
1559 for( i=0; refs[i] != NULL; i++ ) {
1561 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1563 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1567 ber_memvfree( (void **) refs );
1571 print_ctrls( ctrls );
1572 ldap_controls_free( ctrls );
1578 static void print_ctrls(
1579 LDAPControl **ctrls )
1582 for(i=0; ctrls[i] != NULL; i++ ) {
1583 /* control: OID criticality base64value */
1584 struct berval *b64 = NULL;
1589 len += strlen( ctrls[i]->ldctl_oid );
1591 /* add enough for space after OID and the critical value itself */
1592 len += ctrls[i]->ldctl_iscritical
1593 ? sizeof("true") : sizeof("false");
1595 /* convert to base64 */
1596 if( ctrls[i]->ldctl_value.bv_len ) {
1597 b64 = ber_memalloc( sizeof(struct berval) );
1599 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1600 ctrls[i]->ldctl_value.bv_len ) + 1;
1601 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1603 b64->bv_len = lutil_b64_ntop(
1604 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1605 ctrls[i]->ldctl_value.bv_len,
1606 b64->bv_val, b64->bv_len );
1610 len += 1 + b64->bv_len;
1613 str = malloc( len + 1 );
1615 strcpy( str, ": " );
1619 strcat( str, ctrls[i]->ldctl_oid );
1620 strcat( str, ctrls[i]->ldctl_iscritical
1621 ? " true" : " false" );
1625 strcat(str, b64->bv_val );
1629 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1630 "control", str, len );
1639 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1643 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1647 fputs( ldif, stdout );
1648 ber_memfree( ldif );
1654 #ifdef LDAP_CONTROL_PAGEDRESULTS
1658 LDAPMessage *result,
1659 struct berval *cookie )
1663 LDAPControl **ctrl = NULL;
1664 LDAPControl *ctrlp = NULL;
1668 rc = ldap_parse_result( ld, result,
1669 &err, NULL, NULL, NULL, &ctrl, 0 );
1671 if( rc != LDAP_SUCCESS ) {
1672 ldap_perror(ld, "ldap_parse_result");
1673 exit( EXIT_FAILURE );
1676 if ( err != LDAP_SUCCESS ) {
1677 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1681 /* Parse the control value
1682 * searchResult ::= SEQUENCE {
1683 * size INTEGER (0..maxInt),
1684 * -- result set size estimate from server - unused
1685 * cookie OCTET STRING
1689 ber = ber_init( &ctrlp->ldctl_value );
1690 if ( ber == NULL ) {
1691 fprintf( stderr, _("Internal error.\n") );
1692 return EXIT_FAILURE;
1695 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1696 (void) ber_free( ber, 1 );
1698 if( tag == LBER_ERROR ) {
1700 _("Paged results response control could not be decoded.\n") );
1701 return EXIT_FAILURE;
1704 if( entriesLeft < 0 ) {
1706 _("Invalid entries estimate in paged results response.\n") );
1707 return EXIT_FAILURE;
1710 if ( cookie->bv_len == 0 ) {
1711 morePagedResults = 0;
1714 ldap_controls_free( ctrl );
1717 morePagedResults = 0;