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"
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 ) {
616 if ( infile[0] == '-' && infile[1] == '\0' ) {
618 } else if (( fp = fopen( infile, "r" )) == NULL ) {
623 for( i=0 ; filtpattern[i] ; i++ ) {
624 if( filtpattern[i] == '%' ) {
626 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
633 if( filtpattern[i+1] != 's' ) {
634 fprintf( stderr, _("Bad filter pattern \"%s\"\n"),
642 if ( tmpdir == NULL ) {
645 if ( urlpre == NULL )
649 if( urlpre == NULL ) {
650 urlpre = malloc( sizeof("file:////") + strlen(tmpdir) );
652 if( urlpre == NULL ) {
657 sprintf( urlpre, "file:///%s/",
658 tmpdir[0] == *LDAP_DIRSEP ? &tmpdir[1] : tmpdir );
666 ld = tool_conn_setup( 0, &private_conn_setup );
668 if ( pw_file || want_bindpw ) {
670 rc = lutil_get_filed_password( pw_file, &passwd );
671 if( rc ) return EXIT_FAILURE;
673 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
674 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
681 if ( assertion || authzid || manageDSAit || noop
682 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
685 #ifdef LDAP_CONTROL_PAGEDRESULTS
688 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
690 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
692 || subentries || valuesReturnFilter )
698 #ifdef LDAP_CONTROL_X_DOMAIN_SCOPE
700 c[i].ldctl_oid = LDAP_CONTROL_X_DOMAIN_SCOPE;
701 c[i].ldctl_value.bv_val = NULL;
702 c[i].ldctl_value.bv_len = 0;
703 c[i].ldctl_iscritical = domainScope > 1;
708 #ifdef LDAP_CONTROL_SUBENTRIES
710 if (( seber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
714 err = ber_printf( seber, "b", abs(subentries) == 1 ? 0 : 1 );
716 ber_free( seber, 1 );
717 fprintf( stderr, _("Subentries control encoding error!\n") );
721 if ( ber_flatten2( seber, &c[i].ldctl_value, 0 ) == -1 ) {
725 c[i].ldctl_oid = LDAP_CONTROL_SUBENTRIES;
726 c[i].ldctl_iscritical = subentries < 1;
732 if (( syncber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
736 if ( sync_cookie.bv_len == 0 ) {
737 err = ber_printf( syncber, "{e}", abs(ldapsync) );
739 err = ber_printf( syncber, "{eO}", abs(ldapsync),
743 if ( err == LBER_ERROR ) {
744 ber_free( syncber, 1 );
745 fprintf( stderr, _("ldap sync control encoding error!\n") );
749 if ( ber_flatten( syncber, &syncbvalp ) == LBER_ERROR ) {
753 c[i].ldctl_oid = LDAP_CONTROL_SYNC;
754 c[i].ldctl_value = (*syncbvalp);
755 c[i].ldctl_iscritical = ldapsync < 0;
759 if ( valuesReturnFilter ) {
760 if (( vrber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
764 if ( ( err = ldap_put_vrFilter( vrber, vrFilter ) ) == -1 ) {
765 ber_free( vrber, 1 );
766 fprintf( stderr, _("Bad ValuesReturnFilter: %s\n"), vrFilter );
770 if ( ber_flatten2( vrber, &c[i].ldctl_value, 0 ) == -1 ) {
774 c[i].ldctl_oid = LDAP_CONTROL_VALUESRETURNFILTER;
775 c[i].ldctl_iscritical = valuesReturnFilter > 1;
779 #ifdef LDAP_CONTROL_PAGEDRESULTS
780 if ( pagedResults ) {
781 if (( prber = ber_alloc_t(LBER_USE_DER)) == NULL ) {
785 ber_printf( prber, "{iO}", pageSize, &page_cookie );
786 if ( ber_flatten2( prber, &c[i].ldctl_value, 0 ) == -1 ) {
789 if ( page_cookie.bv_val != NULL ) {
790 ber_memfree( page_cookie.bv_val );
791 page_cookie.bv_val = NULL;
794 c[i].ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
795 c[i].ldctl_iscritical = pagedResults > 1;
800 tool_server_controls( ld, c, i );
802 #ifdef LDAP_CONTROL_SUBENTRIES
803 ber_free( seber, 1 );
805 ber_free( vrber, 1 );
806 #ifdef LDAP_CONTROL_PAGEDRESULTS
807 ber_free( prber, 1 );
812 fprintf( stderr, _("filter%s: %s\nrequesting: "),
813 infile != NULL ? _(" pattern") : "",
816 if ( attrs == NULL ) {
817 fprintf( stderr, _("All userApplication attributes") );
819 for ( i = 0; attrs[ i ] != NULL; ++i ) {
820 fprintf( stderr, "%s ", attrs[ i ] );
823 fprintf( stderr, "\n" );
827 printf( _("# extended LDIF\n") );
828 } else if ( ldif < 3 ) {
829 printf( _("version: %d\n\n"), 1 );
834 printf(_("# LDAPv%d\n"), protocol);
835 printf(_("# base <%s> with scope %s\n"),
837 ((scope == LDAP_SCOPE_BASE) ? "baseObject"
838 : ((scope == LDAP_SCOPE_ONELEVEL) ? "oneLevel"
839 #ifdef LDAP_SCOPE_SUBORDINATE
840 : ((scope == LDAP_SCOPE_SUBORDINATE) ? "children"
843 #ifdef LDAP_SCOPE_SUBORDINATE
847 printf(_("# filter%s: %s\n"), infile != NULL ? _(" pattern") : "",
849 printf(_("# requesting: "));
851 if ( attrs == NULL ) {
854 for ( i = 0; attrs[ i ] != NULL; ++i ) {
855 printf( "%s ", attrs[ i ] );
860 printf(_("\n# with manageDSAit %scontrol"),
861 manageDSAit > 1 ? _("critical ") : "" );
864 printf(_("\n# with noop %scontrol"),
865 noop > 1 ? _("critical ") : "" );
868 printf(_("\n# with subentries %scontrol: %s"),
869 subentries < 0 ? _("critical ") : "",
870 abs(subentries) == 1 ? "false" : "true" );
872 if ( valuesReturnFilter ) {
873 printf(_("\n# with valuesReturnFilter %scontrol: %s"),
874 valuesReturnFilter > 1 ? _("critical ") : "", vrFilter );
876 #ifdef LDAP_CONTROL_PAGEDRESULTS
877 if ( pagedResults ) {
878 printf(_("\n# with pagedResults %scontrol: size=%d"),
879 (pagedResults > 1) ? _("critical ") : "",
884 printf( _("\n#\n\n") );
887 if ( infile == NULL ) {
888 rc = dosearch( ld, base, scope, NULL, filtpattern,
889 attrs, attrsonly, NULL, NULL, NULL, -1 );
894 while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
895 line[ strlen( line ) - 1 ] = '\0';
901 rc = dosearch( ld, base, scope, filtpattern, line,
902 attrs, attrsonly, NULL, NULL, NULL, -1 );
909 #ifdef LDAP_CONTROL_PAGEDRESULTS
910 if ( ( rc == LDAP_SUCCESS ) && ( pageSize != 0 ) && ( morePagedResults != 0 ) ) {
912 int i, moreEntries, tmpSize;
914 /* Loop to get the next pages when
915 * enter is pressed on the terminal.
917 if ( pagePrompt != 0 ) {
918 if ( entriesLeft > 0 ) {
919 printf( _("Estimate entries: %d\n"), entriesLeft );
921 printf( _("Press [size] Enter for the next {%d|size} entries.\n"),
924 moreEntries = getchar();
925 while ( moreEntries != EOF && moreEntries != '\n' ) {
926 if ( i < (int)sizeof(buf) - 1 ) {
927 buf[i] = moreEntries;
930 moreEntries = getchar();
934 if ( i > 0 && isdigit( (unsigned char)buf[0] ) ) {
935 int num = sscanf( buf, "%d", &tmpSize );
937 fprintf( stderr, _("Invalid value for PagedResultsControl, %s.\n"), buf);
941 pageSize = (ber_int_t)tmpSize;
963 LDAPControl **sctrls,
964 LDAPControl **cctrls,
965 struct timeval *timeout,
975 LDAPMessage *res, *msg;
978 struct berval *retdata = NULL;
979 int nresponses_psearch = -1;
980 int cancel_msgid = -1;
982 if( filtpatt != NULL ) {
983 filter = malloc( strlen( filtpatt ) + strlen( value ) );
984 if( filter == NULL ) {
989 sprintf( filter, filtpatt, value );
992 fprintf( stderr, _("filter: %s\n"), filter );
996 printf( _("#\n# filter: %s\n#\n"), filter );
1004 return LDAP_SUCCESS;
1007 rc = ldap_search_ext( ld, base, scope, filter, attrs, attrsonly,
1008 sctrls, cctrls, timeout, sizelimit, &msgid );
1010 if ( filtpatt != NULL ) {
1014 if( rc != LDAP_SUCCESS ) {
1015 fprintf( stderr, _("%s: ldap_search_ext: %s (%d)\n"),
1016 prog, ldap_err2string( rc ), rc );
1020 nresponses = nentries = nreferences = nextended = npartial = 0;
1024 while ((rc = ldap_result( ld, LDAP_RES_ANY,
1025 sortattr ? LDAP_MSG_ALL : LDAP_MSG_ONE,
1028 rc = tool_check_abandon( ld, msgid );
1034 (void) ldap_sort_entries( ld, &res,
1035 ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
1038 for ( msg = ldap_first_message( ld, res );
1040 msg = ldap_next_message( ld, msg ) )
1042 if ( nresponses++ ) putchar('\n');
1043 if ( nresponses_psearch >= 0 )
1044 nresponses_psearch++;
1046 switch( ldap_msgtype( msg ) ) {
1047 case LDAP_RES_SEARCH_ENTRY:
1049 print_entry( ld, msg, attrsonly );
1052 case LDAP_RES_SEARCH_REFERENCE:
1054 print_reference( ld, msg );
1057 case LDAP_RES_EXTENDED:
1059 print_extended( ld, msg );
1061 if( ldap_msgid( msg ) == 0 ) {
1062 /* unsolicited extended operation */
1066 if ( cancel_msgid != -1 &&
1067 cancel_msgid == ldap_msgid( msg ) ) {
1068 printf(_("Cancelled \n"));
1069 printf(_("cancel_msgid = %d\n"), cancel_msgid);
1074 case LDAP_RES_SEARCH_RESULT:
1075 rc = print_result( ld, msg, 1 );
1076 #ifdef LDAP_CONTROL_PAGEDRESULTS
1077 if ( pageSize != 0 ) {
1078 if ( rc == LDAP_SUCCESS ) {
1079 rc = parse_page_control( ld, msg, &page_cookie );
1081 morePagedResults = 0;
1084 morePagedResults = 0;
1088 if ( ldapsync == LDAP_SYNC_REFRESH_AND_PERSIST ) {
1094 case LDAP_RES_INTERMEDIATE:
1096 ldap_parse_intermediate( ld, msg,
1097 &retoid, &retdata, NULL, 0 );
1099 nresponses_psearch = 0;
1101 if ( strcmp( retoid, LDAP_SYNC_INFO ) == 0 ) {
1102 printf(_("SyncInfo Received\n"));
1103 ldap_memfree( retoid );
1104 ber_bvfree( retdata );
1108 print_partial( ld, msg );
1109 ldap_memfree( retoid );
1110 ber_bvfree( retdata );
1114 if ( ldapsync && sync_slimit != -1 &&
1115 nresponses_psearch >= sync_slimit ) {
1116 BerElement *msgidber = NULL;
1117 struct berval *msgidvalp = NULL;
1118 msgidber = ber_alloc_t(LBER_USE_DER);
1119 ber_printf(msgidber, "{i}", msgid);
1120 ber_flatten(msgidber, &msgidvalp);
1121 ldap_extended_operation(ld, LDAP_EXOP_X_CANCEL,
1122 msgidvalp, NULL, NULL, &cancel_msgid);
1123 nresponses_psearch = -1;
1127 ldap_msgfree( res );
1132 ldap_perror( ld, "ldap_result" );
1136 ldap_msgfree( res );
1137 #ifdef LDAP_CONTROL_PAGEDRESULTS
1138 if ( pagedResults ) {
1139 npagedresponses += nresponses;
1140 npagedentries += nentries;
1141 npagedextended += nextended;
1142 npagedpartial += npartial;
1143 npagedreferences += nreferences;
1144 if ( ( morePagedResults == 0 ) && ( ldif < 2 ) ) {
1145 printf( _("\n# numResponses: %d\n"), npagedresponses );
1146 if( npagedentries ) printf( _("# numEntries: %d\n"), npagedentries );
1147 if( npagedextended ) printf( _("# numExtended: %d\n"), npagedextended );
1148 if( npagedpartial ) printf( _("# numPartial: %d\n"), npagedpartial );
1149 if( npagedreferences ) printf( _("# numReferences: %d\n"), npagedreferences );
1154 printf( _("\n# numResponses: %d\n"), nresponses );
1155 if( nentries ) printf( _("# numEntries: %d\n"), nentries );
1156 if( nextended ) printf( _("# numExtended: %d\n"), nextended );
1157 if( npartial ) printf( _("# numPartial: %d\n"), npartial );
1158 if( nreferences ) printf( _("# numReferences: %d\n"), nreferences );
1164 /* This is the proposed new way of doing things.
1165 * It is more efficient, but the API is non-standard.
1174 char tmpfname[ 256 ];
1177 BerElement *ber = NULL;
1178 struct berval bv, *bvals, **bvp = &bvals;
1179 LDAPControl **ctrls = NULL;
1182 rc = ldap_get_dn_ber( ld, entry, &ber, &bv );
1185 ufn = ldap_dn2ufn( bv.bv_val );
1186 write_ldif( LDIF_PUT_COMMENT, NULL, ufn, ufn ? strlen( ufn ) : 0 );
1188 write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1190 rc = ldap_get_entry_controls( ld, entry, &ctrls );
1191 if( rc != LDAP_SUCCESS ) {
1192 fprintf(stderr, _("print_entry: %d\n"), rc );
1193 ldap_perror( ld, "ldap_get_entry_controls" );
1194 exit( EXIT_FAILURE );
1198 print_ctrls( ctrls );
1199 ldap_controls_free( ctrls );
1204 ufn = ldap_dn2ufn( bv.bv_val );
1206 write_ldif( LDIF_PUT_VALUE, "ufn", ufn, ufn ? strlen( ufn ) : 0 );
1209 if( ufn != NULL ) ldap_memfree( ufn );
1211 if ( attrsonly ) bvp = NULL;
1213 for ( rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp );
1215 rc = ldap_get_attribute_ber( ld, entry, ber, &bv, bvp ) )
1217 if (bv.bv_val == NULL) break;
1220 write_ldif( LDIF_PUT_NOVALUE, bv.bv_val, NULL, 0 );
1222 } else if ( bvals ) {
1223 for ( i = 0; bvals[i].bv_val != NULL; i++ ) {
1224 if ( vals2tmp > 1 || ( vals2tmp &&
1225 ldif_is_not_printable( bvals[i].bv_val, bvals[i].bv_len )))
1228 /* write value to file */
1229 snprintf( tmpfname, sizeof tmpfname,
1230 "%s" LDAP_DIRSEP "ldapsearch-%s-XXXXXX",
1231 tmpdir, bv.bv_val );
1234 tmpfd = mkstemp( tmpfname );
1241 if (( tmpfp = fdopen( tmpfd, "w")) == NULL ) {
1246 if ( fwrite( bvals[ i ].bv_val,
1247 bvals[ i ].bv_len, 1, tmpfp ) == 0 )
1256 snprintf( url, sizeof url, "%s%s", urlpre,
1257 &tmpfname[strlen(tmpdir) + sizeof(LDAP_DIRSEP) - 1] );
1260 write_ldif( LDIF_PUT_URL, bv.bv_val, url, strlen( url ));
1263 write_ldif( LDIF_PUT_VALUE, bv.bv_val,
1264 bvals[ i ].bv_val, bvals[ i ].bv_len );
1267 ber_memfree( bvals );
1276 static void print_reference(
1278 LDAPMessage *reference )
1282 LDAPControl **ctrls;
1285 printf(_("# search reference\n"));
1288 rc = ldap_parse_reference( ld, reference, &refs, &ctrls, 0 );
1290 if( rc != LDAP_SUCCESS ) {
1291 ldap_perror(ld, "ldap_parse_reference");
1292 exit( EXIT_FAILURE );
1297 for( i=0; refs[i] != NULL; i++ ) {
1298 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1299 "ref", refs[i], strlen(refs[i]) );
1301 ber_memvfree( (void **) refs );
1305 print_ctrls( ctrls );
1306 ldap_controls_free( ctrls );
1310 static void print_extended(
1312 LDAPMessage *extended )
1315 char *retoid = NULL;
1316 struct berval *retdata = NULL;
1319 printf(_("# extended result response\n"));
1322 rc = ldap_parse_extended_result( ld, extended,
1323 &retoid, &retdata, 0 );
1325 if( rc != LDAP_SUCCESS ) {
1326 ldap_perror(ld, "ldap_parse_extended_result");
1327 exit( EXIT_FAILURE );
1331 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1332 "extended", retoid, retoid ? strlen(retoid) : 0 );
1334 ber_memfree( retoid );
1338 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1339 "data", retdata->bv_val, retdata->bv_len );
1341 ber_bvfree( retdata );
1344 print_result( ld, extended, 0 );
1347 static void print_partial(
1349 LDAPMessage *partial )
1352 char *retoid = NULL;
1353 struct berval *retdata = NULL;
1354 LDAPControl **ctrls = NULL;
1357 printf(_("# extended partial response\n"));
1360 rc = ldap_parse_intermediate( ld, partial,
1361 &retoid, &retdata, &ctrls, 0 );
1363 if( rc != LDAP_SUCCESS ) {
1364 ldap_perror(ld, "ldap_parse_intermediate");
1365 exit( EXIT_FAILURE );
1369 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1370 "partial", retoid, retoid ? strlen(retoid) : 0 );
1373 ber_memfree( retoid );
1377 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_BINARY,
1378 "data", retdata->bv_val, retdata->bv_len );
1381 ber_bvfree( retdata );
1385 print_ctrls( ctrls );
1386 ldap_controls_free( ctrls );
1390 static int print_result(
1392 LDAPMessage *result, int search )
1396 char *matcheddn = NULL;
1399 LDAPControl **ctrls = NULL;
1403 printf(_("# search result\n"));
1406 printf("%s: %d\n", _("search"), ldap_msgid(result) );
1410 rc = ldap_parse_result( ld, result,
1411 &err, &matcheddn, &text, &refs, &ctrls, 0 );
1413 if( rc != LDAP_SUCCESS ) {
1414 ldap_perror(ld, "ldap_parse_result");
1415 exit( EXIT_FAILURE );
1420 printf( _("result: %d %s\n"), err, ldap_err2string(err) );
1422 } else if ( err != LDAP_SUCCESS ) {
1423 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1429 write_ldif( LDIF_PUT_VALUE,
1430 "matchedDN", matcheddn, strlen(matcheddn) );
1432 fprintf( stderr, _("Matched DN: %s\n"), matcheddn );
1436 ber_memfree( matcheddn );
1442 write_ldif( LDIF_PUT_TEXT, "text",
1443 text, strlen(text) );
1445 fprintf( stderr, _("Additional information: %s\n"), text );
1449 ber_memfree( text );
1454 for( i=0; refs[i] != NULL; i++ ) {
1456 write_ldif( LDIF_PUT_VALUE, "ref", refs[i], strlen(refs[i]) );
1458 fprintf( stderr, _("Referral: %s\n"), refs[i] );
1462 ber_memvfree( (void **) refs );
1466 print_ctrls( ctrls );
1467 ldap_controls_free( ctrls );
1473 static void print_ctrls(
1474 LDAPControl **ctrls )
1477 for(i=0; ctrls[i] != NULL; i++ ) {
1478 /* control: OID criticality base64value */
1479 struct berval *b64 = NULL;
1484 len += strlen( ctrls[i]->ldctl_oid );
1486 /* add enough for space after OID and the critical value itself */
1487 len += ctrls[i]->ldctl_iscritical
1488 ? sizeof("true") : sizeof("false");
1490 /* convert to base64 */
1491 if( ctrls[i]->ldctl_value.bv_len ) {
1492 b64 = ber_memalloc( sizeof(struct berval) );
1494 b64->bv_len = LUTIL_BASE64_ENCODE_LEN(
1495 ctrls[i]->ldctl_value.bv_len ) + 1;
1496 b64->bv_val = ber_memalloc( b64->bv_len + 1 );
1498 b64->bv_len = lutil_b64_ntop(
1499 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
1500 ctrls[i]->ldctl_value.bv_len,
1501 b64->bv_val, b64->bv_len );
1505 len += 1 + b64->bv_len;
1508 str = malloc( len + 1 );
1510 strcpy( str, ": " );
1514 strcat( str, ctrls[i]->ldctl_oid );
1515 strcat( str, ctrls[i]->ldctl_iscritical
1516 ? " true" : " false" );
1520 strcat(str, b64->bv_val );
1524 write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1525 "control", str, len );
1534 write_ldif( int type, char *name, char *value, ber_len_t vallen )
1538 if (( ldif = ldif_put( type, name, value, vallen )) == NULL ) {
1542 fputs( ldif, stdout );
1543 ber_memfree( ldif );
1549 #ifdef LDAP_CONTROL_PAGEDRESULTS
1553 LDAPMessage *result,
1554 struct berval *cookie )
1558 LDAPControl **ctrl = NULL;
1559 LDAPControl *ctrlp = NULL;
1563 rc = ldap_parse_result( ld, result,
1564 &err, NULL, NULL, NULL, &ctrl, 0 );
1566 if( rc != LDAP_SUCCESS ) {
1567 ldap_perror(ld, "ldap_parse_result");
1568 exit( EXIT_FAILURE );
1571 if ( err != LDAP_SUCCESS ) {
1572 fprintf( stderr, "%s (%d)\n", ldap_err2string(err), err );
1576 /* There might be others, e.g. ppolicy... */
1577 ctrlp = ldap_find_control( LDAP_CONTROL_PAGEDRESULTS, ctrl );
1581 /* Parse the control value
1582 * searchResult ::= SEQUENCE {
1583 * size INTEGER (0..maxInt),
1584 * -- result set size estimate from server - unused
1585 * cookie OCTET STRING
1589 ber = ber_init( &ctrlp->ldctl_value );
1590 if ( ber == NULL ) {
1591 fprintf( stderr, _("Internal error.\n") );
1592 return EXIT_FAILURE;
1595 tag = ber_scanf( ber, "{io}", &entriesLeft, cookie );
1596 (void) ber_free( ber, 1 );
1598 if( tag == LBER_ERROR ) {
1600 _("Paged results response control could not be decoded.\n") );
1601 return EXIT_FAILURE;
1604 if( entriesLeft < 0 ) {
1606 _("Invalid entries estimate in paged results response.\n") );
1607 return EXIT_FAILURE;
1610 if ( cookie->bv_len == 0 ) {
1611 morePagedResults = 0;
1614 ldap_controls_free( ctrl );
1617 morePagedResults = 0;