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 );
983 while ( 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 );
993 if ( rc != 0 && !contoper ) {
1002 if (( rc == LDAP_SUCCESS ) && pageSize && pr_morePagedResults ) {
1004 int i, moreEntries, tmpSize;
1006 /* Loop to get the next pages when
1007 * enter is pressed on the terminal.
1009 if ( pagePrompt != 0 ) {
1010 if ( entriesLeft > 0 ) {
1011 printf( _("Estimate entries: %d\n"), entriesLeft );
1013 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
1016 moreEntries = getchar();
1017 while ( moreEntries != EOF && moreEntries != '\n' ) {
1018 if ( i < (int)sizeof(buf) - 1 ) {
1019 buf[i] = moreEntries;
1022 moreEntries = getchar();
1026 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1027 int num = sscanf( buf, "%d", &tmpSize );
1030 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1031 return EXIT_FAILURE;
1034 pageSize = (ber_int_t)tmpSize;
1045 for ( ; save_nctrls-- > 0; ) {
1046 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1056 static int dosearch(
1064 LDAPControl **sctrls,
1065 LDAPControl **cctrls,
1066 struct timeval *timeout,
1076 LDAPMessage *res, *msg;
1078 char *retoid = NULL;
1079 struct berval *retdata = NULL;
1080 int nresponses_psearch = -1;
1081 int cancel_msgid = -1;
1083 if( filtpatt != NULL ) {
1084 size_t max_fsize = strlen( filtpatt ) + strlen( value ) + 1;
1085 filter = malloc( max_fsize );
1086 if( filter == NULL ) {
1088 return EXIT_FAILURE;
1091 if( snprintf( filter, max_fsize, filtpatt, value ) >= max_fsize ) {
1092 fprintf( stderr, "Bad filter pattern: \"%s\"\n", filtpatt );
1094 return EXIT_FAILURE;
1098 fprintf( stderr, _("filter: %s\n"), filter );
1102 printf( _("#\n# filter: %s\n#\n"), filter );
1110 if ( filtpatt != NULL ) {
1113 return LDAP_SUCCESS;
1116 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1117 sctrls, cctrls, timeout, sizelimit, &msgid );
1119 if ( filtpatt != NULL ) {
1123 if( rc != LDAP_SUCCESS ) {
1124 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1125 prog, ldap_err2string( rc ), rc );
1129 nresponses = nentries = nreferences = nextended = npartial = 0;
1133 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1134 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1137 rc = tool_check_abandon( ld, msgid );
1143 (void) ldap_sort_entries( ld, &res,
1144 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1147 for ( msg = ldap_first_message( ld, res );
1149 msg = ldap_next_message( ld, msg ) )
1151 if ( nresponses++ ) putchar('\n');
1152 if ( nresponses_psearch >= 0 )
1153 nresponses_psearch++;
1155 switch( ldap_msgtype( msg ) ) {
1156 case LDAP_RES_SEARCH_ENTRY:
1158 print_entry( ld, msg, attrsonly );
1161 case LDAP_RES_SEARCH_REFERENCE:
1163 print_reference( ld, msg );
1166 case LDAP_RES_EXTENDED:
1168 print_extended( ld, msg );
1170 if( ldap_msgid( msg ) == 0 ) {
1171 /* unsolicited extended operation */
1175 if ( cancel_msgid != -1 &&
1176 cancel_msgid == ldap_msgid( msg ) ) {
1177 printf(_("Cancelled \n"));
1178 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1183 case LDAP_RES_SEARCH_RESULT:
1184 /* pagedResults stuff is dealt with
1185 * in tool_print_ctrls(), called by
1186 * print_results(). */
1187 rc = print_result( ld, msg, 1 );
1188 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1194 case LDAP_RES_INTERMEDIATE:
1196 ldap_parse_intermediate( ld, msg,
1197 &retoid, &retdata, NULL, 0 );
1199 nresponses_psearch = 0;
1201 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1202 printf(_("SyncInfo Received\n"));
1203 ldap_memfree( retoid );
1204 ber_bvfree( retdata );
1208 print_partial( ld, msg );
1209 ldap_memfree( retoid );
1210 ber_bvfree( retdata );
1214 if ( ldapsync && sync_slimit != -1 &&
1215 nresponses_psearch >= sync_slimit ) {
1216 BerElement *msgidber = NULL;
1217 struct berval *msgidvalp = NULL;
1218 msgidber = ber_alloc_t(LBER_USE_DER);
1219 ber_printf(msgidber, "{i}", msgid);
1220 ber_flatten(msgidber, &msgidvalp);
1221 ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
1222 msgidvalp, NULL, NULL, &cancel_msgid);
1223 nresponses_psearch = -1;
1227 ldap_msgfree( res );
1232 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1236 ldap_msgfree( res );
1238 if ( pagedResults ) {
1239 npagedresponses += nresponses;
1240 npagedentries += nentries;
1241 npagedextended += nextended;
1242 npagedpartial += npartial;
1243 npagedreferences += nreferences;
1244 if ( ( pr_morePagedResults == 0 ) && ( ldif < 2 ) ) {
1245 printf( _("\n# numResponses: %d\n"), npagedresponses );
1246 if( npagedentries ) {
1247 printf( _("# numEntries: %d\n"), npagedentries );
1249 if( npagedextended ) {
1250 printf( _("# numExtended: %d\n"), npagedextended );
1252 if( npagedpartial ) {
1253 printf( _("# numPartial: %d\n"), npagedpartial );
1255 if( npagedreferences ) {
1256 printf( _("# numReferences: %d\n"), npagedreferences );
1259 } else if ( ldif < 2 ) {
1260 printf( _("\n# numResponses: %d\n"), nresponses );
1261 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1262 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1263 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1264 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1270 /* This is the proposed new way of doing things.
1271 * It is more efficient, but the API is non-standard.
1280 char tmpfname[ 256 ];
1283 BerElement *ber = NULL;
1284 struct berval bv, *bvals, **bvp = &bvals;
1285 LDAPControl **ctrls = NULL;
1288 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1291 ufn = ldap_dn2ufn( bv.bv_val );
1292 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1294 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1296 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1297 if( rc != LDAP_SUCCESS ) {
1298 fprintf(stderr, _("print_entry: %d\n"), rc );
1299 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1300 exit( EXIT_FAILURE );
1304 tool_print_ctrls( ld, ctrls );
1305 ldap_controls_free( ctrls );
1310 ufn = ldap_dn2ufn( bv.bv_val );
1312 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1315 if( ufn != NULL ) ldap_memfree( ufn );
1317 if ( attrsonly ) bvp = NULL;
1319 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1321 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1323 if (bv.bv_val == NULL) break;
1326 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1328 } else if ( bvals ) {
1329 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1330 if ( vals2tmp > 1 || ( vals2tmp &&
1331 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1334 /* write value to file */
1335 snprintf( tmpfname, sizeof tmpfname,
1336 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1337 tmpdir, bv.bv_val );
1340 tmpfd = mkstemp( tmpfname );
1347 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1352 if ( fwrite( bvals[ i ].bv_val,
1353 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1362 snprintf( url, sizeof url, "%s%s", urlpre,
1363 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1366 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1369 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1370 bvals[ i ].bv_val, bvals[ i ].bv_len );
1373 ber_memfree( bvals );
1382 static void print_reference(
1384 LDAPMessage *reference )
1388 LDAPControl **ctrls;
1391 printf(_("# search reference\n"));
1394 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1396 if( rc != LDAP_SUCCESS ) {
1397 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1398 exit( EXIT_FAILURE );
1403 for( i=0; refs[i] != NULL; i++ ) {
1404 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1405 "ref", refs[i], strlen(refs[i]) );
1407 ber_memvfree( (void **) refs );
1411 tool_print_ctrls( ld, ctrls );
1412 ldap_controls_free( ctrls );
1416 static void print_extended(
1418 LDAPMessage *extended )
1421 char *retoid = NULL;
1422 struct berval *retdata = NULL;
1425 printf(_("# extended result response\n"));
1428 rc = ldap_parse_extended_result( ld, extended,
1429 &retoid, &retdata, 0 );
1431 if( rc != LDAP_SUCCESS ) {
1432 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1433 exit( EXIT_FAILURE );
1437 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1438 "extended", retoid, retoid ? strlen(retoid) : 0 );
1440 ber_memfree( retoid );
1444 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1445 "data", retdata->bv_val, retdata->bv_len );
1447 ber_bvfree( retdata );
1450 print_result( ld, extended, 0 );
1453 static void print_partial(
1455 LDAPMessage *partial )
1458 char *retoid = NULL;
1459 struct berval *retdata = NULL;
1460 LDAPControl **ctrls = NULL;
1463 printf(_("# extended partial response\n"));
1466 rc = ldap_parse_intermediate( ld, partial,
1467 &retoid, &retdata, &ctrls, 0 );
1469 if( rc != LDAP_SUCCESS ) {
1470 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1471 exit( EXIT_FAILURE );
1475 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1476 "partial", retoid, retoid ? strlen(retoid) : 0 );
1479 ber_memfree( retoid );
1483 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1484 "data", retdata->bv_val, retdata->bv_len );
1487 ber_bvfree( retdata );
1491 tool_print_ctrls( ld, ctrls );
1492 ldap_controls_free( ctrls );
1496 static int print_result(
1498 LDAPMessage *result, int search )
1502 char *matcheddn = NULL;
1505 LDAPControl **ctrls = NULL;
1509 printf(_("# search result\n"));
1512 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1516 rc = ldap_parse_result( ld, result,
1517 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1519 if( rc != LDAP_SUCCESS ) {
1520 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1521 exit( EXIT_FAILURE );
1526 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1528 } else if ( err != LDAP_SUCCESS ) {
1529 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1535 tool_write_ldif( LDIF_PUT_VALUE,
1536 "matchedDN", matcheddn, strlen(matcheddn) );
1538 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1542 ber_memfree( matcheddn );
1548 if ( err == LDAP_PARTIAL_RESULTS ) {
1551 for ( line = text; line != NULL; ) {
1552 char *next = strchr( line, '\n' );
1554 tool_write_ldif( LDIF_PUT_TEXT,
1556 next ? next - line : strlen( line ) );
1558 line = next ? next + 1 : NULL;
1562 tool_write_ldif( LDIF_PUT_TEXT, "text",
1563 text, strlen(text) );
1566 fprintf( stderr, _("Additional information: %s\n"), text );
1570 ber_memfree( text );
1575 for( i=0; refs[i] != NULL; i++ ) {
1577 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1579 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1583 ber_memvfree( (void **) refs );
1586 pr_morePagedResults = 0;
1589 tool_print_ctrls( ld, ctrls );
1590 ldap_controls_free( ctrls );