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-2254 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 #ifdef LDAP_CONTROL_DONTUSECOPY
126 fprintf( stderr, _(" !dontUseCopy (Don't Use Copy)\n"));
128 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
129 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
130 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
131 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
132 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
133 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
134 fprintf( stderr, _(" [!]<oid>=:<value> (generic control; no response handling)\n"));
135 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
136 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
137 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
138 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
139 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
140 fprintf( stderr, _(" and version\n"));
141 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
142 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
143 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
144 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
145 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
146 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
147 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
149 exit( EXIT_FAILURE );
152 static void print_entry LDAP_P((
157 static void print_reference(
159 LDAPMessage *reference );
161 static void print_extended(
163 LDAPMessage *extended );
165 static void print_partial(
167 LDAPMessage *partial );
169 static int print_result(
174 static int dosearch LDAP_P((
182 LDAPControl **sctrls,
183 LDAPControl **cctrls,
184 struct timeval *timeout,
187 static char *tmpdir = NULL;
188 static char *urlpre = NULL;
189 static char *base = NULL;
190 static char *sortattr = NULL;
191 static int includeufn, vals2tmp = 0;
193 static int subentries = 0, valuesReturnFilter = 0;
194 static char *vrFilter = NULL;
196 #ifdef LDAP_CONTROL_DONTUSECOPY
197 static int dontUseCopy = 0;
200 static int domainScope = 0;
202 static int ldapsync = 0;
203 static struct berval sync_cookie = { 0, NULL };
204 static int sync_slimit = -1;
206 static int pagedResults = 0;
207 static int pagePrompt = 1;
208 static ber_int_t pageSize = 0;
209 static ber_int_t entriesLeft = 0;
210 static ber_int_t morePagedResults = 1;
211 static struct berval page_cookie = { 0, NULL };
212 static int npagedresponses;
213 static int npagedentries;
214 static int npagedreferences;
215 static int npagedextended;
216 static int npagedpartial;
218 static LDAPControl *c = NULL;
219 static int nctrls = 0;
220 static int save_nctrls = 0;
228 tmpc = realloc( c, sizeof( LDAPControl ) * nctrls );
229 if ( tmpc == NULL ) {
232 _("unable to make room for control; out of memory?\n"));
240 static int parse_page_control(
243 struct berval *cookie );
250 if (*LDAP_DIRSEP != '/') {
251 for (p = url; *p; p++) {
252 if (*p == *LDAP_DIRSEP)
259 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
260 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
263 handle_private_option( int i )
266 char *control, *cvalue, *next;
268 case 'a': /* set alias deref option */
269 if ( strcasecmp( optarg, "never" ) == 0 ) {
270 deref = LDAP_DEREF_NEVER;
271 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
272 deref = LDAP_DEREF_SEARCHING;
273 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
274 deref = LDAP_DEREF_FINDING;
275 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
276 deref = LDAP_DEREF_ALWAYS;
279 _("alias deref should be never, search, find, or always\n") );
283 case 'A': /* retrieve attribute names only -- no values */
286 case 'b': /* search base */
287 base = ber_strdup( optarg );
289 case 'E': /* search extensions */
290 if( protocol == LDAP_VERSION2 ) {
291 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
293 exit( EXIT_FAILURE );
296 /* should be extended to support comma separated list of
297 * [!]key[=value] parameters, e.g. -E !foo,bar=567
302 if( optarg[0] == '!' ) {
307 control = ber_strdup( optarg );
308 if ( (cvalue = strchr( control, '=' )) != NULL ) {
312 if ( strcasecmp( control, "mv" ) == 0 ) {
313 /* ValuesReturnFilter control */
314 if( valuesReturnFilter ) {
316 _("ValuesReturnFilter previously specified\n"));
317 exit( EXIT_FAILURE );
319 valuesReturnFilter= 1 + crit;
321 if ( cvalue == NULL ) {
323 _("missing filter in ValuesReturnFilter control\n"));
324 exit( EXIT_FAILURE );
328 protocol = LDAP_VERSION3;
330 } else if ( strcasecmp( control, "pr" ) == 0 ) {
332 /* PagedResults control */
333 if ( pagedResults != 0 ) {
335 _("PagedResultsControl previously specified\n") );
336 exit( EXIT_FAILURE );
339 if( cvalue != NULL ) {
342 promptp = strchr( cvalue, '/' );
343 if ( promptp != NULL ) {
345 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
347 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
351 _("Invalid value for PagedResultsControl,"
352 " %s/%s.\n"), cvalue, promptp );
353 exit( EXIT_FAILURE );
356 num = sscanf( cvalue, "%d", &tmp );
359 _("Invalid value for PagedResultsControl, %s.\n"),
361 exit( EXIT_FAILURE );
364 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
365 exit( EXIT_FAILURE );
367 pageSize = (ber_int_t) tmp;
368 pagedResults = 1 + crit;
370 #ifdef LDAP_CONTROL_DONTUSECOPY
371 } else if ( strcasecmp( control, "dontUseCopy" ) == 0 ) {
374 _("dontUseCopy control previously specified\n"));
375 exit( EXIT_FAILURE );
377 if( cvalue != NULL ) {
379 _("dontUseCopy: no control value expected\n") );
384 _("dontUseCopy: critical flag required\n") );
388 dontUseCopy = 1 + crit;
390 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
393 _("domainScope control previously specified\n"));
394 exit( EXIT_FAILURE );
396 if( cvalue != NULL ) {
398 _("domainScope: no control value expected\n") );
402 domainScope = 1 + crit;
404 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
407 _("subentries control previously specified\n"));
408 exit( EXIT_FAILURE );
410 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
412 } else if ( strcasecmp( cvalue, "false") == 0 ) {
416 _("subentries control value \"%s\" invalid\n"),
418 exit( EXIT_FAILURE );
420 if( crit ) subentries *= -1;
422 } else if ( strcasecmp( control, "sync" ) == 0 ) {
426 fprintf( stderr, _("sync control previously specified\n") );
427 exit( EXIT_FAILURE );
429 if ( cvalue == NULL ) {
430 fprintf( stderr, _("missing specification of sync control\n"));
431 exit( EXIT_FAILURE );
433 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
434 ldapsync = LDAP_SYNC_REFRESH_ONLY;
435 cookiep = strchr( cvalue, '/' );
436 if ( cookiep != NULL ) {
438 if ( *cookiep != '\0' ) {
439 ber_str2bv( cookiep, 0, 0, &sync_cookie );
442 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
443 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
444 cookiep = strchr( cvalue, '/' );
445 if ( cookiep != NULL ) {
449 slimitp = strchr( cvalue, '/' );
450 if ( slimitp != NULL ) {
453 if ( cookiep != NULL && *cookiep != '\0' )
454 ber_str2bv( cookiep, 0, 0, &sync_cookie );
455 if ( slimitp != NULL && *slimitp != '\0' ) {
456 ival = strtol( slimitp, &next, 10 );
457 if ( next == NULL || next[0] != '\0' ) {
458 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
459 exit( EXIT_FAILURE );
464 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
466 exit( EXIT_FAILURE );
468 if ( crit ) ldapsync *= -1;
470 } else if ( tool_is_oid( control ) ) {
472 exit( EXIT_FAILURE );
476 c[ nctrls - 1 ].ldctl_oid = control;
479 if ( cvalue == NULL ) {
480 c[ nctrls - 1 ].ldctl_value.bv_val = NULL;
481 c[ nctrls - 1 ].ldctl_value.bv_len = 0;
483 } else if ( cvalue[ 0 ] == ':' ) {
491 * to use ldif_parse_line2() */
493 ldif_parse_line2( &cvalue[ -2 ], &type,
498 c[ nctrls - 1 ].ldctl_value = value;
501 ber_dupbv( &c[ nctrls - 1 ].ldctl_value, &value );
506 c[ nctrls - 1 ].ldctl_iscritical = crit;
509 fprintf( stderr, _("Invalid search extension name: %s\n"),
514 case 'F': /* uri prefix */
515 if( urlpre ) free( urlpre );
516 urlpre = strdup( optarg );
518 case 'l': /* time limit */
519 if ( strcasecmp( optarg, "none" ) == 0 ) {
522 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
523 timelimit = LDAP_MAXINT;
526 ival = strtol( optarg, &next, 10 );
527 if ( next == NULL || next[0] != '\0' ) {
529 _("Unable to parse time limit \"%s\"\n"), optarg );
530 exit( EXIT_FAILURE );
534 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
535 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
537 exit( EXIT_FAILURE );
540 case 'L': /* print entries in LDIF format */
543 case 's': /* search scope */
544 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
545 scope = LDAP_SCOPE_BASE;
546 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
547 scope = LDAP_SCOPE_ONELEVEL;
548 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
549 || ( strcasecmp( optarg, "children" ) == 0 ))
551 scope = LDAP_SCOPE_SUBORDINATE;
552 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
553 scope = LDAP_SCOPE_SUBTREE;
555 fprintf( stderr, _("scope should be base, one, or sub\n") );
559 case 'S': /* sort attribute */
560 sortattr = strdup( optarg );
562 case 't': /* write attribute values to TMPDIR files */
565 case 'T': /* tmpdir */
566 if( tmpdir ) free( tmpdir );
567 tmpdir = strdup( optarg );
569 case 'u': /* include UFN */
572 case 'z': /* size limit */
573 if ( strcasecmp( optarg, "none" ) == 0 ) {
576 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
577 sizelimit = LDAP_MAXINT;
580 ival = strtol( optarg, &next, 10 );
581 if ( next == NULL || next[0] != '\0' ) {
583 _("Unable to parse size limit \"%s\"\n"), optarg );
584 exit( EXIT_FAILURE );
588 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
589 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
591 exit( EXIT_FAILURE );
602 private_conn_setup( LDAP *ld )
605 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
606 != LDAP_OPT_SUCCESS )
608 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
609 exit( EXIT_FAILURE );
612 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
613 != LDAP_OPT_SUCCESS )
616 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
617 exit( EXIT_FAILURE );
620 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
621 != LDAP_OPT_SUCCESS )
624 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
625 exit( EXIT_FAILURE );
630 main( int argc, char **argv )
632 char *filtpattern, **attrs = NULL, line[BUFSIZ];
636 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
638 BerElement *syncber = NULL;
639 struct berval *syncbvalp = NULL;
643 npagedresponses = npagedentries = npagedreferences =
644 npagedextended = npagedpartial = 0;
646 prog = lutil_progname( "ldapsearch", argc, argv );
648 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
649 (def_tmpdir = getenv("TMP")) == NULL &&
650 (def_tmpdir = getenv("TEMP")) == NULL )
652 def_tmpdir = LDAP_TMPDIR;
656 def_tmpdir = LDAP_TMPDIR;
658 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
660 if( def_urlpre == NULL ) {
665 sprintf( def_urlpre, "file:///%s/",
666 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
668 urlize( def_urlpre );
670 tool_args( argc, argv );
672 if (( argc - optind < 1 ) ||
673 ( *argv[optind] != '(' /*')'*/ &&
674 ( strchr( argv[optind], '=' ) == NULL ) ) )
676 filtpattern = "(objectclass=*)";
678 filtpattern = argv[optind++];
681 if ( argv[optind] != NULL ) {
682 attrs = &argv[optind];
685 if ( infile != NULL ) {
686 if ( infile[0] == '-' && infile[1] == '\0' ) {
688 } else if (( fp = fopen( infile, "r" )) == NULL ) {
694 if ( tmpdir == NULL ) {
697 if ( urlpre == NULL )
701 if( urlpre == NULL ) {
702 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
704 if( urlpre == NULL ) {
709 sprintf( urlpre, "file:///%s/",
710 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
718 ld = tool_conn_setup( 0, &private_conn_setup );
720 if ( pw_file || want_bindpw ) {
722 rc = lutil_get_filed_password( pw_file, &passwd );
723 if( rc ) return EXIT_FAILURE;
725 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
726 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
733 if ( nctrls > 0 || assertion || authzid || manageDSAit || noop
734 #ifdef LDAP_CONTROL_DONTUSECOPY
737 || domainScope || pagedResults
738 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
740 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
742 || subentries || valuesReturnFilter )
746 save_nctrls = nctrls;
748 #ifdef LDAP_CONTROL_DONTUSECOPY
754 c[i].ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
755 c[i].ldctl_value.bv_val = NULL;
756 c[i].ldctl_value.bv_len = 0;
757 c[i].ldctl_iscritical = dontUseCopy > 1;
767 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
768 c[i].ldctl_value.bv_val = NULL;
769 c[i].ldctl_value.bv_len = 0;
770 c[i].ldctl_iscritical = domainScope > 1;
779 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
783 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
785 ber_free( seber, 1 );
786 fprintf( stderr, _("Subentries control encoding error!\n") );
790 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
794 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
795 c[i].ldctl_iscritical = subentries < 1;
804 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
808 if ( sync_cookie.bv_len == 0 ) {
809 err = ber_printf( syncber, "{e}", abs(ldapsync) );
811 err = ber_printf( syncber, "{eO}", abs(ldapsync),
815 if ( err == LBER_ERROR ) {
816 ber_free( syncber, 1 );
817 fprintf( stderr, _("ldap sync control encoding error!\n") );
821 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
825 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
826 c[i].ldctl_value = (*syncbvalp);
827 c[i].ldctl_iscritical = ldapsync < 0;
831 if ( valuesReturnFilter ) {
836 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
840 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
841 ber_free( vrber, 1 );
842 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
846 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
850 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
851 c[i].ldctl_iscritical = valuesReturnFilter > 1;
855 if ( pagedResults ) {
860 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
864 ber_printf( prber, "{iO}", pageSize, &page_cookie );
865 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
868 if ( page_cookie.bv_val != NULL ) {
869 ber_memfree( page_cookie.bv_val );
870 page_cookie.bv_val = NULL;
873 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
874 c[i].ldctl_iscritical = pagedResults > 1;
878 tool_server_controls( ld, c, i );
880 /* step back to the original number of controls, so that
881 * those set while parsing args are preserved */
882 nctrls = save_nctrls;
884 ber_free( seber, 1 );
885 ber_free( vrber, 1 );
886 ber_free( prber, 1 );
890 fprintf( stderr, _("filter%s: %s\nrequesting: "),
891 infile != NULL ? _(" pattern") : "",
894 if ( attrs == NULL ) {
895 fprintf( stderr, _("All userApplication attributes") );
897 for ( i = 0; attrs[ i ] != NULL; ++i ) {
898 fprintf( stderr, "%s ", attrs[ i ] );
901 fprintf( stderr, "\n" );
905 printf( _("# extended LDIF\n") );
906 } else if ( ldif < 3 ) {
907 printf( _("version: %d\n\n"), 1 );
912 printf(_("# LDAPv%d\n"), protocol);
913 printf(_("# base <%s> with scope %s\n"),
915 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
916 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
917 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
919 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
921 printf(_("# requesting: "));
923 if ( attrs == NULL ) {
926 for ( i = 0; attrs[ i ] != NULL; ++i ) {
927 printf( "%s ", attrs[ i ] );
932 printf(_("\n# with manageDSAit %scontrol"),
933 manageDSAit > 1 ? _("critical ") : "" );
936 printf(_("\n# with noop %scontrol"),
937 noop > 1 ? _("critical ") : "" );
940 printf(_("\n# with subentries %scontrol: %s"),
941 subentries < 0 ? _("critical ") : "",
942 abs(subentries) == 1 ? "false" : "true" );
944 if ( valuesReturnFilter ) {
945 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
946 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
948 if ( pagedResults ) {
949 printf(_("\n# with pagedResults %scontrol: size=%d"),
950 (pagedResults > 1) ? _("critical ") : "",
954 printf( _("\n#\n\n") );
957 if ( infile == NULL ) {
958 rc = dosearch( ld, base, scope, NULL, filtpattern,
959 attrs, attrsonly, NULL, NULL, NULL, -1 );
964 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
965 line[ strlen( line ) - 1 ] = '\0';
971 rc = dosearch( ld, base, scope, filtpattern, line,
972 attrs, attrsonly, NULL, NULL, NULL, -1 );
979 if (( rc == LDAP_SUCCESS ) && pageSize && morePagedResults ) {
981 int i, moreEntries, tmpSize;
983 /* Loop to get the next pages when
984 * enter is pressed on the terminal.
986 if ( pagePrompt != 0 ) {
987 if ( entriesLeft > 0 ) {
988 printf( _("Estimate entries: %d\n"), entriesLeft );
990 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
993 moreEntries = getchar();
994 while ( moreEntries != EOF && moreEntries != '\n' ) {
995 if ( i < (int)sizeof(buf) - 1 ) {
996 buf[i] = moreEntries;
999 moreEntries = getchar();
1003 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
1004 int num = sscanf( buf, "%d", &tmpSize );
1007 _("Invalid value for PagedResultsControl, %s.\n"), buf);
1008 return EXIT_FAILURE;
1011 pageSize = (ber_int_t)tmpSize;
1022 for ( ; save_nctrls-- > 0; ) {
1023 ber_memfree( c[ save_nctrls ].ldctl_value.bv_val );
1033 static int dosearch(
1041 LDAPControl **sctrls,
1042 LDAPControl **cctrls,
1043 struct timeval *timeout,
1053 LDAPMessage *res, *msg;
1055 char *retoid = NULL;
1056 struct berval *retdata = NULL;
1057 int nresponses_psearch = -1;
1058 int cancel_msgid = -1;
1060 if( filtpatt != NULL ) {
1061 filter = malloc( strlen( filtpatt ) + strlen( value ) );
1062 if( filter == NULL ) {
1064 return EXIT_FAILURE;
1067 sprintf( filter, filtpatt, value );
1070 fprintf( stderr, _("filter: %s\n"), filter );
1074 printf( _("#\n# filter: %s\n#\n"), filter );
1082 return LDAP_SUCCESS;
1085 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1086 sctrls, cctrls, timeout, sizelimit, &msgid );
1088 if ( filtpatt != NULL ) {
1092 if( rc != LDAP_SUCCESS ) {
1093 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1094 prog, ldap_err2string( rc ), rc );
1098 nresponses = nentries = nreferences = nextended = npartial = 0;
1102 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1103 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1106 rc = tool_check_abandon( ld, msgid );
1112 (void) ldap_sort_entries( ld, &res,
1113 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1116 for ( msg = ldap_first_message( ld, res );
1118 msg = ldap_next_message( ld, msg ) )
1120 if ( nresponses++ ) putchar('\n');
1121 if ( nresponses_psearch >= 0 )
1122 nresponses_psearch++;
1124 switch( ldap_msgtype( msg ) ) {
1125 case LDAP_RES_SEARCH_ENTRY:
1127 print_entry( ld, msg, attrsonly );
1130 case LDAP_RES_SEARCH_REFERENCE:
1132 print_reference( ld, msg );
1135 case LDAP_RES_EXTENDED:
1137 print_extended( ld, msg );
1139 if( ldap_msgid( msg ) == 0 ) {
1140 /* unsolicited extended operation */
1144 if ( cancel_msgid != -1 &&
1145 cancel_msgid == ldap_msgid( msg ) ) {
1146 printf(_("Cancelled \n"));
1147 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1152 case LDAP_RES_SEARCH_RESULT:
1153 rc = print_result( ld, msg, 1 );
1154 if ( pageSize != 0 ) {
1155 if ( rc == LDAP_SUCCESS ) {
1156 rc = parse_page_control( ld, msg, &page_cookie );
1158 morePagedResults = 0;
1161 morePagedResults = 0;
1164 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1170 case LDAP_RES_INTERMEDIATE:
1172 ldap_parse_intermediate( ld, msg,
1173 &retoid, &retdata, NULL, 0 );
1175 nresponses_psearch = 0;
1177 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1178 printf(_("SyncInfo Received\n"));
1179 ldap_memfree( retoid );
1180 ber_bvfree( retdata );
1184 print_partial( ld, msg );
1185 ldap_memfree( retoid );
1186 ber_bvfree( retdata );
1190 if ( ldapsync && sync_slimit != -1 &&
1191 nresponses_psearch >= sync_slimit ) {
1192 BerElement *msgidber = NULL;
1193 struct berval *msgidvalp = NULL;
1194 msgidber = ber_alloc_t(LBER_USE_DER);
1195 ber_printf(msgidber, "{i}", msgid);
1196 ber_flatten(msgidber, &msgidvalp);
1197 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1198 msgidvalp, NULL, NULL, &cancel_msgid);
1199 nresponses_psearch = -1;
1203 ldap_msgfree( res );
1208 tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1212 ldap_msgfree( res );
1214 if ( pagedResults ) {
1215 npagedresponses += nresponses;
1216 npagedentries += nentries;
1217 npagedextended += nextended;
1218 npagedpartial += npartial;
1219 npagedreferences += nreferences;
1220 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1221 printf( _("\n# numResponses: %d\n"), npagedresponses );
1222 if( npagedentries ) {
1223 printf( _("# numEntries: %d\n"), npagedentries );
1225 if( npagedextended ) {
1226 printf( _("# numExtended: %d\n"), npagedextended );
1228 if( npagedpartial ) {
1229 printf( _("# numPartial: %d\n"), npagedpartial );
1231 if( npagedreferences ) {
1232 printf( _("# numReferences: %d\n"), npagedreferences );
1235 } else if ( ldif < 2 ) {
1236 printf( _("\n# numResponses: %d\n"), nresponses );
1237 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1238 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1239 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1240 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1246 /* This is the proposed new way of doing things.
1247 * It is more efficient, but the API is non-standard.
1256 char tmpfname[ 256 ];
1259 BerElement *ber = NULL;
1260 struct berval bv, *bvals, **bvp = &bvals;
1261 LDAPControl **ctrls = NULL;
1264 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1267 ufn = ldap_dn2ufn( bv.bv_val );
1268 tool_write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1270 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1272 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1273 if( rc != LDAP_SUCCESS ) {
1274 fprintf(stderr, _("print_entry: %d\n"), rc );
1275 tool_perror( "ldap_get_entry_controls", rc, NULL, NULL, NULL, NULL );
1276 exit( EXIT_FAILURE );
1280 tool_print_ctrls( ld, ctrls );
1281 ldap_controls_free( ctrls );
1286 ufn = ldap_dn2ufn( bv.bv_val );
1288 tool_write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1291 if( ufn != NULL ) ldap_memfree( ufn );
1293 if ( attrsonly ) bvp = NULL;
1295 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1297 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1299 if (bv.bv_val == NULL) break;
1302 tool_write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1304 } else if ( bvals ) {
1305 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1306 if ( vals2tmp > 1 || ( vals2tmp &&
1307 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1310 /* write value to file */
1311 snprintf( tmpfname, sizeof tmpfname,
1312 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1313 tmpdir, bv.bv_val );
1316 tmpfd = mkstemp( tmpfname );
1323 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1328 if ( fwrite( bvals[ i ].bv_val,
1329 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1338 snprintf( url, sizeof url, "%s%s", urlpre,
1339 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1342 tool_write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1345 tool_write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1346 bvals[ i ].bv_val, bvals[ i ].bv_len );
1349 ber_memfree( bvals );
1358 static void print_reference(
1360 LDAPMessage *reference )
1364 LDAPControl **ctrls;
1367 printf(_("# search reference\n"));
1370 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1372 if( rc != LDAP_SUCCESS ) {
1373 tool_perror( "ldap_parse_reference", rc, NULL, NULL, NULL, NULL );
1374 exit( EXIT_FAILURE );
1379 for( i=0; refs[i] != NULL; i++ ) {
1380 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1381 "ref", refs[i], strlen(refs[i]) );
1383 ber_memvfree( (void **) refs );
1387 tool_print_ctrls( ld, ctrls );
1388 ldap_controls_free( ctrls );
1392 static void print_extended(
1394 LDAPMessage *extended )
1397 char *retoid = NULL;
1398 struct berval *retdata = NULL;
1401 printf(_("# extended result response\n"));
1404 rc = ldap_parse_extended_result( ld, extended,
1405 &retoid, &retdata, 0 );
1407 if( rc != LDAP_SUCCESS ) {
1408 tool_perror( "ldap_parse_extended_result", rc, NULL, NULL, NULL, NULL );
1409 exit( EXIT_FAILURE );
1413 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1414 "extended", retoid, retoid ? strlen(retoid) : 0 );
1416 ber_memfree( retoid );
1420 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1421 "data", retdata->bv_val, retdata->bv_len );
1423 ber_bvfree( retdata );
1426 print_result( ld, extended, 0 );
1429 static void print_partial(
1431 LDAPMessage *partial )
1434 char *retoid = NULL;
1435 struct berval *retdata = NULL;
1436 LDAPControl **ctrls = NULL;
1439 printf(_("# extended partial response\n"));
1442 rc = ldap_parse_intermediate( ld, partial,
1443 &retoid, &retdata, &ctrls, 0 );
1445 if( rc != LDAP_SUCCESS ) {
1446 tool_perror( "ldap_parse_intermediate", rc, NULL, NULL, NULL, NULL );
1447 exit( EXIT_FAILURE );
1451 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1452 "partial", retoid, retoid ? strlen(retoid) : 0 );
1455 ber_memfree( retoid );
1459 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1460 "data", retdata->bv_val, retdata->bv_len );
1463 ber_bvfree( retdata );
1467 tool_print_ctrls( ld, ctrls );
1468 ldap_controls_free( ctrls );
1472 static int print_result(
1474 LDAPMessage *result, int search )
1478 char *matcheddn = NULL;
1481 LDAPControl **ctrls = NULL;
1485 printf(_("# search result\n"));
1488 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1492 rc = ldap_parse_result( ld, result,
1493 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1495 if( rc != LDAP_SUCCESS ) {
1496 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1497 exit( EXIT_FAILURE );
1502 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1504 } else if ( err != LDAP_SUCCESS ) {
1505 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1511 tool_write_ldif( LDIF_PUT_VALUE,
1512 "matchedDN", matcheddn, strlen(matcheddn) );
1514 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1518 ber_memfree( matcheddn );
1524 tool_write_ldif( LDIF_PUT_TEXT, "text",
1525 text, strlen(text) );
1527 fprintf( stderr, _("Additional information: %s\n"), text );
1531 ber_memfree( text );
1536 for( i=0; refs[i] != NULL; i++ ) {
1538 tool_write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1540 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1544 ber_memvfree( (void **) refs );
1548 tool_print_ctrls( ld, ctrls );
1549 ldap_controls_free( ctrls );
1558 LDAPMessage *result,
1559 struct berval *cookie )
1563 LDAPControl **ctrl = NULL;
1564 LDAPControl *ctrlp = NULL;
1568 rc = ldap_parse_result( ld, result,
1569 &err, NULL, NULL, NULL, &ctrl, 0 );
1571 if ( rc != LDAP_SUCCESS ) {
1572 tool_perror( "ldap_parse_result", rc, NULL, NULL, NULL, NULL );
1573 exit( EXIT_FAILURE );
1576 if ( err != LDAP_SUCCESS ) {
1577 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1581 /* There might be others, e.g. ppolicy... */
1582 ctrlp = ldap_find_control( LDAP_CONTROL_PAGEDRESULTS, ctrl );
1586 /* Parse the control value
1587 * searchResult ::= SEQUENCE {
1588 * size INTEGER (0..maxInt),
1589 * -- result set size estimate from server - unused
1590 * cookie OCTET STRING
1594 ber = ber_init( &ctrlp->ldctl_value );
1595 if ( ber == NULL ) {
1596 fprintf( stderr, _("Internal error.\n") );
1597 return EXIT_FAILURE;
1600 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1601 (void) ber_free( ber, 1 );
1603 if( tag == LBER_ERROR ) {
1605 _("Paged results response control could not be decoded.\n") );
1606 return EXIT_FAILURE;
1609 if( entriesLeft < 0 ) {
1611 _("Invalid entries estimate in paged results response.\n") );
1612 return EXIT_FAILURE;
1615 if ( cookie->bv_len == 0 ) {
1616 morePagedResults = 0;
1619 ldap_controls_free( ctrl );
1622 morePagedResults = 0;