1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2006 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"
76 * NOTE: we use this deprecated function only because
77 * we want ldapsearch to provide some client-side sorting
81 typedef int (LDAP_SORT_AD_CMP_PROC) LDAP_P(( /* deprecated */
82 LDAP_CONST char *left,
83 LDAP_CONST char *right ));
85 LDAP_F( int ) /* deprecated */
86 ldap_sort_entries LDAP_P(( LDAP *ld,
88 LDAP_CONST char *attr,
89 LDAP_SORT_AD_CMP_PROC *cmp ));
92 static int scope = LDAP_SCOPE_SUBTREE;
93 static int deref = -1;
95 static int timelimit = -1;
96 static int sizelimit = -1;
98 static char *def_tmpdir;
99 static char *def_urlpre;
101 #if defined(__CYGWIN__) || defined(__MINGW32__)
102 /* Turn off commandline globbing, otherwise you cannot search for
111 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
112 fprintf( stderr, _(" filter\tRFC 4515 compliant LDAP search filter\n"));
113 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
114 fprintf( stderr, _(" which may include:\n"));
115 fprintf( stderr, _(" 1.1 no attributes\n"));
116 fprintf( stderr, _(" * all user attributes\n"));
117 fprintf( stderr, _(" + all operational attributes\n"));
120 fprintf( stderr, _("Search options:\n"));
121 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
122 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
123 fprintf( stderr, _(" -b basedn base dn for search\n"));
124 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
125 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
126 fprintf( stderr, _(" !dontUseCopy (Don't Use Copy)\n"));
127 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
128 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
129 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
130 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
131 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
132 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
133 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
134 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
135 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
136 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
137 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
138 fprintf( stderr, _(" and version\n"));
139 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
140 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
141 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
142 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
143 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
144 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
145 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
147 exit( EXIT_FAILURE );
150 static void print_entry LDAP_P((
155 static void print_reference(
157 LDAPMessage *reference );
159 static void print_extended(
161 LDAPMessage *extended );
163 static void print_partial(
165 LDAPMessage *partial );
167 static int print_result(
172 static int dosearch LDAP_P((
180 LDAPControl **sctrls,
181 LDAPControl **cctrls,
182 struct timeval *timeout,
185 static char *tmpdir = NULL;
186 static char *urlpre = NULL;
187 static char *base = NULL;
188 static char *sortattr = NULL;
189 static int includeufn, vals2tmp = 0;
191 static int subentries = 0, valuesReturnFilter = 0;
192 static char *vrFilter = NULL;
194 #ifdef LDAP_CONTROL_DONTUSECOPY
195 static int dontUseCopy = 0;
198 static int domainScope = 0;
200 static int ldapsync = 0;
201 static struct berval sync_cookie = { 0, NULL };
202 static int sync_slimit = -1;
204 /* cookie and morePagedResults moved to common.c */
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 int npagedresponses;
210 static int npagedentries;
211 static int npagedreferences;
212 static int npagedextended;
213 static int npagedpartial;
215 static LDAPControl *c = NULL;
216 static int nctrls = 0;
217 static int save_nctrls = 0;
225 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
226 if ( tmpc == NULL ) {
229 _("unable to make room for control; out of memory?\n"));
242 if (*LDAP_DIRSEP != '/') {
243 for (p = url; *p; p++) {
244 if (*p == *LDAP_DIRSEP)
251 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
252 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
255 handle_private_option( int i )
258 char *control, *cvalue, *next;
260 case 'a': /* set alias deref option */
261 if ( strcasecmp( optarg, "never" ) == 0 ) {
262 deref = LDAP_DEREF_NEVER;
263 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
264 deref = LDAP_DEREF_SEARCHING;
265 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
266 deref = LDAP_DEREF_FINDING;
267 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
268 deref = LDAP_DEREF_ALWAYS;
271 _("alias deref should be never, search, find, or always\n") );
275 case 'A': /* retrieve attribute names only -- no values */
278 case 'b': /* search base */
279 base = ber_strdup( optarg );
281 case 'E': /* search extensions */
282 if( protocol == LDAP_VERSION2 ) {
283 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
285 exit( EXIT_FAILURE );
288 /* should be extended to support comma separated list of
289 * [!]key[=value] parameters, e.g. -E !foo,bar=567
294 if( optarg[0] == '!' ) {
299 control = ber_strdup( optarg );
300 if ( (cvalue = strchr( control, '=' )) != NULL ) {
304 if ( strcasecmp( control, "mv" ) == 0 ) {
305 /* ValuesReturnFilter control */
306 if( valuesReturnFilter ) {
308 _("ValuesReturnFilter previously specified\n"));
309 exit( EXIT_FAILURE );
311 valuesReturnFilter= 1 + crit;
313 if ( cvalue == NULL ) {
315 _("missing filter in ValuesReturnFilter control\n"));
316 exit( EXIT_FAILURE );
320 protocol = LDAP_VERSION3;
322 } else if ( strcasecmp( control, "pr" ) == 0 ) {
324 /* PagedResults control */
325 if ( pagedResults != 0 ) {
327 _("PagedResultsControl previously specified\n") );
328 exit( EXIT_FAILURE );
331 if( cvalue != NULL ) {
334 promptp = strchr( cvalue, '/' );
335 if ( promptp != NULL ) {
337 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
339 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
343 _("Invalid value for PagedResultsControl,"
344 " %s/%s.\n"), cvalue, promptp );
345 exit( EXIT_FAILURE );
348 num = sscanf( cvalue, "%d", &tmp );
351 _("Invalid value for PagedResultsControl, %s.\n"),
353 exit( EXIT_FAILURE );
356 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
357 exit( EXIT_FAILURE );
359 pageSize = (ber_int_t) tmp;
360 pagedResults = 1 + crit;
362 #ifdef LDAP_CONTROL_DONTUSECOPY
363 } else if ( strcasecmp( control, "dontUseCopy" ) == 0 ) {
366 _("dontUseCopy control previously specified\n"));
367 exit( EXIT_FAILURE );
369 if( cvalue != NULL ) {
371 _("dontUseCopy: no control value expected\n") );
376 _("dontUseCopy: critical flag required\n") );
380 dontUseCopy = 1 + crit;
382 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
385 _("domainScope control previously specified\n"));
386 exit( EXIT_FAILURE );
388 if( cvalue != NULL ) {
390 _("domainScope: no control value expected\n") );
394 domainScope = 1 + crit;
396 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
399 _("subentries control previously specified\n"));
400 exit( EXIT_FAILURE );
402 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
404 } else if ( strcasecmp( cvalue, "false") == 0 ) {
408 _("subentries control value \"%s\" invalid\n"),
410 exit( EXIT_FAILURE );
412 if( crit ) subentries *= -1;
414 } else if ( strcasecmp( control, "sync" ) == 0 ) {
418 fprintf( stderr, _("sync control previously specified\n") );
419 exit( EXIT_FAILURE );
421 if ( cvalue == NULL ) {
422 fprintf( stderr, _("missing specification of sync control\n"));
423 exit( EXIT_FAILURE );
425 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
426 ldapsync = LDAP_SYNC_REFRESH_ONLY;
427 cookiep = strchr( cvalue, '/' );
428 if ( cookiep != NULL ) {
430 if ( *cookiep != '\0' ) {
431 ber_str2bv( cookiep, 0, 0, &sync_cookie );
434 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
435 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
436 cookiep = strchr( cvalue, '/' );
437 if ( cookiep != NULL ) {
441 slimitp = strchr( cvalue, '/' );
442 if ( slimitp != NULL ) {
445 if ( cookiep != NULL && *cookiep != '\0' )
446 ber_str2bv( cookiep, 0, 0, &sync_cookie );
447 if ( slimitp != NULL && *slimitp != '\0' ) {
448 ival = strtol( slimitp, &next, 10 );
449 if ( next == NULL || next[0] != '\0' ) {
450 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
451 exit( EXIT_FAILURE );
456 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
458 exit( EXIT_FAILURE );
460 if ( crit ) ldapsync *= -1;
462 } else if ( tool_is_oid( control ) ) {
464 exit( EXIT_FAILURE );
468 c[ nctrls - 1 ].ldctl_oid = control;
471 if ( cvalue == NULL ) {
472 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
473 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
475 } else if ( cvalue[ 0 ] == ':' ) {
483 * to use ldif_parse_line2() */
485 ldif_parse_line2( &cvalue[ -2 ], &type,
490 c[ nctrls - 1 ].ldctl_value = value;
493 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
498 c[ nctrls - 1 ].ldctl_iscritical = crit;
501 fprintf( stderr, _("Invalid search extension name: %s\n"),
506 case 'F': /* uri prefix */
507 if( urlpre ) free( urlpre );
508 urlpre = strdup( optarg );
510 case 'l': /* time limit */
511 if ( strcasecmp( optarg, "none" ) == 0 ) {
514 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
515 timelimit = LDAP_MAXINT;
518 ival = strtol( optarg, &next, 10 );
519 if ( next == NULL || next[0] != '\0' ) {
521 _("Unable to parse time limit \"%s\"\n"), optarg );
522 exit( EXIT_FAILURE );
526 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
527 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
529 exit( EXIT_FAILURE );
532 case 'L': /* print entries in LDIF format */
535 case 's': /* search scope */
536 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
537 scope = LDAP_SCOPE_BASE;
538 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
539 scope = LDAP_SCOPE_ONELEVEL;
540 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
541 || ( strcasecmp( optarg, "children" ) == 0 ))
543 scope = LDAP_SCOPE_SUBORDINATE;
544 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
545 scope = LDAP_SCOPE_SUBTREE;
547 fprintf( stderr, _("scope should be base, one, or sub\n") );
551 case 'S': /* sort attribute */
552 sortattr = strdup( optarg );
554 case 't': /* write attribute values to TMPDIR files */
557 case 'T': /* tmpdir */
558 if( tmpdir ) free( tmpdir );
559 tmpdir = strdup( optarg );
561 case 'u': /* include UFN */
564 case 'z': /* size limit */
565 if ( strcasecmp( optarg, "none" ) == 0 ) {
568 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
569 sizelimit = LDAP_MAXINT;
572 ival = strtol( optarg, &next, 10 );
573 if ( next == NULL || next[0] != '\0' ) {
575 _("Unable to parse size limit \"%s\"\n"), optarg );
576 exit( EXIT_FAILURE );
580 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
581 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
583 exit( EXIT_FAILURE );
594 private_conn_setup( LDAP *ld )
597 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
598 != LDAP_OPT_SUCCESS )
600 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
601 exit( EXIT_FAILURE );
604 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
605 != LDAP_OPT_SUCCESS )
608 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
609 exit( EXIT_FAILURE );
612 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
613 != LDAP_OPT_SUCCESS )
616 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
617 exit( EXIT_FAILURE );
622 main( int argc, char **argv )
624 char *filtpattern, **attrs = NULL, line[BUFSIZ];
628 BerElement *seber = NULL, *vrber = NULL;
630 BerElement *syncber = NULL;
631 struct berval *syncbvalp = NULL;
634 tool_init( TOOL_SEARCH );
636 npagedresponses = npagedentries = npagedreferences =
637 npagedextended = npagedpartial = 0;
639 prog = lutil_progname( "ldapsearch", argc, argv );
641 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
642 (def_tmpdir = getenv("TMP")) == NULL &&
643 (def_tmpdir = getenv("TEMP")) == NULL )
645 def_tmpdir = LDAP_TMPDIR;
649 def_tmpdir = LDAP_TMPDIR;
651 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
653 if( def_urlpre == NULL ) {
658 sprintf( def_urlpre, "file:///%s/",
659 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
661 urlize( def_urlpre );
663 tool_args( argc, argv );
665 if (( argc - optind < 1 ) ||
666 ( *argv[optind] != '(' /*')'*/ &&
667 ( strchr( argv[optind], '=' ) == NULL ) ) )
669 filtpattern = "(objectclass=*)";
671 filtpattern = argv[optind++];
674 if ( argv[optind] != NULL ) {
675 attrs = &argv[optind];
678 if ( infile != NULL ) {
681 if ( infile[0] == '-' && infile[1] == '\0' ) {
683 } else if (( fp = fopen( infile, "r" )) == NULL ) {
688 for( i=0 ; filtpattern[i] ; i++ ) {
689 if( filtpattern[i] == '%' ) {
691 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
698 if( filtpattern[i+1] != 's' ) {
699 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
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 save_nctrls = nctrls;
749 #ifdef LDAP_CONTROL_DONTUSECOPY
756 || valuesReturnFilter )
759 #ifdef LDAP_CONTROL_DONTUSECOPY
765 c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
766 c[i].ldctl_value.bv_val = NULL;
767 c[i].ldctl_value.bv_len = 0;
768 c[i].ldctl_iscritical = dontUseCopy > 1;
778 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
779 c[i].ldctl_value.bv_val = NULL;
780 c[i].ldctl_value.bv_len = 0;
781 c[i].ldctl_iscritical = domainScope > 1;
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;
815 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
819 if ( sync_cookie.bv_len == 0 ) {
820 err = ber_printf( syncber, "{e}", abs(ldapsync) );
822 err = ber_printf( syncber, "{eO}", abs(ldapsync),
826 if ( err == LBER_ERROR ) {
827 ber_free( syncber, 1 );
828 fprintf( stderr, _("ldap sync control encoding error!\n") );
832 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
836 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
837 c[i].ldctl_value = (*syncbvalp);
838 c[i].ldctl_iscritical = ldapsync < 0;
842 if ( valuesReturnFilter ) {
847 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
851 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
852 ber_free( vrber, 1 );
853 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
857 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
861 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
862 c[i].ldctl_iscritical = valuesReturnFilter > 1;
866 if ( pagedResults ) {
871 if ( ldap_create_page_control_value( ld,
872 pageSize, &pr_cookie, &c[i].ldctl_value ) )
877 if ( pr_cookie.bv_val != NULL ) {
878 ber_memfree( pr_cookie.bv_val );
879 pr_cookie.bv_val = NULL;
880 pr_cookie.bv_len = 0;
883 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
884 c[i].ldctl_iscritical = pagedResults > 1;
889 tool_server_controls( ld, c, i );
891 ber_free( seber, 1 );
892 ber_free( vrber, 1 );
894 /* step back to the original number of controls, so that
895 * those set while parsing args are preserved */
896 nctrls = save_nctrls;
899 fprintf( stderr, _("filter%s: %s\nrequesting: "),
900 infile != NULL ? _(" pattern") : "",
903 if ( attrs == NULL ) {
904 fprintf( stderr, _("All userApplication attributes") );
906 for ( i = 0; attrs[ i ] != NULL; ++i ) {
907 fprintf( stderr, "%s ", attrs[ i ] );
910 fprintf( stderr, "\n" );
914 printf( _("# extended LDIF\n") );
915 } else if ( ldif < 3 ) {
916 printf( _("version: %d\n\n"), 1 );
920 char *realbase = base;
922 if ( realbase == NULL ) {
923 ldap_get_option( ld, LDAP_OPT_DEFBASE, (void **)&realbase );
927 printf(_("# LDAPv%d\n"), protocol);
928 printf(_("# base <%s>%s with scope %s\n"),
929 realbase ? realbase : "",
930 ( realbase == NULL || realbase != base ) ? " (default)" : "",
931 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
932 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
933 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
935 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
937 printf(_("# requesting: "));
939 if ( attrs == NULL ) {
942 for ( i = 0; attrs[ i ] != NULL; ++i ) {
943 printf( "%s ", attrs[ i ] );
948 printf(_("\n# with manageDSAit %scontrol"),
949 manageDSAit > 1 ? _("critical ") : "" );
952 printf(_("\n# with noop %scontrol"),
953 noop > 1 ? _("critical ") : "" );
956 printf(_("\n# with subentries %scontrol: %s"),
957 subentries < 0 ? _("critical ") : "",
958 abs(subentries) == 1 ? "false" : "true" );
960 if ( valuesReturnFilter ) {
961 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
962 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
964 if ( pagedResults ) {
965 printf(_("\n# with pagedResults %scontrol: size=%d"),
966 (pagedResults > 1) ? _("critical ") : "",
970 printf( _("\n#\n\n") );
972 if ( realbase && realbase != base ) {
973 ldap_memfree( realbase );
977 if ( infile == NULL ) {
978 rc = dosearch( ld, base, scope, NULL, filtpattern,
979 attrs, attrsonly, NULL, NULL, NULL, -1 );
984 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
985 line[ strlen( line ) - 1 ] = '\0';
991 rc = dosearch( ld, base, scope, filtpattern, line,
992 attrs, attrsonly, NULL, NULL, NULL, -1 );
999 if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
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 );
1027 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1028 return EXIT_FAILURE;
1031 pageSize = (ber_int_t)tmpSize;
1042 for ( ; save_nctrls-- > 0; ) {
1043 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1053 static int dosearch(
1061 LDAPControl **sctrls,
1062 LDAPControl **cctrls,
1063 struct timeval *timeout,
1073 LDAPMessage *res, *msg;
1075 char *retoid = NULL;
1076 struct berval *retdata = NULL;
1077 int nresponses_psearch = -1;
1078 int cancel_msgid = -1;
1080 if( filtpatt != NULL ) {
1081 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1;
1082 filter = malloc( max_fsize );
1083 if( filter == NULL ) {
1085 return EXIT_FAILURE;
1088 if( snprintf( filter, max_fsize, filtpatt, value ) >= max_fsize ) {
1089 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1091 return EXIT_FAILURE;
1095 fprintf( stderr, _("filter: %s\n"), filter );
1099 printf( _("#\n# filter: %s\n#\n"), filter );
1107 if ( filtpatt != NULL ) {
1110 return LDAP_SUCCESS;
1113 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1114 sctrls, cctrls, timeout, sizelimit, &msgid );
1116 if ( filtpatt != NULL ) {
1120 if( rc != LDAP_SUCCESS ) {
1121 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1122 prog, ldap_err2string( rc ), rc );
1126 nresponses = nentries = nreferences = nextended = npartial = 0;
1130 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1131 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1134 rc = tool_check_abandon( ld, msgid );
1140 (void) ldap_sort_entries( ld, &res,
1141 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1144 for ( msg = ldap_first_message( ld, res );
1146 msg = ldap_next_message( ld, msg ) )
1148 if ( nresponses++ ) putchar('\n');
1149 if ( nresponses_psearch >= 0 )
1150 nresponses_psearch++;
1152 switch( ldap_msgtype( msg ) ) {
1153 case LDAP_RES_SEARCH_ENTRY:
1155 print_entry( ld, msg, attrsonly );
1158 case LDAP_RES_SEARCH_REFERENCE:
1160 print_reference( ld, msg );
1163 case LDAP_RES_EXTENDED:
1165 print_extended( ld, msg );
1167 if( ldap_msgid( msg ) == 0 ) {
1168 /* unsolicited extended operation */
1172 if ( cancel_msgid != -1 &&
1173 cancel_msgid == ldap_msgid( msg ) ) {
1174 printf(_("Cancelled \n"));
1175 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1180 case LDAP_RES_SEARCH_RESULT:
1181 /* pagedResults stuff is dealt with
1182 * in tool_print_ctrls(), called by
1183 * print_results(). */
1184 rc = print_result( ld, msg, 1 );
1185 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1191 case LDAP_RES_INTERMEDIATE:
1193 ldap_parse_intermediate( ld, msg,
1194 &retoid, &retdata, NULL, 0 );
1196 nresponses_psearch = 0;
1198 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1199 printf(_("SyncInfo Received\n"));
1200 ldap_memfree( retoid );
1201 ber_bvfree( retdata );
1205 print_partial( ld, msg );
1206 ldap_memfree( retoid );
1207 ber_bvfree( retdata );
1211 if ( ldapsync && sync_slimit != -1 &&
1212 nresponses_psearch >= sync_slimit ) {
1213 BerElement *msgidber = NULL;
1214 struct berval *msgidvalp = NULL;
1215 msgidber = ber_alloc_t(LBER_USE_DER);
1216 ber_printf(msgidber, "{i}", msgid);
1217 ber_flatten(msgidber, &msgidvalp);
1218 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1219 msgidvalp, NULL, NULL, &cancel_msgid);
1220 nresponses_psearch = -1;
1224 ldap_msgfree( res );
1229 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1233 ldap_msgfree( res );
1235 if ( pagedResults ) {
1236 npagedresponses += nresponses;
1237 npagedentries += nentries;
1238 npagedextended += nextended;
1239 npagedpartial += npartial;
1240 npagedreferences += nreferences;
1241 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1242 printf( _("\n# numResponses: %d\n"), npagedresponses );
1243 if( npagedentries ) {
1244 printf( _("# numEntries: %d\n"), npagedentries );
1246 if( npagedextended ) {
1247 printf( _("# numExtended: %d\n"), npagedextended );
1249 if( npagedpartial ) {
1250 printf( _("# numPartial: %d\n"), npagedpartial );
1252 if( npagedreferences ) {
1253 printf( _("# numReferences: %d\n"), npagedreferences );
1256 } else if ( ldif < 2 ) {
1257 printf( _("\n# numResponses: %d\n"), nresponses );
1258 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1259 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1260 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1261 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1267 /* This is the proposed new way of doing things.
1268 * It is more efficient, but the API is non-standard.
1277 char tmpfname[ 256 ];
1280 BerElement *ber = NULL;
1281 struct berval bv, *bvals, **bvp = &bvals;
1282 LDAPControl **ctrls = NULL;
1285 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1288 ufn = ldap_dn2ufn( bv.bv_val );
1289 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1291 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1293 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1294 if( rc != LDAP_SUCCESS ) {
1295 fprintf(stderr, _("print_entry: %d\n"), rc );
1296 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1297 exit( EXIT_FAILURE );
1301 tool_print_ctrls( ld, ctrls );
1302 ldap_controls_free( ctrls );
1307 ufn = ldap_dn2ufn( bv.bv_val );
1309 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1312 if( ufn != NULL ) ldap_memfree( ufn );
1314 if ( attrsonly ) bvp = NULL;
1316 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1318 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1320 if (bv.bv_val == NULL) break;
1323 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1325 } else if ( bvals ) {
1326 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1327 if ( vals2tmp > 1 || ( vals2tmp &&
1328 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1331 /* write value to file */
1332 snprintf( tmpfname, sizeof tmpfname,
1333 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1334 tmpdir, bv.bv_val );
1337 tmpfd = mkstemp( tmpfname );
1344 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1349 if ( fwrite( bvals[ i ].bv_val,
1350 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1359 snprintf( url, sizeof url, "%s%s", urlpre,
1360 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1363 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1366 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1367 bvals[ i ].bv_val, bvals[ i ].bv_len );
1370 ber_memfree( bvals );
1379 static void print_reference(
1381 LDAPMessage *reference )
1385 LDAPControl **ctrls;
1388 printf(_("# search reference\n"));
1391 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1393 if( rc != LDAP_SUCCESS ) {
1394 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1395 exit( EXIT_FAILURE );
1400 for( i=0; refs[i] != NULL; i++ ) {
1401 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1402 "ref", refs[i], strlen(refs[i]) );
1404 ber_memvfree( (void **) refs );
1408 tool_print_ctrls( ld, ctrls );
1409 ldap_controls_free( ctrls );
1413 static void print_extended(
1415 LDAPMessage *extended )
1418 char *retoid = NULL;
1419 struct berval *retdata = NULL;
1422 printf(_("# extended result response\n"));
1425 rc = ldap_parse_extended_result( ld, extended,
1426 &retoid, &retdata, 0 );
1428 if( rc != LDAP_SUCCESS ) {
1429 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1430 exit( EXIT_FAILURE );
1434 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1435 "extended", retoid, retoid ? strlen(retoid) : 0 );
1437 ber_memfree( retoid );
1441 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1442 "data", retdata->bv_val, retdata->bv_len );
1444 ber_bvfree( retdata );
1447 print_result( ld, extended, 0 );
1450 static void print_partial(
1452 LDAPMessage *partial )
1455 char *retoid = NULL;
1456 struct berval *retdata = NULL;
1457 LDAPControl **ctrls = NULL;
1460 printf(_("# extended partial response\n"));
1463 rc = ldap_parse_intermediate( ld, partial,
1464 &retoid, &retdata, &ctrls, 0 );
1466 if( rc != LDAP_SUCCESS ) {
1467 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1468 exit( EXIT_FAILURE );
1472 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1473 "partial", retoid, retoid ? strlen(retoid) : 0 );
1476 ber_memfree( retoid );
1480 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1481 "data", retdata->bv_val, retdata->bv_len );
1484 ber_bvfree( retdata );
1488 tool_print_ctrls( ld, ctrls );
1489 ldap_controls_free( ctrls );
1493 static int print_result(
1495 LDAPMessage *result, int search )
1499 char *matcheddn = NULL;
1502 LDAPControl **ctrls = NULL;
1506 printf(_("# search result\n"));
1509 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1513 rc = ldap_parse_result( ld, result,
1514 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1516 if( rc != LDAP_SUCCESS ) {
1517 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1518 exit( EXIT_FAILURE );
1523 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1525 } else if ( err != LDAP_SUCCESS ) {
1526 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1532 tool_write_ldif( LDIF_PUT_VALUE,
1533 "matchedDN", matcheddn, strlen(matcheddn) );
1535 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1539 ber_memfree( matcheddn );
1545 if ( err == LDAP_PARTIAL_RESULTS ) {
1548 for ( line = text; line != NULL; ) {
1549 char *next = strchr( line, '\n' );
1551 tool_write_ldif( LDIF_PUT_TEXT,
1553 next ? next - line : strlen( line ) );
1555 line = next ? next + 1 : NULL;
1559 tool_write_ldif( LDIF_PUT_TEXT, "text",
1560 text, strlen(text) );
1563 fprintf( stderr, _("Additional information: %s\n"), text );
1567 ber_memfree( text );
1572 for( i=0; refs[i] != NULL; i++ ) {
1574 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1576 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1580 ber_memvfree( (void **) refs );
1583 pr_morePagedResults = 0;
1586 tool_print_ctrls( ld, ctrls );
1587 ldap_controls_free( ctrls );