1 /* ldapsearch -- a tool for searching LDAP directories */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2005 The OpenLDAP Foundation.
6 * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7 * Portions Copyright 1998-2001 Net Boolean Incorporated.
8 * Portions Copyright 2001-2003 IBM Corporation.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted only as authorized by the OpenLDAP
15 * A copy of this license is available in the file LICENSE in the
16 * top-level directory of the distribution or, alternatively, at
17 * <http://www.OpenLDAP.org/license.html>.
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20 * All rights reserved.
22 * Redistribution and use in source and binary forms are permitted
23 * provided that this notice is preserved and that due credit is given
24 * to the University of Michigan at Ann Arbor. The name of the
25 * University may not be used to endorse or promote products derived
26 * from this software without specific prior written permission. This
27 * software is provided ``as is'' without express or implied warranty.
30 * This work was originally developed by the University of Michigan
31 * (as part of U-MICH LDAP). Additional significant contributors
43 #include <ac/stdlib.h>
46 #include <ac/string.h>
47 #include <ac/unistd.h>
51 #include <ac/signal.h>
56 #ifdef HAVE_SYS_TYPES_H
57 #include <sys/types.h>
67 #include "lutil_ldap.h"
68 #include "ldap_defaults.h"
75 static int scope = LDAP_SCOPE_SUBTREE;
76 static int deref = -1;
78 static int timelimit = -1;
79 static int sizelimit = -1;
81 static char *def_tmpdir;
82 static char *def_urlpre;
84 #if defined(__CYGWIN__) || defined(__MINGW32__)
85 /* Turn off commandline globbing, otherwise you cannot search for
94 fprintf( stderr, _("usage: %s [options] [filter [attributes...]]\nwhere:\n"), prog);
95 fprintf( stderr, _(" filter\tRFC-2254 compliant LDAP search filter\n"));
96 fprintf( stderr, _(" attributes\twhitespace-separated list of attribute descriptions\n"));
97 fprintf( stderr, _(" which may include:\n"));
98 fprintf( stderr, _(" 1.1 no attributes\n"));
99 fprintf( stderr, _(" * all user attributes\n"));
100 fprintf( stderr, _(" + all operational attributes\n"));
103 fprintf( stderr, _("Search options:\n"));
104 fprintf( stderr, _(" -a deref one of never (default), always, search, or find\n"));
105 fprintf( stderr, _(" -A retrieve attribute names only (no values)\n"));
106 fprintf( stderr, _(" -b basedn base dn for search\n"));
107 fprintf( stderr, _(" -E [!]<ext>[=<extparam>] search extensions (! indicates criticality)\n"));
108 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
109 fprintf( stderr, _(" [!]domainScope (domain scope)\n"));
111 fprintf( stderr, _(" [!]mv=<filter> (matched values filter)\n"));
112 #ifdef LDAP_CONTROL_PAGEDRESULTS
113 fprintf( stderr, _(" [!]pr=<size>[/prompt|noprompt] (paged results/prompt)\n"));
115 #ifdef LDAP_CONTROL_SUBENTRIES
116 fprintf( stderr, _(" [!]subentries[=true|false] (subentries)\n"));
118 fprintf( stderr, _(" [!]sync=ro[/<cookie>] (LDAP Sync refreshOnly)\n"));
119 fprintf( stderr, _(" rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)\n"));
120 fprintf( stderr, _(" -F prefix URL prefix for files (default: %s)\n"), def_urlpre);
121 fprintf( stderr, _(" -l limit time limit (in seconds, or \"none\" or \"max\") for search\n"));
122 fprintf( stderr, _(" -L print responses in LDIFv1 format\n"));
123 fprintf( stderr, _(" -LL print responses in LDIF format without comments\n"));
124 fprintf( stderr, _(" -LLL print responses in LDIF format without comments\n"));
125 fprintf( stderr, _(" and version\n"));
126 #ifdef LDAP_SCOPE_SUBORDINATE
127 fprintf( stderr, _(" -s scope one of base, one, sub or children (search scope)\n"));
128 #else /* ! LDAP_SCOPE_SUBORDINATE */
129 fprintf( stderr, _(" -s scope one of base, one, or sub (search scope)\n"));
130 #endif /* ! LDAP_SCOPE_SUBORDINATE */
131 fprintf( stderr, _(" -S attr sort the results by attribute `attr'\n"));
132 fprintf( stderr, _(" -t write binary values to files in temporary directory\n"));
133 fprintf( stderr, _(" -tt write all values to files in temporary directory\n"));
134 fprintf( stderr, _(" -T path write files to directory specified by path (default: %s)\n"), def_tmpdir);
135 fprintf( stderr, _(" -u include User Friendly entry names in the output\n"));
136 fprintf( stderr, _(" -z limit size limit (in entries, or \"none\" or \"max\") for search\n"));
138 exit( EXIT_FAILURE );
141 static void print_entry LDAP_P((
146 static void print_reference(
148 LDAPMessage *reference );
150 static void print_extended(
152 LDAPMessage *extended );
154 static void print_partial(
156 LDAPMessage *partial );
158 static int print_result(
163 static void print_ctrls(
164 LDAPControl **ctrls );
166 static int write_ldif LDAP_P((
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, ldif = 0;
191 static int subentries = 0, valuesReturnFilter = 0;
192 static char *vrFilter = NULL;
194 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
195 static int domainScope = 0;
198 static int ldapsync = 0;
199 static struct berval sync_cookie = { 0, NULL };
200 static int sync_slimit = -1;
202 #ifdef LDAP_CONTROL_PAGEDRESULTS
203 static int pagedResults = 0;
204 static int pagePrompt = 1;
205 static ber_int_t pageSize = 0;
206 static ber_int_t entriesLeft = 0;
207 static ber_int_t morePagedResults = 1;
208 static struct berval page_cookie = { 0, NULL };
209 static int npagedresponses;
210 static int npagedentries;
211 static int npagedreferences;
212 static int npagedextended;
213 static int npagedpartial;
215 static int parse_page_control(
218 struct berval *cookie );
226 if (*LDAP_DIRSEP != '/') {
227 for (p = url; *p; p++) {
228 if (*p == *LDAP_DIRSEP)
235 const char options[] = "a:Ab:cE:F:l:Ls:S:tT:uz:"
236 "Cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
239 handle_private_option( int i )
242 char *control, *cvalue, *next;
244 case 'a': /* set alias deref option */
245 if ( strcasecmp( optarg, "never" ) == 0 ) {
246 deref = LDAP_DEREF_NEVER;
247 } else if ( strncasecmp( optarg, "search", sizeof("search")-1 ) == 0 ) {
248 deref = LDAP_DEREF_SEARCHING;
249 } else if ( strncasecmp( optarg, "find", sizeof("find")-1 ) == 0 ) {
250 deref = LDAP_DEREF_FINDING;
251 } else if ( strcasecmp( optarg, "always" ) == 0 ) {
252 deref = LDAP_DEREF_ALWAYS;
255 _("alias deref should be never, search, find, or always\n") );
259 case 'A': /* retrieve attribute names only -- no values */
262 case 'b': /* search base */
263 base = ber_strdup( optarg );
265 case 'E': /* search extensions */
266 if( protocol == LDAP_VERSION2 ) {
267 fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
269 exit( EXIT_FAILURE );
272 /* should be extended to support comma separated list of
273 * [!]key[=value] parameters, e.g. -E !foo,bar=567
278 if( optarg[0] == '!' ) {
283 control = ber_strdup( optarg );
284 if ( (cvalue = strchr( control, '=' )) != NULL ) {
288 if ( strcasecmp( control, "mv" ) == 0 ) {
289 /* ValuesReturnFilter control */
290 if( valuesReturnFilter ) {
292 _("ValuesReturnFilter previously specified\n"));
293 exit( EXIT_FAILURE );
295 valuesReturnFilter= 1 + crit;
297 if ( cvalue == NULL ) {
299 _("missing filter in ValuesReturnFilter control\n"));
300 exit( EXIT_FAILURE );
304 protocol = LDAP_VERSION3;
306 #ifdef LDAP_CONTROL_PAGEDRESULTS
307 } else if ( strcasecmp( control, "pr" ) == 0 ) {
309 /* PagedResults control */
310 if ( pagedResults != 0 ) {
312 _("PagedResultsControl previously specified\n") );
313 exit( EXIT_FAILURE );
316 if( cvalue != NULL ) {
319 promptp = strchr( cvalue, '/' );
320 if ( promptp != NULL ) {
322 if ( strcasecmp( promptp, "prompt" ) == 0 ) {
324 } else if ( strcasecmp( promptp, "noprompt" ) == 0) {
328 _("Invalid value for PagedResultsControl,"
329 " %s/%s.\n"), cvalue, promptp );
330 exit( EXIT_FAILURE );
333 num = sscanf( cvalue, "%d", &tmp );
336 _("Invalid value for PagedResultsControl, %s.\n"),
338 exit( EXIT_FAILURE );
341 fprintf(stderr, _("Invalid value for PagedResultsControl.\n"));
342 exit( EXIT_FAILURE );
344 pageSize = (ber_int_t) tmp;
345 pagedResults = 1 + crit;
348 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
349 } else if ( strcasecmp( control, "domainScope" ) == 0 ) {
352 _("domainScope control previously specified\n"));
353 exit( EXIT_FAILURE );
355 if( cvalue != NULL ) {
357 _("domainScope: no control value expected\n") );
361 domainScope = 1 + crit;
364 #ifdef LDAP_CONTROL_SUBENTRIES
365 } else if ( strcasecmp( control, "subentries" ) == 0 ) {
368 _("subentries control previously specified\n"));
369 exit( EXIT_FAILURE );
371 if( cvalue == NULL || strcasecmp( cvalue, "true") == 0 ) {
373 } else if ( strcasecmp( cvalue, "false") == 0 ) {
377 _("subentries control value \"%s\" invalid\n"),
379 exit( EXIT_FAILURE );
381 if( crit ) subentries *= -1;
384 } else if ( strcasecmp( control, "sync" ) == 0 ) {
388 fprintf( stderr, _("sync control previously specified\n") );
389 exit( EXIT_FAILURE );
391 if ( cvalue == NULL ) {
392 fprintf( stderr, _("missing specification of sync control\n"));
393 exit( EXIT_FAILURE );
395 if ( strncasecmp( cvalue, "ro", 2 ) == 0 ) {
396 ldapsync = LDAP_SYNC_REFRESH_ONLY;
397 cookiep = strchr( cvalue, '/' );
398 if ( cookiep != NULL ) {
400 if ( *cookiep != '\0' ) {
401 ber_str2bv( cookiep, 0, 0, &sync_cookie );
404 } else if ( strncasecmp( cvalue, "rp", 2 ) == 0 ) {
405 ldapsync = LDAP_SYNC_REFRESH_AND_PERSIST;
406 cookiep = strchr( cvalue, '/' );
407 if ( cookiep != NULL ) {
411 slimitp = strchr( cvalue, '/' );
412 if ( slimitp != NULL ) {
415 if ( cookiep != NULL && *cookiep != '\0' )
416 ber_str2bv( cookiep, 0, 0, &sync_cookie );
417 if ( slimitp != NULL && *slimitp != '\0' ) {
418 ival = strtol( slimitp, &next, 10 );
419 if ( next == NULL || next[0] != '\0' ) {
420 fprintf( stderr, _("Unable to parse sync control value \"%s\"\n"), slimitp );
421 exit( EXIT_FAILURE );
426 fprintf( stderr, _("sync control value \"%s\" invalid\n"),
428 exit( EXIT_FAILURE );
430 if ( crit ) ldapsync *= -1;
433 fprintf( stderr, _("Invalid search extension name: %s\n"),
438 case 'F': /* uri prefix */
439 if( urlpre ) free( urlpre );
440 urlpre = strdup( optarg );
442 case 'l': /* time limit */
443 if ( strcasecmp( optarg, "none" ) == 0 ) {
446 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
447 timelimit = LDAP_MAXINT;
450 ival = strtol( optarg, &next, 10 );
451 if ( next == NULL || next[0] != '\0' ) {
453 _("Unable to parse time limit \"%s\"\n"), optarg );
454 exit( EXIT_FAILURE );
458 if( timelimit < 0 || timelimit > LDAP_MAXINT ) {
459 fprintf( stderr, _("%s: invalid timelimit (%d) specified\n"),
461 exit( EXIT_FAILURE );
464 case 'L': /* print entries in LDIF format */
467 case 's': /* search scope */
468 if ( strncasecmp( optarg, "base", sizeof("base")-1 ) == 0 ) {
469 scope = LDAP_SCOPE_BASE;
470 } else if ( strncasecmp( optarg, "one", sizeof("one")-1 ) == 0 ) {
471 scope = LDAP_SCOPE_ONELEVEL;
472 #ifdef LDAP_SCOPE_SUBORDINATE
473 } else if (( strcasecmp( optarg, "subordinate" ) == 0 )
474 || ( strcasecmp( optarg, "children" ) == 0 ))
476 scope = LDAP_SCOPE_SUBORDINATE;
478 } else if ( strncasecmp( optarg, "sub", sizeof("sub")-1 ) == 0 ) {
479 scope = LDAP_SCOPE_SUBTREE;
481 fprintf( stderr, _("scope should be base, one, or sub\n") );
485 case 'S': /* sort attribute */
486 sortattr = strdup( optarg );
488 case 't': /* write attribute values to TMPDIR files */
491 case 'T': /* tmpdir */
492 if( tmpdir ) free( tmpdir );
493 tmpdir = strdup( optarg );
495 case 'u': /* include UFN */
498 case 'z': /* size limit */
499 if ( strcasecmp( optarg, "none" ) == 0 ) {
502 } else if ( strcasecmp( optarg, "max" ) == 0 ) {
503 sizelimit = LDAP_MAXINT;
506 ival = strtol( optarg, &next, 10 );
507 if ( next == NULL || next[0] != '\0' ) {
509 _("Unable to parse size limit \"%s\"\n"), optarg );
510 exit( EXIT_FAILURE );
514 if( sizelimit < 0 || sizelimit > LDAP_MAXINT ) {
515 fprintf( stderr, _("%s: invalid sizelimit (%d) specified\n"),
517 exit( EXIT_FAILURE );
528 private_conn_setup( LDAP *ld )
531 ldap_set_option( ld, LDAP_OPT_DEREF, (void *) &deref )
532 != LDAP_OPT_SUCCESS )
534 fprintf( stderr, _("Could not set LDAP_OPT_DEREF %d\n"), deref );
535 exit( EXIT_FAILURE );
538 ldap_set_option( ld, LDAP_OPT_TIMELIMIT, (void *) &timelimit )
539 != LDAP_OPT_SUCCESS )
542 _("Could not set LDAP_OPT_TIMELIMIT %d\n"), timelimit );
543 exit( EXIT_FAILURE );
546 ldap_set_option( ld, LDAP_OPT_SIZELIMIT, (void *) &sizelimit )
547 != LDAP_OPT_SUCCESS )
550 _("Could not set LDAP_OPT_SIZELIMIT %d\n"), sizelimit );
551 exit( EXIT_FAILURE );
556 main( int argc, char **argv )
558 char *filtpattern, **attrs = NULL, line[BUFSIZ];
562 BerElement *seber = NULL, *vrber = NULL, *prber = NULL;
564 BerElement *syncber = NULL;
565 struct berval *syncbvalp = NULL;
569 #ifdef LDAP_CONTROL_PAGEDRESULTS
570 npagedresponses = npagedentries = npagedreferences =
571 npagedextended = npagedpartial = 0;
574 prog = lutil_progname( "ldapsearch", argc, argv );
576 if((def_tmpdir = getenv("TMPDIR")) == NULL &&
577 (def_tmpdir = getenv("TMP")) == NULL &&
578 (def_tmpdir = getenv("TEMP")) == NULL )
580 def_tmpdir = LDAP_TMPDIR;
584 def_tmpdir = LDAP_TMPDIR;
586 def_urlpre = malloc( sizeof("file:////") + strlen(def_tmpdir) );
588 if( def_urlpre == NULL ) {
593 sprintf( def_urlpre, "file:///%s/",
594 def_tmpdir[0] == *LDAP_DIRSEP ? &def_tmpdir[1] : def_tmpdir );
596 urlize( def_urlpre );
598 tool_args( argc, argv );
600 if (( argc - optind < 1 ) ||
601 ( *argv[optind] != '(' /*')'*/ &&
602 ( strchr( argv[optind], '=' ) == NULL ) ) )
604 filtpattern = "(objectclass=*)";
606 filtpattern = argv[optind++];
609 if ( argv[optind] != NULL ) {
610 attrs = &argv[optind];
613 if ( infile != NULL ) {
614 if ( infile[0] == '-' && infile[1] == '\0' ) {
616 } else if (( fp = fopen( infile, "r" )) == NULL ) {
622 if ( tmpdir == NULL ) {
625 if ( urlpre == NULL )
629 if( urlpre == NULL ) {
630 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
632 if( urlpre == NULL ) {
637 sprintf( urlpre, "file:///%s/",
638 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
646 ld = tool_conn_setup( 0, &private_conn_setup );
648 if ( pw_file || want_bindpw ) {
650 rc = lutil_get_filed_password( pw_file, &passwd );
651 if( rc ) return EXIT_FAILURE;
653 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
654 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
661 if ( assertion || authzid || manageDSAit || noop
662 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
665 #ifdef LDAP_CONTROL_PAGEDRESULTS
668 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
670 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
672 || subentries || valuesReturnFilter )
678 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
680 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
681 c[i].ldctl_value.bv_val = NULL;
682 c[i].ldctl_value.bv_len = 0;
683 c[i].ldctl_iscritical = domainScope > 1;
688 #ifdef LDAP_CONTROL_SUBENTRIES
690 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
694 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
696 ber_free( seber, 1 );
697 fprintf( stderr, _("Subentries control encoding error!\n") );
701 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
705 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
706 c[i].ldctl_iscritical = subentries < 1;
712 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
716 if ( sync_cookie.bv_len == 0 ) {
717 err = ber_printf( syncber, "{e}", abs(ldapsync) );
719 err = ber_printf( syncber, "{eO}", abs(ldapsync),
723 if ( err == LBER_ERROR ) {
724 ber_free( syncber, 1 );
725 fprintf( stderr, _("ldap sync control encoding error!\n") );
729 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
733 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
734 c[i].ldctl_value = (*syncbvalp);
735 c[i].ldctl_iscritical = ldapsync < 0;
739 if ( valuesReturnFilter ) {
740 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
744 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
745 ber_free( vrber, 1 );
746 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
750 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
754 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
755 c[i].ldctl_iscritical = valuesReturnFilter > 1;
759 #ifdef LDAP_CONTROL_PAGEDRESULTS
760 if ( pagedResults ) {
761 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
765 ber_printf( prber, "{iO}", pageSize, &page_cookie );
766 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
769 if ( page_cookie.bv_val != NULL ) {
770 ber_memfree( page_cookie.bv_val );
771 page_cookie.bv_val = NULL;
774 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
775 c[i].ldctl_iscritical = pagedResults > 1;
780 tool_server_controls( ld, c, i );
782 #ifdef LDAP_CONTROL_SUBENTRIES
783 ber_free( seber, 1 );
785 ber_free( vrber, 1 );
786 #ifdef LDAP_CONTROL_PAGEDRESULTS
787 ber_free( prber, 1 );
792 fprintf( stderr, _("filter%s: %s\nrequesting: "),
793 infile != NULL ? _(" pattern") : "",
796 if ( attrs == NULL ) {
797 fprintf( stderr, _("ALL") );
799 for ( i = 0; attrs[ i ] != NULL; ++i ) {
800 fprintf( stderr, "%s ", attrs[ i ] );
803 fprintf( stderr, "\n" );
807 printf( _("# extended LDIF\n") );
808 } else if ( ldif < 3 ) {
809 printf( _("version: %d\n\n"), 1 );
814 printf(_("# LDAPv%d\n"), protocol);
815 printf(_("# base <%s> with scope %s\n"),
817 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
818 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
819 #ifdef LDAP_SCOPE_SUBORDINATE
820 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
823 #ifdef LDAP_SCOPE_SUBORDINATE
827 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
829 printf(_("# requesting: "));
831 if ( attrs == NULL ) {
834 for ( i = 0; attrs[ i ] != NULL; ++i ) {
835 printf( "%s ", attrs[ i ] );
840 printf(_("\n# with manageDSAit %scontrol"),
841 manageDSAit > 1 ? _("critical ") : "" );
844 printf(_("\n# with noop %scontrol"),
845 noop > 1 ? _("critical ") : "" );
848 printf(_("\n# with subentries %scontrol: %s"),
849 subentries < 0 ? _("critical ") : "",
850 abs(subentries) == 1 ? "false" : "true" );
852 if ( valuesReturnFilter ) {
853 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
854 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
856 #ifdef LDAP_CONTROL_PAGEDRESULTS
857 if ( pagedResults ) {
858 printf(_("\n# with pagedResults %scontrol: size=%d"),
859 (pagedResults > 1) ? _("critical ") : "",
864 printf( _("\n#\n\n") );
867 if ( infile == NULL ) {
868 rc = dosearch( ld, base, scope, NULL, filtpattern,
869 attrs, attrsonly, NULL, NULL, NULL, -1 );
874 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
875 line[ strlen( line ) - 1 ] = '\0';
881 rc = dosearch( ld, base, scope, filtpattern, line,
882 attrs, attrsonly, NULL, NULL, NULL, -1 );
889 #ifdef LDAP_CONTROL_PAGEDRESULTS
890 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
892 int i, moreEntries, tmpSize;
894 /* Loop to get the next pages when
895 * enter is pressed on the terminal.
897 if ( pagePrompt != 0 ) {
898 if ( entriesLeft > 0 ) {
899 printf( _("Estimate entries: %d\n"), entriesLeft );
901 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
904 moreEntries = getchar();
905 while ( moreEntries != EOF && moreEntries != '\n' ) {
906 if ( i < (int)sizeof(buf) - 1 ) {
907 buf[i] = moreEntries;
910 moreEntries = getchar();
914 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
915 int num = sscanf( buf, "%d", &tmpSize );
917 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
921 pageSize = (ber_int_t)tmpSize;
943 LDAPControl **sctrls,
944 LDAPControl **cctrls,
945 struct timeval *timeout,
955 LDAPMessage *res, *msg;
958 struct berval *retdata = NULL;
959 int nresponses_psearch = -1;
960 int cancel_msgid = -1;
962 if( filtpatt != NULL ) {
963 filter = malloc( strlen( filtpatt ) + strlen( value ) );
964 if( filter == NULL ) {
969 sprintf( filter, filtpatt, value );
972 fprintf( stderr, _("filter: %s\n"), filter );
976 printf( _("#\n# filter: %s\n#\n"), filter );
987 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
988 sctrls, cctrls, timeout, sizelimit, &msgid );
990 if ( filtpatt != NULL ) {
994 if( rc != LDAP_SUCCESS ) {
995 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
996 prog, ldap_err2string( rc ), rc );
1000 nresponses = nentries = nreferences = nextended = npartial = 0;
1004 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1005 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1008 rc = tool_check_abandon( ld, msgid );
1014 (void) ldap_sort_entries( ld, &res,
1015 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1018 for ( msg = ldap_first_message( ld, res );
1020 msg = ldap_next_message( ld, msg ) )
1022 if ( nresponses++ ) putchar('\n');
1023 if ( nresponses_psearch >= 0 )
1024 nresponses_psearch++;
1026 switch( ldap_msgtype( msg ) ) {
1027 case LDAP_RES_SEARCH_ENTRY:
1029 print_entry( ld, msg, attrsonly );
1032 case LDAP_RES_SEARCH_REFERENCE:
1034 print_reference( ld, msg );
1037 case LDAP_RES_EXTENDED:
1039 print_extended( ld, msg );
1041 if( ldap_msgid( msg ) == 0 ) {
1042 /* unsolicited extended operation */
1046 if ( cancel_msgid != -1 &&
1047 cancel_msgid == ldap_msgid( msg ) ) {
1048 printf(_("Cancelled \n"));
1049 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1054 case LDAP_RES_SEARCH_RESULT:
1055 rc = print_result( ld, msg, 1 );
1056 #ifdef LDAP_CONTROL_PAGEDRESULTS
1057 if ( pageSize != 0 ) {
1058 if ( rc == LDAP_SUCCESS ) {
1059 rc = parse_page_control( ld, msg, &page_cookie );
1061 morePagedResults = 0;
1064 morePagedResults = 0;
1068 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1074 case LDAP_RES_INTERMEDIATE:
1076 ldap_parse_intermediate( ld, msg,
1077 &retoid, &retdata, NULL, 0 );
1079 nresponses_psearch = 0;
1081 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1082 printf(_("SyncInfo Received\n"));
1083 ldap_memfree( retoid );
1084 ber_bvfree( retdata );
1088 print_partial( ld, msg );
1089 ldap_memfree( retoid );
1090 ber_bvfree( retdata );
1094 if ( ldapsync && sync_slimit != -1 &&
1095 nresponses_psearch >= sync_slimit ) {
1096 BerElement *msgidber = NULL;
1097 struct berval *msgidvalp = NULL;
1098 msgidber = ber_alloc_t(LBER_USE_DER);
1099 ber_printf(msgidber, "{i}", msgid);
1100 ber_flatten(msgidber, &msgidvalp);
1101 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1102 msgidvalp, NULL, NULL, &cancel_msgid);
1103 nresponses_psearch = -1;
1107 ldap_msgfree( res );
1112 ldap_perror( ld, "ldap_result" );
1116 ldap_msgfree( res );
1117 #ifdef LDAP_CONTROL_PAGEDRESULTS
1118 if ( pagedResults ) {
1119 npagedresponses += nresponses;
1120 npagedentries += nentries;
1121 npagedextended += nextended;
1122 npagedpartial += npartial;
1123 npagedreferences += nreferences;
1124 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1125 printf( _("\n# numResponses: %d\n"), npagedresponses );
1126 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1127 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1128 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1129 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1134 printf( _("\n# numResponses: %d\n"), nresponses );
1135 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1136 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1137 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1138 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1144 /* This is the proposed new way of doing things.
1145 * It is more efficient, but the API is non-standard.
1154 char tmpfname[ 256 ];
1157 BerElement *ber = NULL;
1158 struct berval bv, *bvals, **bvp = &bvals;
1159 LDAPControl **ctrls = NULL;
1162 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1165 ufn = ldap_dn2ufn( bv.bv_val );
1166 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1168 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1170 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1171 if( rc != LDAP_SUCCESS ) {
1172 fprintf(stderr, _("print_entry: %d\n"), rc );
1173 ldap_perror( ld, "ldap_get_entry_controls" );
1174 exit( EXIT_FAILURE );
1178 print_ctrls( ctrls );
1179 ldap_controls_free( ctrls );
1184 ufn = ldap_dn2ufn( bv.bv_val );
1186 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1189 if( ufn != NULL ) ldap_memfree( ufn );
1191 if ( attrsonly ) bvp = NULL;
1193 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1195 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1197 if (bv.bv_val == NULL) break;
1200 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1202 } else if ( bvals ) {
1203 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1204 if ( vals2tmp > 1 || ( vals2tmp &&
1205 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1208 /* write value to file */
1209 snprintf( tmpfname, sizeof tmpfname,
1210 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1211 tmpdir, bv.bv_val );
1214 tmpfd = mkstemp( tmpfname );
1221 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1226 if ( fwrite( bvals[ i ].bv_val,
1227 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1236 snprintf( url, sizeof url, "%s%s", urlpre,
1237 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1240 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1243 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1244 bvals[ i ].bv_val, bvals[ i ].bv_len );
1247 ber_memfree( bvals );
1256 static void print_reference(
1258 LDAPMessage *reference )
1262 LDAPControl **ctrls;
1265 printf(_("# search reference\n"));
1268 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1270 if( rc != LDAP_SUCCESS ) {
1271 ldap_perror(ld, "ldap_parse_reference");
1272 exit( EXIT_FAILURE );
1277 for( i=0; refs[i] != NULL; i++ ) {
1278 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1279 "ref", refs[i], strlen(refs[i]) );
1281 ber_memvfree( (void **) refs );
1285 print_ctrls( ctrls );
1286 ldap_controls_free( ctrls );
1290 static void print_extended(
1292 LDAPMessage *extended )
1295 char *retoid = NULL;
1296 struct berval *retdata = NULL;
1299 printf(_("# extended result response\n"));
1302 rc = ldap_parse_extended_result( ld, extended,
1303 &retoid, &retdata, 0 );
1305 if( rc != LDAP_SUCCESS ) {
1306 ldap_perror(ld, "ldap_parse_extended_result");
1307 exit( EXIT_FAILURE );
1311 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1312 "extended", retoid, retoid ? strlen(retoid) : 0 );
1314 ber_memfree( retoid );
1318 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1319 "data", retdata->bv_val, retdata->bv_len );
1321 ber_bvfree( retdata );
1324 print_result( ld, extended, 0 );
1327 static void print_partial(
1329 LDAPMessage *partial )
1332 char *retoid = NULL;
1333 struct berval *retdata = NULL;
1334 LDAPControl **ctrls = NULL;
1337 printf(_("# extended partial response\n"));
1340 rc = ldap_parse_intermediate( ld, partial,
1341 &retoid, &retdata, &ctrls, 0 );
1343 if( rc != LDAP_SUCCESS ) {
1344 ldap_perror(ld, "ldap_parse_intermediate");
1345 exit( EXIT_FAILURE );
1349 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1350 "partial", retoid, retoid ? strlen(retoid) : 0 );
1353 ber_memfree( retoid );
1357 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1358 "data", retdata->bv_val, retdata->bv_len );
1361 ber_bvfree( retdata );
1365 print_ctrls( ctrls );
1366 ldap_controls_free( ctrls );
1370 static int print_result(
1372 LDAPMessage *result, int search )
1376 char *matcheddn = NULL;
1379 LDAPControl **ctrls = NULL;
1383 printf(_("# search result\n"));
1386 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1390 rc = ldap_parse_result( ld, result,
1391 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1393 if( rc != LDAP_SUCCESS ) {
1394 ldap_perror(ld, "ldap_parse_result");
1395 exit( EXIT_FAILURE );
1400 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1402 } else if ( err != LDAP_SUCCESS ) {
1403 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1409 write_ldif( LDIF_PUT_VALUE,
1410 "matchedDN", matcheddn, strlen(matcheddn) );
1412 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1416 ber_memfree( matcheddn );
1422 write_ldif( LDIF_PUT_TEXT, "text",
1423 text, strlen(text) );
1425 fprintf( stderr, _("Additional information: %s\n"), text );
1429 ber_memfree( text );
1434 for( i=0; refs[i] != NULL; i++ ) {
1436 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1438 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1442 ber_memvfree( (void **) refs );
1446 print_ctrls( ctrls );
1447 ldap_controls_free( ctrls );
1453 static void print_ctrls(
1454 LDAPControl **ctrls )
1457 for(i=0; ctrls[i] != NULL; i++ ) {
1458 /* control: OID criticality base64value */
1459 struct berval *b64 = NULL;
1464 len += strlen( ctrls[i]->ldctl_oid );
1466 /* add enough for space after OID and the critical value itself */
1467 len += ctrls[i]->ldctl_iscritical
1468 ? sizeof("true") : sizeof("false");
1470 /* convert to base64 */
1471 if( ctrls[i]->ldctl_value.bv_len ) {
1472 b64 = ber_memalloc( sizeof(struct berval) );
1474 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1475 ctrls[i]->ldctl_value.bv_len ) + 1;
1476 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1478 b64->bv_len = lutil_b64_ntop(
1479 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1480 ctrls[i]->ldctl_value.bv_len,
1481 b64->bv_val, b64->bv_len );
1485 len += 1 + b64->bv_len;
1488 str = malloc( len + 1 );
1490 strcpy( str, ": " );
1494 strcat( str, ctrls[i]->ldctl_oid );
1495 strcat( str, ctrls[i]->ldctl_iscritical
1496 ? " true" : " false" );
1500 strcat(str, b64->bv_val );
1504 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1505 "control", str, len );
1514 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1518 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1522 fputs( ldif, stdout );
1523 ber_memfree( ldif );
1529 #ifdef LDAP_CONTROL_PAGEDRESULTS
1533 LDAPMessage *result,
1534 struct berval *cookie )
1538 LDAPControl **ctrl = NULL;
1539 LDAPControl *ctrlp = NULL;
1543 rc = ldap_parse_result( ld, result,
1544 &err, NULL, NULL, NULL, &ctrl, 0 );
1546 if( rc != LDAP_SUCCESS ) {
1547 ldap_perror(ld, "ldap_parse_result");
1548 exit( EXIT_FAILURE );
1551 if ( err != LDAP_SUCCESS ) {
1552 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1556 /* Parse the control value
1557 * searchResult ::= SEQUENCE {
1558 * size INTEGER (0..maxInt),
1559 * -- result set size estimate from server - unused
1560 * cookie OCTET STRING
1564 ber = ber_init( &ctrlp->ldctl_value );
1565 if ( ber == NULL ) {
1566 fprintf( stderr, _("Internal error.\n") );
1567 return EXIT_FAILURE;
1570 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1571 (void) ber_free( ber, 1 );
1573 if( tag == LBER_ERROR ) {
1575 _("Paged results response control could not be decoded.\n") );
1576 return EXIT_FAILURE;
1579 if( entriesLeft < 0 ) {
1581 _("Invalid entries estimate in paged results response.\n") );
1582 return EXIT_FAILURE;
1585 if ( cookie->bv_len == 0 ) {
1586 morePagedResults = 0;
1589 ldap_controls_free( ctrl );
1592 morePagedResults = 0;